Friday, September 25, 2009

Php Arrays

An array is a data structure that stores one or more values in a single value.An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible

Each element in the array has its own index so that it can be easily accessed.

In PHP, there are three kind of arrays:

* Numeric array - An array with a numeric index
* Associative array - An array where each ID key is associated with a value
* Multidimensional array - An array containing one or more arrays

Numeric array
A numeric array stores each array element with a numeric index.

Example:

General:
$example=array("abc",123,"xyz","test");

In the following example we assign the index manually:
$example[0]="abc";
$example[1]=123;
$example[2]="xyz";
$example[3]="test";

we call the Indexed array as
echo $example[0] . " and " . $example[1] ;

or

foreach ($example as $i => $value) {
echo $value;
}

Associative Array
An associative array, each ID key is associated with a value.

Initializing an Associative Array

The following code creates an associative array with product names as keys and prices as values.

$prices = array( 'test1'=>100,
'test2'=>10, 'test3'=>4,'test4'=>5 );

There are different ways we can initialize the associative array

$prices = array( 'test1'=>100 );
$prices['test2'] = 10;
$prices['test3'] = 4;

Using Loops with Associative Arrays
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.

The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:

foreach ($prices as $key => $value)
echo $key.'=>'.$value.'
';

The following code lists the contents of our $prices array using the each() construct:

while( $element = each( $prices ) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value' ];
echo '
';
}

Some of the Usefull methods are:

$b = array_values($a);

This will assign the the array a to the b and b will be considered as a array.

unset($arr[5]);
This will removes the particular element in the array

Leia Mais…

Friday, September 11, 2009

Why File Upload Forms are a major security threat part2

Case 4: Double extensions (part 1)

This case’s security measures, as a concept are very similar to that one used in case 3. Though instead of simply checking the extension string present in the filename, the developer is extracting the file extension by looking for the ‘.’ character in the filename, and extracting the string after the dot character.

The method used to bypass this approach is a bit more complicated, but still realistic. First, let’s have a look at how Apache handles files with multiple extensions. A quote from the Apache manual states:

“Files can have more than one extension, and the order of the extensions is normally irrelevant. For example, if the file welcome.html.fr maps onto content type text/html and language French then the file welcome.fr.html will map onto exactly the same information. If more than one extension is given which maps onto the same type of meta-information, then the one to the right will be used, except for languages and content encodings. For example, if .gif maps to the MIME-type image/gif and .html maps to the MIME-type text/html, then the file welcome.gif.html will be associated with the MIME-type text/html.”

Therefore a file named ‘filename.php.123’, will be interpreted as a PHP file and will be executed. This only works if the last extension (in our case .123), is not specified in the list of mime-types known to the web server. Web developers, usually are not aware of such ‘feature’ in Apache, which can be very dangerous for a number of reasons. Knowing this, an attacker can upload a file named shell.php.123 and bypass the file upload form protection. The script will compute the last extension (.123), and concludes that this extension is not in the list of dangerous extension. Having said that, it is impossible to predict all the possible random extensions a malicious user will use to be able to upload a file on your web server.

Case 5: Double extensions (part 2)

A better approach to securing file upload forms is the white list approach. In this case, the developer defines a list of known/accepted extensions and does not allow extensions that are not specified in the list.

However, in some cases this approach will not work as expected. When Apache is configured to execute PHP code, there are 2 ways one can specify this: to use the AddHandler directive, or to use the AddType directive. If AddHandler directive is used, all filenames containing the ‘.php’ extension (e.g. ‘.php’, ‘.php.jpg’) will be executed as a PHP script. Therefore, if your Apache configuration file contains the following line, you may be vulnerable:

AddHandler php5-script .php

An attacker can upload a file named ‘filename.php.jpg’ and bypass the protection, and will be able to execute the code.

Case 6: Checking the image header

When images only are allowed to be uploaded, developers usually validate the image header by using the PHP function called getimagesize. When called, this function will return the size of an image. If the image validation is invalid, which means that the header is incorrect, the function will return a false. Therefore a developer typically checks if the function returns a true or false, and validate the uploaded file using this information. So, if a malicious user tries to upload a simple PHP shell embedded in a jpg file, the function will return false and he won’t be allowed to upload the file. However, even this approach can be easily bypassed. If a picture is opened in an image editor, like Gimp, one can edit the image comment, where PHP code is inserted, as shown below.



