hacker


Ingresar con nombre de usuario, contraseña y duración de la sesión
| Portal Hacker | Editorial | Descargas | Ezine |
Inicio Ayuda Ingresar Registrarse
25 de Julio de 2008, 10:26:01
Noticias: Visita la nueva sección de Física y matemáticas
Para ver este enlace Registrate o Inicia Sesion
Aquí

+  Foros pOrtal Hacker
|-+  Programacion
| |-+  Desarrollo Web
| | |-+  Php (Moderador: shevchenko)
| | | |-+  seguridad al Crear Scripts en PHP
0 Usuarios y 1 Visitante están viendo este tema. « anterior próximo »
Páginas: [1] Ir Abajo Imprimir
Autor Tema: seguridad al Crear Scripts en PHP  (Leído 1206 veces)
electro-ooz
NZ2
**
Desconectado Desconectado

Mensajes: 109


ociohacks


Ver Perfil WWW
« : 27 de ſeptiembre de 2005, 02:06:16 »

Cuando hacemos un script en PHP debemos tener en cuenta 3 factores fundamentales:

- Diseño
- Funcionalidad
- Seguridad

Lo explicado está orientado a PHP 4 y 5, no se asegura su correcta funcionalidad en versiones anteriores.

Si estamos trabajando con un php que procesa la informacion de un form, y sólo necesitamos los valores que llegan por el form, es necesario indicarle a php al momento de procesar los valores, que lea solo los que le llegan por el mà   ©todo utilizado (ej. Post, Get, etc).
Para esto usamos las variables corresponiente s Ejemplo:

<?
echo $_POST["nombre"];
?>

Entonces si tenemos un form utilizando el metodo post, este php solo tomara la informacion enviados en un imput llamado nombre y lo mostrara en pantalla.
En cambio si consultamos a travà   ©s del navegador de esta forma:

http://localhost/script.php?nombre=pepe

el navegador nos devolverá una pantalla en blanco ya que para el script php, la informacion dada por la variable nombre, no fue pasada a travà   ©s de el mà   ©odo post.

Si utilizamos el metodo get, las variables seran $_GET["nombre"], etc.

