Foros del Web » Programando para Internet » PHP »

(fixear) Corregir sql vulnerable php

Estas en el tema de (fixear) Corregir sql vulnerable php en el foro de PHP en Foros del Web. hola quisiera que me ayudaran a reparar este problema no parece difícil pero no conozco mucho de sql y de php asi que no se ...
  #1 (permalink)  
Antiguo 06/05/2013, 10:55
 
Fecha de Ingreso: octubre-2011
Mensajes: 11
Antigüedad: 12 años, 5 meses
Puntos: 0
Pregunta (fixear) Corregir sql vulnerable php

hola quisiera que me ayudaran a reparar este problema no parece difícil pero no conozco mucho de sql y de php asi que no se como reparar estas vulnerabilidades se trata de un plugin que notificaron vulnerable a inyecciones sql aqui esta explicado
[URL="http://www.ebanyu.com.ar/2013/03/wordpress-comment-rating-plugin-2932.html"]http://www.ebanyu.com.ar/2013/03/wordpress-comment-rating-plugin-2932.html[/URL]
y no lo quiero cambiar porque ya tengo un tiempo usandolo pero tampoco me quiero exponer
este es el codigo del archivo y en la url muestra donde estan la vulnerabilidades
Código PHP:
<?php
    
/*
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    */

require_once('../../../wp-config.php');
require_once(
'../../../wp-includes/functions.php');

// CSRF attack protection. Check the Referal field to be the same
// domain of the script

$k_id strip_tags($wpdb->escape($_GET['id']));
$k_action strip_tags($wpdb->escape($_GET['action']));
$k_path strip_tags($wpdb->escape($_GET['path']));
$k_imgIndex strip_tags($wpdb->escape($_GET['imgIndex']));

// prevent SQL injection
if (!is_numeric($k_id)) die('error|Query error');

$table_name $wpdb->prefix 'comment_rating';
$comment_table_name $wpdb->prefix 'comments';

if(
$k_id && $k_action && $k_path) {
    
//Check to see if the comment id exists and grab the rating
    
$query "SELECT * FROM `$table_name` WHERE ck_comment_id = $k_id";
    
$result mysql_query($query);

    if(!
$result) { die('error|mysql: '.mysql_error()); }
    
   if(
mysql_num_rows($result))
    {
      
$duplicated 0;  // used as a counter to off set duplicated votes
      
if($row = @mysql_fetch_assoc($result))
      {
         
// Handle proxy with original IP address
         
$ip getenv("HTTP_X_FORWARDED_FOR") ? getenv("HTTP_X_FORWARDED_FOR") : getenv("REMOTE_ADDR");
         if(
strstr($row['ck_ips'], $ip)) {
            
// die('error|You have already voted on this item!'); 
            // Just don't count duplicated votes
            
$duplicated 1;
            
$ck_ips $row['ck_ips'];
         }
         else {
            
$ck_ips $row['ck_ips'] . ',' $ip// IPs are separated by ','
         
}
      }
        
      
$total $row['ck_rating_up'] - $row['ck_rating_down'];
      if(
$k_action == 'add') {
         
$rating $row['ck_rating_up'] + $duplicated;
         
$direction 'up';
         
$total $total $duplicated;
      }
      elseif(
$k_action == 'subtract')
      {
         
$rating $row['ck_rating_down'] + $duplicated;
         
$direction 'down';
         
$total $total $duplicated;
      } else {
            die(
'error|Try again later'); //No action given.
      
}
        
      if (!
$duplicated)
      {
         
$query "UPDATE `$table_name` SET ck_rating_$direction = '$rating', ck_ips = '" $ck_ips  "' WHERE ck_comment_id = $k_id";
         
$result mysql_query($query); 
         if(!
$result)
         {
            
// die('error|query '.$query);
            
die('error|Query error');
         }
          
         
// Now duplicated votes will not 
         
if(!mysql_affected_rows())
         {
            die(
'error|affected '$rating);
         }
         
         
$karma_modified 0;
         if (
get_option('ckrating_karma_type') == 'likes' && $k_action == 'add') {
            
$karma_modified 1$karma $rating;
         }
         if (
get_option('ckrating_karma_type') == 'dislikes' && $k_action == 'subtract') {
            
$karma_modified 1$karma $rating;
         }
         if (
get_option('ckrating_karma_type') == 'both') {
            
$karma_modified 1$karma $total;
         }

         if (
$karma_modified) {
            
$query "UPDATE `$comment_table_name` SET comment_karma = '$karma' WHERE comment_ID = $k_id";
            
$result mysql_query($query); 
            if(!
$result) die('error|Comment Query error');
         }

         
// Invalidate the W3 cache by triggering the global wordpress action hook for an edited comment
         
do_action("edit_comment"$k_id);
      }
   } else {
        die(
'error|Comment doesnt exist'); //Comment id not found in db, something wrong ?
   
}
} else {
    die(
'error|Fatal: html format error');
}

