Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Clase MYSQL e Inyecciones

Estas en el tema de Clase MYSQL e Inyecciones en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Buenas Tardes, tengo una clase para realizar la conexión y consultas a la base de datos. Por ejemplo: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código PHP: Ver original <?php ...
  #1 (permalink)  
Antiguo 23/05/2011, 14:27
Avatar de McBlink  
Fecha de Ingreso: noviembre-2006
Ubicación: $ARG->LaPampa()
Mensajes: 1.694
Antigüedad: 17 años, 4 meses
Puntos: 23
Pregunta Clase MYSQL e Inyecciones

Buenas Tardes,
tengo una clase para realizar la conexión y consultas a la base de datos. Por ejemplo:

Código PHP:
Ver original
  1. <?php
  2. class MySQL{
  3.  
  4.     function MySQL(){
  5.             if(!isset($this->conexion)){
  6.                 $this->conexion = (mysql_connect($this->host,$this->user,$this->pass)) or die(mysql_error());
  7.                 mysql_select_db($this->data,$this->conexion) or die(mysql_error());
  8.             }
  9.         }
  10.        
  11.     function query($consulta) {
  12.         $resultado = mysql_query($consulta,$this->conexion);
  13.         return $resultado;
  14.     }

de forma tal que llamo a :
Código PHP:
Ver original
  1. $row = $db->query("SELECT * FROM .....");

Ahora quiero implementar un poco de seguridad a estas consultas, y estuve leyendo bastante pero no me quedo muy claro.

1- validaría los datos por GET y POST antes de realizar la consulta, con funciones como is_numeric() y demás.

2- Aplicaría la función mysql_real_escape().

tengo la duda si esta función la aplico antes de realizar la consulta o en método de la clase que lo ejecuta, en el ejemplo seria en query().
Aplicando estas dos consideraciones, estarian seguras mis consultas?


Muchas Gracias
Saludos
  #2 (permalink)  
Antiguo 23/05/2011, 14:30
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Clase MYSQL e Inyecciones

Usa PDO y con prepend, bindParam o bindValue es suficiente para prevenir inyecciones de primer grado.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #3 (permalink)  
Antiguo 23/05/2011, 14:37
Avatar de McBlink  
Fecha de Ingreso: noviembre-2006
Ubicación: $ARG->LaPampa()
Mensajes: 1.694
Antigüedad: 17 años, 4 meses
Puntos: 23
Respuesta: Clase MYSQL e Inyecciones

Gracias, pero por el momento no me interesa usar un framework para el manejo de la base de datos y además quiero hacer mi propia clase para aprender.

Saludos
  #4 (permalink)  
Antiguo 23/05/2011, 14:46
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Clase MYSQL e Inyecciones

Ehhh PDO es una libreria de PHP asi como la libreria de mysql y PDO es la recomendada al momento hasta que PHP se invente una que lea los pensamientos
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #5 (permalink)  
Antiguo 23/05/2011, 14:51
Avatar de McBlink  
Fecha de Ingreso: noviembre-2006
Ubicación: $ARG->LaPampa()
Mensajes: 1.694
Antigüedad: 17 años, 4 meses
Puntos: 23
Respuesta: Clase MYSQL e Inyecciones

Ah, OK, tenia entendido que era un Framework, le voy a dar una leída pero de te agradecería si me das tu opinión para poder implementar mi propia clase.
Gracias
  #6 (permalink)  
Antiguo 23/05/2011, 15:36
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Clase MYSQL e Inyecciones

Bueno yo tengo una clase llamada Filter
Código PHP:
Ver original
  1. <?php
  2. class Filter
  3. {
  4.     /**
  5.      * Remove XSS attacks that came in the input
  6.      *
  7.      * Function taken from:
  8.      * http://quickwired.com/smallprojects/php_xss_filter_function.php
  9.      * and alter to use in application
  10.      *
  11.      * @param string $value The value to filter
  12.      * @return string
  13.      */
  14.     public function filterXss($params, $returnStr = false)
  15.     {
  16.         $params = is_array($params)
  17.             ? $params
  18.             : array($params);
  19.  
  20.         foreach($params as $key => $val){
  21.             /**
  22.              * remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  23.              * this prevents some character re-spacing such as <java\0script>
  24.              * note that you have to handle splits with \n, \r, and \t later since
  25.              * they *are* allowed in some inputs
  26.              */
  27.             $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
  28.  
  29.             /**
  30.              * straight replacements, the user should never need these since they're normal characters
  31.              * this prevents like
  32.              * <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
  33.              */
  34.             $search = 'abcdefghijklmnopqrstuvwxyz';
  35.             $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  36.             $search .= '1234567890!@#$%^&*()';
  37.             $search .= '~`";:?+/={}[]-_|\'\\';
  38.             for($i = 0; $i < strlen($search); $i++){
  39.                 /**
  40.                  * ;? matches the ;, which is optional
  41.                  * 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  42.                  */
  43.  
  44.                 /**
  45.                  * &#x0040 @ search for the hex values
  46.                  */
  47.                 $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
  48.                 /**
  49.                  * &#00064 @ 0{0,7} matches '0' zero to seven times
  50.                  */
  51.                 $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
  52.             }
  53.  
  54.             /**
  55.              * now the only remaining whitespace attacks are \t, \n, and \r
  56.              */
  57.             $ra1 = array(
  58.                 'javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link',
  59.                 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer',
  60.                 'layer', 'bgsound', 'title', 'base'
  61.             );
  62.             $ra2 = array(
  63.                 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate',
  64.                 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste',
  65.                 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange',
  66.                 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut',
  67.                 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate',
  68.                 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
  69.                 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout',
  70.                 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture',
  71.                 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover',
  72.                 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange',
  73.                 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter',
  74.                 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange',
  75.                 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'
  76.             );
  77.             $ra = array_merge($ra1, $ra2);
  78.  
  79.             $found = true; // keep replacing as long as the previous round replaced something
  80.             while($found){
  81.                 $val_before = $val;
  82.                 for($i = 0; $i < sizeof($ra); $i++){
  83.                     $pattern = '/';
  84.                     for($j = 0; $j < strlen($ra[$i]); $j++){
  85.                         if($j > 0){
  86.                             $pattern .= '(';
  87.                             $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
  88.                             $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
  89.                             $pattern .= ')?';
  90.                         }
  91.                         $pattern .= $ra[$i][$j];
  92.                     }
  93.                     $pattern .= '/i';
  94.                     $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
  95.                     $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  96.                     if($val_before == $val){
  97.                         /**
  98.                          * no replacements were made, so exit the loop
  99.                          */
  100.                         $found = false;
  101.                     }
  102.                 }
  103.             }
  104.             $params[$key] = is_array($val)
  105.                 ? $this->filterXss($val)
  106.                 : $val;
  107.         }
  108.  
  109.         return $returnStr
  110.             ? $params[0]
  111.             : $params;
  112.     }
  113.  
  114.     /**
  115.      * Remove XSS attacks and remove tags and extra white spaces
  116.      * that came in the input before and after
  117.      *
  118.      * @param string|array $params The value to filter
  119.      * @param bool Set this if you want to return string value
  120.      * @return string|array
  121.      */
  122.     public function realEscape($params, $returnStr = false)
  123.     {
  124.         /**
  125.          * Check for XSS atacks
  126.          */
  127.         $params = $this->filterXss($params, $returnStr);
  128.  
  129.         $params = is_array($params)
  130.             ? $params
  131.             : array($params);
  132.  
  133.         foreach($params as $k => $v){
  134.             /**
  135.              * Recursive, re-send all values that are arrays
  136.              */
  137.             if(is_array($v)){
  138.                 $params[$k] = $this->realEscape($v);
  139.                 continue;
  140.             }
  141.             /**
  142.              * Decode all hexadecimal values (urldecode and html_entity_decode)
  143.              * Clean up all values (strip_tags)
  144.              * Erase all white space before and after string (trim)
  145.              */
  146.             $params[$k] = urldecode($v);
  147.             $params[$k] = html_entity_decode($params[$k]);
  148.             $params[$k] = strip_tags($params[$k]);
  149.             $params[$k] = trim($params[$k]);
  150.         }
  151.  
  152.         return $returnStr
  153.             ? $params[0]
  154.             : $params;
  155.     }
  156. }
Uso
Código PHP:
Ver original
  1. $filter = new Filter;
  2. $values = $filter->filterXss($_POST);
  3. print_r($values);
  4.  
  5. //o puedes limpiarlo así
  6. $filter = new Filter;
  7. $values = $filter->realEscape($_POST);
  8. print_r($values);
  9.  
  10. //Si quieres que te devuelva en string, indica true en el segundo parametro.
  11. $filter = new Filter;
  12. $value = $filter->filterXss($_POST['foo'], true);
  13.  
  14. //o puedes limpiarlo así
  15. $filter =  new Filter;
  16. $value = $filter->realEscape($_POST['foo'], true);
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #7 (permalink)  
Antiguo 23/05/2011, 21:57
 
Fecha de Ingreso: diciembre-2009
Ubicación: dirname(__FILE__)
Mensajes: 149
Antigüedad: 14 años, 3 meses
Puntos: 11
Respuesta: Clase MYSQL e Inyecciones

Hace tiempo yo tuve el mismo problema, intentaba implementar la clase con mysql_conect, eso ya está anticuado :)