Si estamos usando formularios y páginas php que procesan dicha información es muy importante limpiar lo que llega de códigos dañinos. Asà   ­, los caracteres que pueden ser usados para atacar (', ", < ,>) se transformarán en códigos sin capacidad de ataque.

Podemos usar las funciones:

* htmlentities — Convierte todos los caracteres aplicables a entidades HTML
* htmlspecialcha rs — Convierte caracteres especiales a entidades HTML
* strip_tags — Elimina marcas HTML y PHP de una cadena

Veamos un ejemplo de como usarlas:

En un formulario tenemos un input llamado nombre y un archivo php que procesa los datos. En el php, vamos a trabajar al principio del script con la variable que llega llamada $nombre, entonces veamos:

Si queremos limpiar todo caracter usamos htmlentities

<?
//Limpiar!
$nombre = htmlentities ($nombre);
?>

Si quieremos limpiar solo &, ", < , > usamos htmlspecialcha rs de la sig. forma:
<?
//limpiar todo!
$nombre = htmlspecialcha rs ($nombre);
?>

La siguente funcion mas que limpiar caracteres, lo que hace es eliminar cualquier tipo de código html o php que sea REPLACEado, como nosotros en este caso sólo queremos pasar al formulario una cadena de texto comun y corriente, no nos serviran otros caracteres, por lo tanto estos seran eliminados de la siguiente forma:

<?
//Limpiar codigo que no me sirve para nada
$nombre = strip_tags ($nombre);
?>

Es conocido que si trabajamos con base de datos MySQL o mSQL puede ser pasado código para hacer las famosas SQL injection.
Una forma de solucionar esto es aplicar lo que aprendimos anteriormente, pero tambien es muy
En línea


Para ver este enlace Registrate o Inicia Sesion
ghost
NZ2
**
Desconectado Desconectado

Mensajes: 306


Developer


Ver Perfil WWW
« Respuesta #1 : 27 de ſeptiembre de 2005, 02:15:14 »

Un buen codigo de seguridad anti-injeccion sql  Grin

Código:
<?PHP
$xa = getenv('REMOTE_ADDR');
$badwords = array(";","'","\"","union","del","DEL","REPLACE","update","drop","sele","memb","set","$","res3t","wareh","%");

foreach($_POST as $value)
  foreach($badwords as $word)
    if(substr_count($value, $word) > 0)
      die("HaHaHa!<br />Algunos Simbolos Lo Tomamos Como Hack Intenta De Nuevo [Tu -IP] ->> $xa ");

class sql_inject
{
    /**
* @shortdesc url to redirect if an sql inject attempt is detect. if unset, value is FALSE
* @private
* @type mixed
*/
    var $urlRedirect;
    /**
* @shortdesc does the session must be destroy if an attempt is detect
* @private
* @type bool
*/
    var $bdestroy_session;
    /**
* @shortdesc the SQL data currently test
* @private
* @type string
*/
    var $rq;
    /**
* @shortdesc if not FALSE, the url to the log file
* @private
* @type mixed
*/
    var $bLog;
   
    /**
* Builder
*
* @param bool bdestroy_session optional. does the session must be destroy if an attempt is detect?
* @param string urlRedirect optional. url to redirect if an sql inject attempt is detect
     * @public
* @type void
     */
    function sql_inject($mLog=FALSE,$bdestroy_session=FALSE,$urlRedirect=FALSE)
    {
        $this->bLog = (($mLog!=FALSE)?$mLog:'');
        $this->urlRedirect = (((trim($urlRedirect)!='') && file_exists($urlRedirect))?$urlRedirect:'');
        $this->bdestroy_session = $bdestroy_session;
        $this->rq = '';
    }

    /**
* @shortdesc test if there is a sql inject attempt detect
* test if there is a sql inject attempt detect
*
* @param string sRQ required. SQL Data to test
     * @public
* @type bool
     */
    function test($sRQ)
    {
        $sRQ = strtolower($sRQ);
        $this->rq = $sRQ;
        $aValues = array();
        $aTemp = array(); // temp array
        $aWords = array(); //
        $aSep = array(' and ',' or ');
        $sConditions = '(';
        $matches = array();
        $sSep = '';
        // is there an attempt to unused part of the rq?
        if (is_int((strpos($sRQ,"#")))&&$this->_in_post('#')) return $this->detect();
       
        // is there a attempt to do a 2nd SQL requete ?
        if (is_int(strpos($sRQ,';'))){
            $aTemp = explode(';',$sRQ);
            if ($this->_in_post($aTemp[1])) return $this->detect();
        }
       
        $aTemp = explode(" where ",$sRQ);
        if (count($aTemp)==1) return FALSE;
        $sConditions = $aTemp[1];
        $aWords = explode(" ",$sConditions);
        if(strcasecmp($aWords[0],'select')!=0) $aSep[] = ',';
        $sSep = '('.implode('|',$aSep).')';
        $aValues = preg_split($sSep,$sConditions,-1, PREG_SPLIT_NO_EMPTY);

        // test the always true expressions
        foreach($aValues as $i => $v)
        {
            // SQL injection like 1=1 or a=a or 'za'='za'
            if (is_int(strpos($v,'=')))
            {
                 $aTemp = explode('=',$v);
                 if (trim($aTemp[0])==trim($aTemp[1])) return $this->detect();
            }
           
            //SQL injection like 1<>2
            if (is_int(strpos($v,'<>')))
            {
                $aTemp = explode('<>',$v);
                if ((trim($aTemp[0])!=trim($aTemp[1]))&& ($this->_in_post('<>'))) return $this->detect();
            }
        }
       
        if (strpos($sConditions,' null'))
        {
            if (preg_match("/null +is +null/",$sConditions)) return $this->detect();
            if (preg_match("/is +not +null/",$sConditions,$matches))
            {
                foreach($matches as $i => $v)
                {
                    if ($this->_in_post($v))return $this->detect();
                }
            }
        }
       
        if (preg_match("/[a-z0-9]+ +between +[a-z0-9]+ +and +[a-z0-9]+/",$sConditions,$matches))
        {
            $Temp = explode(' between ',$matches[0]);
            $Evaluate = $Temp[0];
            $Temp = explode(' and ',$Temp[1]);
            if ((strcasecmp($Evaluate,$Temp[0])>0) && (strcasecmp($Evaluate,$Temp[1])<0) && $this->_in_post($matches[0])) return $this->detect();
        }
        return FALSE;
    }

    function _in_post($value)
    {
        foreach($_POST as $i => $v)
        {
             if (is_int(strpos(strtolower($v),$value))) return TRUE;
        }
        return FALSE;
    }

    function detect()
    {
        // log the attempt to sql inject?
        if ($this->bLog)
        {
            $fp = @fopen($this->bLog,'a+');
            if ($fp)
            {
                fputs($fp,"\r\n".date("d-m-Y H:i:s").' ['.$this->rq.'] from '.$this->sIp = getenv("REMOTE_ADDR"));
                fclose($fp);
            }
        }
        // destroy session?
        if ($this->bdestroy_session) session_destroy();
        // redirect?
        if ($this->urlRedirect!=''){
             if (!headers_sent())  header("location: $this->urlRedirect");
        }
        return TRUE;
    }


function protect1($protected) {
$banlist = array ("'", "\"", "<", "\\", "|", "/", "=", "REPLACE", "select", "update", "delete", "distinct", "having", "truncate", "replace", "handler", "like", "procedure", "limit", "order by", "group by", "asc", "desc");
//$banlist is the list of words you dont want to allow.
if ( eregi ( "[a-zA-Z0-9@]+", $protected ) ) {
$protected = trim(str_replace($banlist, '', $protected));
return $protected;
//echo "+";
} else {
//echo "-";
echo $protected;
die ( 'Hahaha, Intentas Inj..' );
} // ends the if ( eregi ( "[a-zA-Z0-9]+", $this->protected ) ) {
} // ends the function Protect() {

function protect2($protected) {
$banlist = array ("'", "\"", "<", "\\", "|", "/", "=", "REPLACE", "select", "update", "delete", "distinct", "having", "truncate", "replace", "handler", "like", "procedure", "limit", "order by", "group by", "asc", "desc");
//$banlist is the list of words you dont want to allow.
if ( eregi ( "[0-9]+", $protected ) ) { .
$protected = trim(str_replace($banlist, '', $protected));
return $protected;
//echo "+";
} else {
//echo "-";
echo $protected;
die ( ' Is invalid for that spot, please try a different entry.' );
} // ends the if ( eregi ( "[a-zA-Z0-9]+", $this->protected ) ) {
} // ends the function Protect() {


}
?>


Espero que les sirva, esta muy bien configurado!  Wink
En línea

Mañana te daras cuenta, que hoy, no sabes nada!

Para ver este enlace Registrate o Inicia Sesion
Páginas: [1] Ir Arriba Imprimir 
« anterior próximo »
Ir a:  


Ingresar con nombre de usuario, contraseña y duración de la sesión

Powered by SMF 1.1.5 | SMF © 2006-2008, Simple Machines LLC hacker

Juegos gratis - Articulos PHP - Juegos - Trucos - Letras - Juegos - Juegos Online