// Add the + sign, 
if ($total 0) { $total "+$total"; }

//This sends the data back to the js to process and show on the page
// The dummy field will separate out any potential garbage that
// WP-superCache may attached to the end of the return.
echo("done|$k_id|$rating|$k_path|$direction|$total|$k_imgIndex|dummy");
?>
aqui puden descargar el plugin por si acaso
[URL="http://www.cyber-knowledge.net/blog/extras/comment-rating-2.9.32.zip"]http://www.cyber-knowledge.net/blog/extras/comment-rating-2.9.32.zip[/URL]
gracias de antemano
  #2 (permalink)  
Antiguo 06/05/2013, 11:07
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 15 años, 11 meses
Puntos: 2534
Respuesta: fixear sql vulnerable php

¿Necesitas que alguien use su tiempo y esfuerzo para haga el trabajo de analizar el problema y el código para que te explique lo que debes hacer con precisión o para que te haga el trabajo?

Como sea creo que tu tema está violando las normas del foro, te sugiero leerlas.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 06/05/2013, 11:22
 
Fecha de Ingreso: octubre-2011
Mensajes: 11
Antigüedad: 12 años, 5 meses
Puntos: 0
Respuesta: fixear sql vulnerable php

Cita:
Iniciado por pateketrueke Ver Mensaje
¿Necesitas que alguien use su tiempo y esfuerzo para haga el trabajo de analizar el problema y el código para que te explique lo que debes hacer con precisión o para que te haga el trabajo?

Como sea creo que tu tema está violando las normas del foro, te sugiero leerlas.

no se porque dises eso lo unico que esto pidiendo es ayuda el enalisis del problema esta en la url que deje como dije desconosco mucho de sql solo quiero una solucion al ploblema del inyeccion sql que no lo veo dificil si me equivoco mis disculpas, e leido que usando mysql_real_escape_string() se pude arreglar pero no se como implementarlo soble las reglas no esto seguro si las esto violando pero este plugin como dije ya lo reportaron en difrentes sitios como vulnerable y yo lo esto usando en mi web por lo que me perocupa ,solo esto pidieno ayuda como cualquier otro tema .
  #4 (permalink)  
Antiguo 06/05/2013, 14:18
Avatar de Nemutagk
Colaborador
 
Fecha de Ingreso: marzo-2004
Ubicación: México
Mensajes: 2.633
Antigüedad: 20 años
Puntos: 406
Respuesta: fixear sql vulnerable php

mysql_real_escape_string() en ningún momento es para evitar inyección SQL, lo unico que hace es escapar las comillas, si quieres algo seguro lo mejor es que dejes de usar mysql y uses mysqli o mejor aun PDO, con cualquiera de las 2 usando prepare() y bind_param() te aseguras de que estas mas protegido contra inyección SQL
__________________
Listo?, tendría que tener 60 puntos menos de IQ para considerarme listo!!!
-- Sheldon Cooper
http://twitter.com/nemutagk
PD: No contestaré temas vía mensaje personal =)
  #5 (permalink)  
Antiguo 06/05/2013, 14:25
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 4 meses
Puntos: 2658
Respuesta: fixear sql vulnerable php