The image will still have a valid header; therefore it bypasses the getimagesize PHP check. As seen in the screen shot below, the PHP code inserted in the image comments still gets executed when the image is requested from a normal web browser:



Case 7: Protecting the upload folder with .htaccess

Another popular way of securing file upload forms, is to protect the folder where the files are uploaded using .htaccess file. The idea is to restrict execution of script files in this folder. A .htaccess file typically contains the below code when used in this kind of scenario:

AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi
Options –ExecCGI

The above is another type of blacklist approach, which in itself is not very secure. In the PHP manual, in the move_uploaded_file section, there is a warning which states ‘If the destination file already exists, it will be overwritten.’

Because uploaded files can and will overwrite the existing ones, a malicious user can easily replace the .htaccess file with his own modified version. This will allows him to execute specific scripts which can help him compromise the server.

Case 8: Client-side validation

Another common type of security used in file upload forms, is client-side validation of files to be uploaded. Typically, such approach is more common in ASP.NET applications, since ASP.NET offers easy to use validation controls.
A malicious user can easily bypass this type of validation. It is possible to write a short client side script that will do the validation instead of the script provided by the web application. Without using a web browser, the attacker can use an application that allows sending of HTTP POST requests to be able to upload the file.

Suggested Solution

Below is a list of best practices that should be enforced when file uploads are allowed on websites and web applications. These practices will help you securing file upload forms used in web applications;

*
Define a .htaccess file that will only allow access to files with allowed extensions.
*
Do not place the .htaccess file in the same directory where the uploaded files will be stored. It should be placed in the parent directory.
*
A typical .htaccess which allows only gif, jpg, jpeg and png files should include the following (adapt it for your own need). This will also prevent double extension attacks.


deny from all

<Files ~ "^\w+\.(gif|jpe?g|png)$">

order deny,allow

allow from all

</Files>

*
If possible, upload the files in a directory outside the server root.
*
Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
*
Create a list of accepted mime-types (map extensions from these mime types).
*
Generate a random file name and add the previously generated extension.
*
Don’t rely on client-side validation only, since it is not enough. Ideally one should have both server-side and client-side validation implemented.

Leia Mais…

Thursday, September 10, 2009

Why File Upload Forms are a major security threat

To allow an end user to upload files to your website, is like opening another door for a malicious user to compromise your server. Even though, in today’s modern internet web applications, it is a common requirement, because it helps in increasing your business efficiency. File uploads are allowed in social network web applications, such as Facebook and Twitter. They are also allowed in blogs, forums, e-banking sites, YouTube and also in corporate support portals, to give the opportunity to the end user to efficiently share files with corporate employees.

Users are allowed to upload images, videos, avatars and many other types of files.
The more functionality provided to the end user, the greater is the risk of having a vulnerable web application and the chance that such functionality will be abused from malicious users, to gain access to a specific website, or to compromise a server is very high.

While testing several web applications, we noticed that a good number of well known web applications, do not have secure file upload forms. Some of these vulnerabilities were easily exploited, and we could gain access to the file system of the server hosting these web applications. In this whitepaper, we present you with 8 common ways we encountered of securing file upload forms. We also show how a malicious user, can easily bypass such security measures.

Below are the sample cases:

Case 1: Simple file upload form with no validation

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

we use php code for saving the uploaded file is
* $_FILES[‘uploadedfile’][‘name’]: The original name of the file on the client machine
* $_FILES[‘uploadedfile’][‘type’]: The mime type of the file
* $_FILES[‘uploadedfile’][‘size’]: The size of the file in bytes
* $_FILES[‘uploadedfile’][‘tmp_name’]: The temporary filename in which the uploaded file was stored on the server.

In this simple example, there are no restrictions about the type of files allowed for upload and therefore an attacker can upload a PHP or .NET file with malicious code that can lead to a server compromise.

This might look like a naïve example, but we did encounter such code in a number of web applications.

Case 2: Mime Type validation