Como dice abimaelrc, PDO es hoy por hoy la mejor librería nativa de PHP para conectarse a cualquier base de datos popular (MySQL, Oracle, etc).

Ahora, al igual como se puede crear una clase con mysql_conect y familia, se puede hacer con PDO.

Aquí deje hace un tiempo una clase con PDO, por si te interesa, esta todo explicado y en español.

Saludos.
__________________
Estreno blog ~ DesarrolladorWeb.cl :)
  #8 (permalink)  
Antiguo 24/05/2011, 02:12
Avatar de historiasdemaria  
Fecha de Ingreso: septiembre-2010
Ubicación: www
Mensajes: 433
Antigüedad: 13 años, 6 meses
Puntos: 54
Respuesta: Clase MYSQL e Inyecciones

Para evitar inyecciones SQL:
Si no usas PDO en tu clase puedes tener un metodo asi:

Código PHP:
Ver original
  1. function static quote_smart($value)
  2. {
  3. // Stripslashes
  4. $value = stripslashes($value);
  5. }
  6. // Ver si es numerico
  7.  
  8. if (!is_numeric($value)) {
  9. $value = "'" . mysql_real_escape_string($value) . "'";
  10. }
  11. return $value;
  12. }

este metodo debes llamarlo en las SQL queries

"SELECT * FROM lo_que_sea WHERE id=".SQL::quote_smart($value);

Etiquetas: clase, inyecciones, mysql
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 08:46.