Cita:
Iniciado por mauto Ver Mensaje
no se porque dises eso lo unico que esto pidiendo es ayuda el enalisis del problema esta en la url que deje como dije desconosco mucho de sql solo quiero una solucion al ploblema del inyeccion sql que no lo veo dificil si me equivoco mis disculpas, e leido que usando mysql_real_escape_string() se pude arreglar pero no se como implementarlo soble las reglas no esto seguro si las esto violando pero este plugin como dije ya lo reportaron en difrentes sitios como vulnerable y yo lo esto usando en mi web por lo que me perocupa ,solo esto pidieno ayuda como cualquier otro tema .
Básicamente lo que te quieren decir es:
1) No hacemos trabajos ajenos. Ayudamos a que aprendan a hacerlo.
2) Si quieres encargarlo a otro, hay un foro dedicado precisamente a ofertas de trabajo.
3) Si quieres que te ayudemos, entonces muestra qué analisis del tema hiciste, qué supones que tienes que hacer, y qué parte no entiendes cómo hacer.
4) No vamos a instalar algo para resolverte el inconveniente. Para eso lo instalaste tu y si necesitas ayuda para comprender cómo funciona, debes decirno lo que hiciste, y lo que no pudiste hacer.

O sea: empieza por explicar con tranquilidad y paciencia qué pruebas realizaste, que cosas no te resultan claras, y concretamente qué es lo que quieres lograr.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #6 (permalink)  
Antiguo 06/05/2013, 17:09
 
Fecha de Ingreso: octubre-2011
Mensajes: 11
Antigüedad: 12 años, 5 meses
Puntos: 0
Respuesta: fixear sql vulnerable php

¿y algo como esto podria prevenirlo?
Cita:
function clean_injection($ck_ips)
{
$ck_ips = strip_tags($ck_ips);
$ck_ips = mysql_real_escape_string($ck_ips);
return $ck_ips;
}
$query = "UPDATE `$table_name` SET ck_rating_$direction = '$rating', ck_ips = '" .clean_injection($ck_ips). "' WHERE ck_comment_id = $k_id";
  #7 (permalink)  
Antiguo 06/05/2013, 17:32
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 4 meses
Puntos: 2658
Respuesta: fixear sql vulnerable php

Una muy buena idea es empezar leyendo las recomendaciones que expresa el Manual de PHP: Inyección de SQL

¿Ya lo habías pensado?

Otra muy buena opción es no inventar la rueda de nuevo. hay muchísimos artículos sobre el tema.

Ver artículos de SQL injection

Lo siento, no pude evitarlo.

A nive de bases de datos, una de las mejores soluciones es jamás enviar consultas, sino usar stored procedures. Como los SP sólo aceptan parámetros, y los parámetros sólo ingresan como valores a las consultas internas, no pueden alterarlas. Solamente pueden devolver resultados nulos.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #8 (permalink)  
Antiguo 06/05/2013, 17:42
 
Fecha de Ingreso: octubre-2011
Mensajes: 11
Antigüedad: 12 años, 5 meses
Puntos: 0
Respuesta: fixear sql vulnerable php

bueno gracias de todas formas vere que hago
  #9 (permalink)  
Antiguo 06/05/2013, 18:33
 
Fecha de Ingreso: octubre-2011
Mensajes: 11
Antigüedad: 12 años, 5 meses
Puntos: 0
Respuesta: (fixear) Corregir sql vulnerable php

bueno segui los consejos y hice esto
Cita:
$query = sprintf("UPDATE `$table_name` SET ck_rating_$direction = '$rating', ck_ips = '".$ck_ips. "' WHERE ck_comment_id = %s",mysql_real_escape_string($k_id));
no se si funcione pero espero que si
  #10 (permalink)  
Antiguo 06/05/2013, 18:37
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 13 años, 11 meses
Puntos: 461
Respuesta: (fixear) Corregir sql vulnerable php

fijate las recomendaciones que da triby en este post
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way

Etiquetas: html, mysql, select, sql
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 09:58.