Another common mistake web developers do when securing file upload forms, is to only check for mime type returned from PHP. When a file is uploaded to the server, PHP will set the variable $_FILES[‘uploadedfile’][‘type’] to the mime-type provided by the web browser the client is using. However, a file upload form validation cannot depend on this value only. A malicious user can easily upload files using a script or some other automated application that allows sending of HTTP POST requests, which allow him to send a fake mime-type.

Case 3: Block dangerous extensions

In other cases, we encountered file upload forms using a blacklist approach, as a security measure. A list of dangerous extensions is compiled from the developer, and the access is denied if the extension of the file being uploaded is on the compiled list.

One main disadvantage of using black listing of file extensions, is that it is almost impossible to compile a list that includes all possible extensions that an attacker can use. E.g. If the code is running in a hosted environment, usually such environments allow a large number of scripting languages, such as Perl, Python, Ruby etc, and the list can be endless.

A malicious user can easily bypass such check by uploading a file called “.htaccess”, which contains a line of code similar to the below:

AddType application/x-httpd-php .jpg

The above line of code, instructs Apache web server to execute jpg images as if they were PHP scripts. The attacker can now upload a file with a jpg extension, which contains PHP code. As seen in the screen shot below, requesting a jpg file which includes the PHP command phpinfo() from a web browser, it is still executed from the web server:



Source taken from http://www.acunetix.com

Leia Mais…

Tuesday, September 8, 2009

New features in PHP 5.3 & Improvements in Object oriented concepts

Late static binding

One of the more annoying things about PHP before V5.3 is how static methods and members are dealt with. Up until now, static references, such as those made with self or __CLASS__, are resolved in the class scope in which the function was defined. The problem is that the reference would be incorrect if the class was extended and the call was made from the new child class. Late static binding has been added in PHP V5.3 to alleviate this problem. To better illustrate, let's create a class with a static method below.

Class Foo with static method test()


class Foo
{
protected static $name = 'Foo';

public static function test()
{
return self::$name;
}
}


Let's extend this class. We'll redefine the member $name in this child class.

Child class Bar that extends parent class Foo


class Bar extends Foo
{
protected static $name = 'Bar';
}


We make the static call below example.

Static method call test()


echo Bar::test();


What is output from that call would be the string Foo. This is because the self::$name reference made in the test() method is done with the Foo class. The binding occurs this way because this is where the function is defined.

PHP V5.3 has added the keyword static to allow you to make a reference against the current class. So you will change the Foo class above to use this keyword in next example, and we'll see that Bar will instead be output.

Using the static keyword


class Foo
{
protected static $name = 'Foo';

public static function test()
{
return static::$name;
}
}

class Bar
{
protected static $name = 'Bar';
}

echo Bar::test(); // outputs 'Bar'


One thing to note about the static keyword is that it doesn't work the same as how this works in the nonstatic context. This means that the normal inheritance rules do not apply to static calls. The static keyword will simply try to resolve the call in the current class instead of the class the function was defined in. This is an important thing to note.

Now that we have seen some enhancements with static methods and members, let's take a look at some new classes added to a very useful part of PHP V5: the Standard PHP Library.



Standard PHP Library


The Standard PHP Library (SPL) is a collection of interfaces and classes added in PHP V5 designed to solve standard problems. These problems include having an object be iterateable, letting an object behave as if it was an array, or implementing a linked list. The advantage of using these classes and methods is that they are native to PHP, which means they are faster than if they were implemented in PHP itself. They also, in many instances, allow many of the internal functions of PHP to use these objects directly, such as how the Iterator interface allows you to use the foreach construct to iterate over the object.

PHP V5.3 adds a few more classes to SPL. One we referenced earlier is the implementation of a doubly linked list in the SPL class SplDoublyLinkedList. It is used by two other new SPL classes: SplStack, which implements a stack, and SplQueue, which implements a queue.

Let's take a look at how you can use the SplStack class to implement a stack.

Using SplStack

$stack = new SplStack();

// push a few new items on the stack
$stack->push('a');
$stack->push('b');
$stack->push('c');

// see how many items are on the stack
echo count($stack); // returns 3

// iterate over the items in the stack
foreach ( $stack as $item )
echo "[$item],";
// the above outputs: [c],[b],[a]

// pop an item off the stack
echo $stack->pop(); // returns 'c'

// now see how many items are on the stack
echo count($stack); // returns 2


The SqlQueue works in a similar fashion, but it works like a queue would (first item in, first item out; instead of last item in, first item out, like the stack). In addition, a heap implementation exists (SplHeap), as well as specific queue and heap implementations for certain situations (SplMinHeap, SplMaxHeap, and SplPriorityQueue).

Another useful addition is the SplFixedArray class, which, as the name implies, is a fixed-size array implementation. It is, however, rather fast — actually so fast that it's been benchmarked to be 10-30 percent faster than the built-in array implementation in PHP. This speedup is due to the fact that the array is a fixed size, not a variable-sized one like the default PHP one is, and that non-numeric indexes are not allowed. Listing 10 shows how it's used.

SplFixedArray

$array = new SplFixedArray(3);
$array[0] = 'dog';
$array[1] = 'cat';
$array[2] = 'bird';
$a->setSize(4); // increase the size on the fly
$array[3] = 'mouse';
foreach ( $array as $value )
echo "[$value],";

Output:
[dog],[cat],[bird],[mouse]


In addition, a few new iterator classes have been added: FilesystemIterator and GlobIterator. These work the same as the other iterator classes in PHP, but they are specially designed for certain instances.

One other change with SPL is that it is always enabled now in PHP V5.3. In previous versions of PHP V5, you could disable SPL at compile time, but as of PHP V5.3, this is no longer possible.

The new additions to SPL add some useful functionality to PHP that is easy to use, as well as implementations of data structures, such as doubly linked lists, stacks, heaps, and queues. These classes can be used to replace user space implementations you may have, which will gain increased speed and better integration with various PHP functions and constructs.

Now that we have seen some new additions to SPL, let's see how OOP in PHP V5.3 has gained an important performance and memory usage improvement with the addition of circular garbage collection.



Circular garbage collection

One problem PHP developers run into from a performance standpoint is garbage collection. PHP has a pretty simple garbage collector, which basically will garbage collect an object when it no longer is in scope. The way it does this internally is by using a reference counter, so that when the counter reaches zero (meaning no more references to this object are available), the object will be garbage collected and expunged from memory.

This works fairly well, but can become a problem in situations where one object references another in a parent-child relationship. In this situation, the reference counter for those object are not collected, so the memory used by these objects stays in unreferenced memory and is not unallocated until the end of the request. Let's take a look at an example of when this problem occurs.

Parent-child class relationship not properly garbage collected in PHP V5.2 and earlier

class Parent
{
public function __construct()
{
$this->child = new Child($this);
}
}

class Child
{
public function __construct(
Parent $parent
)
{
$this->parent = $parent;
}
}


In this instance, every time you create an instance of the Parent class and then subsequently the instance goes out of scope, the memory is never released, so the script will grow and grow in memory usage. There are a few user space solutions to this problem, such as creating a destructor for the parent class that will release the child object directly. This destructor would have to be called specifically before unsetting the parent class reference. While doing all of this works, it complicates your code quite a bit.

In PHP V5.3, the garbage collector will detect these circular references and is able to free up the memory used by them, so the PHP memory usage will remain flat as the script is executed. As each reference to the Parent class is removed, the Child class reference inside the Parent class will also be garbage collected.

This article is taken from https://www.ibm.com/

Leia Mais…

New features in PHP 5.3

Comparing to the PHP previous version php5.3 has many improved features. There are so many changes in the object interface.Php5.3 added several needed improvements, such as class visibility, proper constructors and destructors, type hinting, and a class-reflection API. It opened the door for advanced objected-oriented programming in PHP, and allowed you to implement many design patterns much easier, along with better design classes and APIs.

Improved static method and member handling
One useful addition made in PHP V5 was the ability to specify a method or member of a class as static. PHP 4 did support static access to methods and members of class, but not the ability to specify that the method or member is designed for static access. Static access is especially useful for implementing the singleton design pattern, where only one instance of class exists.

PHP5.3 has added several features to enhance the support for static members and methods within a class. A newly added magic method: __callStatic().

The _callStatic() magic method

PHP V5 has several specially defined methods that can be used inside classes known as magic methods. When defined in the class, these methods provide special functionality, and enable overloading (the ability to allow a method to accept different types of parameters) and polymorphism (the ability to allow different data types to use the same interface). They also open the door to using different types of OOP programming methods and design patterns with PHP easily.

In PHP V5.3, a new magic method is added: __callStatic(). This works similar to the __call() magic method, which is designed to handle method calls for methods that aren't defined or visible in the class. However, __callStatic() is designed for handling static method calls, which gives us the ability to better design our method overloading. An example of how to use this method is below.


class Foo
{
public static function __callStatic(
$name,
$args
)
{
echo "Called method $name statically";
}

public function __call(
$name,
$args
)
{
echo "Called method $name";
}
}

Foo::dog(); // outputs "Called method dog statically"
$foo = new Foo;
$foo->dog(); // outputs "Called method dog"

Dynamic static calls

One nice feature of PHP is variable variables. What this means is you can use the string value of a variable to specify the name of another variable. In other words, you could do something like what is shown below.

Variable variables

$x = 'y';
$$x = 'z';
echo $x; // outputs 'y'
echo $y; // outputs 'z'
echo $$x; // outputs 'z'


The same concept can be used with functions, or even class methods, as shown below.

Variable function and class method names


class Dog
{
public function bark()
{
echo "Woof!";
}
}

$class = 'Dog'
$action = 'bark';
$x = new $class(); // instantiates the class 'Dog'
$x->$action(); // outputs "Woof!"


New to PHP V5.3 is the ability to have the name of the class when specified be a variable when making a static call. This opens up a few new possibilities, as shown below.


Variable class naming


class Dog
{
public static function bark()
{
echo "Woof!";
}
}

$class = 'Dog';
$action = 'bark';
$class::$action(); //outputs "Woof!"


This addition makes the variable-variables feature of PHP complete, allowing them to be used in just about every situation with PHP.

This article is taken from https://www.ibm.com/

Leia Mais…

Monday, September 7, 2009

How To Install Apache 2.0/PHP 4.3 and MySQL 5.0 on Redhat

* Uninstall previous versions of apache and mysql

rpm -e httpd mysql

* Download and install RPM packages of MySQL's server, client and dynamic shared libraries from mysql.com. do not opt to change the password on MySQL database unless you know what you're doing (I don't). If requested at first installation attempt, download the appropriate version of perl-dbi from rpmfind.net.

rpm -ivh MySQL-client-5.0.20-0.glibc23.i386.rpm MySQL-server-5.0.20-0.glibc23.i386.rpm MySQL-shared-5.0.20-0.glibc23.i386.rpm

* Initialize mysql database after installation by typing..

mysql_install_db

* Make sure /etc/ld.so.conf contains:

/usr/lib

* Run ldconfig

/sbin/ldconfig

* Download, unpack, and install Apache 2.0 from source at apache.org

mv httpd-2.0.55.tar.gz /usr/local/; cd /usr/local/
tar -xzvf httpd-2.0.55.tar.gz
cd httpd-2.0.55
./configure --enable-so
make
make install

* Ensure Apache functions properly by starting, testing, and stopping it.

/usr/local/apache2/bin/apachectl start
http://localhost/

/usr/local/apache2/bin/apachectl stop

* Download, unpack, and install the newest 4.4.x version of PHP from php.net

mv php-4.4.1.tar.gz /usr/local/; cd /usr/local/
tar -xzvf php-4.4.1.tar.gz; cd php-4.4.1/
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
make
make install

* Add the following to your httpd.conf file:

LoadModule php4_module modules/libphp4.so
AddType application/x-httpd-php .php .phtml
AddType application/x-httpd-php-source .phps

* Modify httpd.conf again, and then restart the httpd (/usr/local/apache2/bin/apachectl restart):

DirectoryIndex index.html index.php

* To test your accomplishments, drop the following text into an index.php file within your DocumentRoot directory:

< ?php
phpinfo();
?>

Leia Mais…