In this article, guide or tutorial (call it whatever you want), you will se what the hosters and developers should do to avoid the major security risks when using a *nix system and PHP + MySQL. This do cover the basics of PHP and MySQL security and will tell you methods to avoid the most used hacking attempts.
Safe_mode
Safemode activates a couple of settings that will:
* Force PHP to check UID permission before opening files.
* Prevent some calls, such as system(), from working. This is unless safe_mode_exec_dir is set.
* Set open_basedir to allow hosters to force file access to stay within a virtual directory.
There are though ways around safe_mode. Most PHP exploits use methods to get around the safe_mode restrictions.
One tips for the hosters is to not just turn on safe_mode without knowing what the actions are. You are not safe just because you turned on safe mode.
Safe Mode has also been removed totally in PHP 6.0.
Magic quotes and addslashes()
Lot’s of people recommend the use of addslashes(). This is however a prety poor advice today when connecting to a mysql database.
To prevent SQL injections, the best thing to do is to use a combination of methods. However, the best method is definately to use PDO or mysql_real_escape_string(). As a hoster, you should quickly upgrade to the latest PHP version to encourage safer and more secure functions for the users and their software.
So - how do I know if I’m vulnerable?
If the users can do remote code execution, you are in fact lucky if you’re still alive.
How do you see if you allow this then?
One thing could be if you check if this works on your site:
$file = $_POST[‘file’]; include $file; </php> or this <pre lang="php"> $txt = $_POST[‘txt’]; eval(“echo $txt”);
Other functions that can be dangerous are fopen, fsockopen, popen and system. The last two functions are direct command execution and allows remote attackers to execude code on the system.
If you want to protect yourself against this you can as a DEVELOPER:
Control that all your $_POST and $_GET arrays are secure and that file operations such as includes/requires, eval statements and every type of file operation is validated before use.
When you write new software you should limit the use of dynamic inputs as this is the most common security whole in php scripts.
As a HOSTER you should, to provide security, disable allow_url_fopen in the php.ini, enable safe_mode and set open_basedir restrictions.
Another huge and commonly used security whole is XSS or Cross-site scripting.
This refers to HTML injections or user agent injections which can effect all types of servers. This doesn’t hurt the server itself but makes the site leak information and the users that access the website can bring their information to wrong parts, such as their credit card or password.
An insecure output can look like this:
echo $_POST['text'];
While, if you want to be atleast quite secure, you can use the function htmlentities.
Developers
* Switch off register_globals and make sure that all the variables are properly initialized.
* Take user input from correct location, ie $_POST or $_GET, rather then relying on register_globals or $_REQUEST.
* Validate user input for syntax, length and type.
* Text can only be visable after using HTML entities.
* Variables that are sent back should be URL encoded using urlencode().
Hosters
Hosters can’t configure the server to be XSS (cross site scripting) safe but can remove all applications that have XSS attacks in their history. This means that the developers has to have XSS protection or their software will not be used at all.
SQL Injections
The most common and widely used hacking attempt is to use a SQL injection.
What can the developer do to protect the site and server from any SQL injection then?
* Validate the data when having dynamic SQL queries.
* Use PDO (Included in PHP 5.1 and later)
* At least use functions like mysql_real_escape_string().
Nowadays every developer should migrate to PHP 5.1 and use PDO since it has a SAFE SQL interface wich avoid all these issues.
addslashes() is not enough to avoid injections.
The php magic quotes, which automatically adds slashes to input data on the basis of database destination, is not enough as a security method either.
Developers
* Migrate to PHP 5.1 and use PDO.
* Use mysql_real_escape_string()
* Validate the data!
* Have a .htaccess file to ensure that register_globals and magic_quotes are forced off to provide properly initialization anv validation for the inputs.
Hosters
Provide PHP 5.1 and PDO for their clients. Configure MySQL to be the most secure as possible. Users should not be granted admin privileges and the database should be running in a chroot environment to avoid as much damage as possible if a successful attack has reached.
PHP Configuration
It is quite suprising that there is no real secure PHP configuration by default. Here’s a list of settings that should be set:
* register_globals (off by default in modern PHP, should be set off)
* allow_url_fopen (enabled by default, should be set off)
* magic_quotes_gpc (on by default, should be set off)
* magic_quotes_runtime (off by default, should be set off)
* safe_mode and open_basedir (disabled by default, should be enabled and configured correctly. But be aware that safe_mode isn’t really safe and can be totally useless)
Developers should during installation test using ini_get() for common hosting mistakes such as allowing things usch as register_globals or magic_quotes_gpc.
What can the developers and hosters then do to make sure they are safe towards hacking? It’s not possible to be bulletproof in this business, but if you keep your software up to date and make sure all the common mistakes are undone you will in general be safe. Here’s a compilation of what the developers and hosters should think of when securing their scripts and systems.
Developers
* Ensure that all variables are properly initialized before use.
* Ensure that the users only can affect file operations to the degree you had in your mind creating the function.
* Ensure that your scripts are totally compatible with safe mode restrictiongs and will work under things such as suPHP.
* Move the secrets and logs out of the web roots if scripts are supposed to work on a shared hosting environment.
* Use PDO for MySQL queries.
* Validate the data with length, type and every kind of method you can think of.
Hosters
* Enable safe_mode (be aware that it though isn’t really safe and can be useless)
* Use open_basedir restrictions!
* Make sure that users have a place outside web root to store logs and secrets.
* Run PHP under a least privilege model, as a user or via use of PHPsuExec or suPHP.
Google recently released a new REST API which will replace their old SOAP API (which they haven’t given out keys for since 2006)
This is very good news for those who want to do searchqueries “server-side”.
Documentation: http://code.google.com/apis/ajaxsearch/doc…entation/#fonje
Video: http://google-code-updates.blogspot.com/20…om-outside.html
Google släppte igår ett nytt REST API som skall ersätta deras SOAP API (som de slutade att dela ut API nyckar till 2006):
Here’s some PHPcode of how to use this API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php $url = “http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Hello%20World” // sendRequest // note how referer is set manually $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, “http://www.knark.com”); $body = curl_exec($ch); curl_close($ch); // now, process the JSON string $json = json_decode($body); // now have some fun with the results… ?> |
Since PHP 5.1.2 the hash function is enabled by default. To create a sha256 hash you simply write:
hash("sha256", $data, false);
There you have your sha256 hash!
SQL injections are common nowadays and plenty of sites get hacked because of insecure database calls.
Making it bulletproof against injections is hard and will take time, but making safer calls are essential and doesn’t take that long to make.
So, what is a SQL injection?
To clearify it I will give a very easy example:
A database may look something like this:
ID | USERNAME | PASSWORD
When you make a call to that database your query can look something like this:
SELECT * FROM database_name WHERE id = '2'So far no problems.. But when you code it, it will be something like this (the insecure way):
$sql = "SELECT * FROM database_name WHERE id = '".$_POST['id']."'";
If you make that query and has a id that is “2″, there will be no problem, but if you change it to something else, you will get some problems.
What if $_POST[’id’] would contain something like: ‘ or 1=1– ?
The query would now be:
$sql = "SELECT * FROM database_name WHERE id = '' or 1=1--";
That would automaticly select the whole database since that “or 1=1″ definetly is true.
That was a very short description of what a SQL injection is so how can we now prevent without using any PDO? Using PDO may be the most secure way but requires more knowledge too.
Three lines of code will secure your code against the most known injections and will make it a lot harder to inject your site and hack it. One of this lines will take care of XSS hacking methods too:
1 2 3 | $_POST = array_map("htmlspecialchars", $_POST); # Will secure from XSS $_POST = array_map("trim", $_POST); # Remove spaces before and after posts $_POST = array_map("mysql_real_escape_string", $_POST); # Protects from most known SQL injections |
Just add these lines in the top include file and you will always have your $_POST protected from the most known SQL injections. One easy way of securing your web applications a little further.
Since a couple of Swedens largest sites got hacked and the passwords are floating across the internet, we thought writing a small guide of how to not do the same mistake as those people have done, not using any salts. So, first of all, what is a md5 hash?
MD5 stands for Message-Digest algorithm 5 and has a 128bit hash value. An MD5 hash is typically a 32-character hexadecimal number. At first, there were problems cracking MD5 hashes, but in later time there have been something called a “rainbow table” which easily can crack md5 hashes. So, what to do to protect ourself against those rainbow tables? Use something called a “salt”. The reason why you have to add salts is because lot’s of people are using words such as “mydamncatsname” or “ilovejesus” which hashes have been generated and then if you compare your databases password-hash against the generated list, you will find out which password you have in your database. If you then have a salt such as “fsjlk4u9pfs” and the hash would generate the word ilovejesusfsjlk4u9pfs or something, which is not likely at all that a dictionary will have.
So how to implement this salt then? Does it involve some tremendous programming effort? No. It’s the easiest thing you can do.
To simplify this, heres a code snippet of how a salt works.
1 2 3 4 | <?php $salt = "kfoe56"; $hash = md5($salt.$password); ?> |
That is a static salt, which is better then nothing, but not far as good as a dynamic salt. There is absolutely no reason why to use a static salt since it’s not any harder to create a dynamic salt.
A dynamic salt can be something that uses the userid or something like that. This is a pretty good example of how a dynamic salt can be used:
1 2 3 4 | <?php $salt = $userid; md5($salt.md5($password.$salt)); ?> |
The time to crack that password is by far longer then a normal hash.
So please, use some damn salt when you store your users passwords.
There are some major differences between PHP and C++. PHP is significantly less strict than C++ and it supports dynamic typich which allows you to assign values of different types to the same variable. There are also no pointers in PHP, instead you use a mechanism of references.
When you take a look on the object-oriented fact, PHP is kind of inferior to C++, but in the newer editions, PHP 5.X, PHP has started to think of it more and more.
If you compare the operators, there is a small difference there as well. In PHP you a string might return NULL if a substring is not found or 0 if the string starts with the substring. In C++ it’s not possible to distinguish 0 and Null.
One other difference is that PHP is far inferior to C++ in the aspect of performance. You shouldn’t make any complicated and sophisticated softwares with PHP since C++ is superior in the performance part. On the other hand, PHP is the standard in dynamic web page processing, which leads PHP to be almost more used then C++, therefore there are more resources available for PHP.
Ever thought of having external content in a DIV without using iframes?
Iframes are ugly and will not validate properly in strict XHTML so therefore a solution for this is needed.
The solution we will use is a very simple PHP function that will grab the content from the page and then display it properly.
So how do we replace that iframe with something else? How can we create an iframe without an iframe?
This solution is widely used as proxy-scripts around the web and it is by far the most simple.
If you’re only aiming to replace an iframe you can do it easily with the file_get_content PHP function.
1 2 3 4 5 6 7 | <?php function displaycontent($url) { $content = file_get_content($url); echo $content; } ?> |
And if you are aiming for a simple proxy-script, you can just add a str_replace command and replace all hrefs with some additional characters:
1 2 3 4 5 | function displaycontentproxy($url) { $content = file_get_content($url); $content = str_replace('href="', 'href='proxy.php?url=', $content); } |
A very simple solution to the iframe problem. Solved?
Before you comment, this is a quite lame script, however, it is quite useful as both information and other matters as well. Most people hate spamming but even though you hate it, the source code can be used as something else.
This script will spam a target site with some non existing traffic. You won’t be able to fool web analytics with this script since they will see that you’re from a single IP so there’s no reason to try.
The full source can be viewed at the bottom of this post so you don’t have to copy and extract every piece because of the comments.
Well, let’s get to the point:
In the beginning of the script, we activate error_reporting so we will get some errors written if something goes wrong:
1 2 | <?php ini_set('error_reporting', E_ALL); |
After that piece, the configuration follows. Referer, spam-location and the number of hits will be written here:
3 4 5 | $referer = "http://thereferersite.com"; // Where the traffic should be sent from $spamsite = "http://www.thespamsite.com"; // The spam site location $times = 1; // Number of times you want to traffic spam a site |
To continue this, we get the header part. Here we will have the User-agent, which referer we have and which site we have targeted:
6 7 8 | $header = "GET / HTTP/1.1\r\nHost: $spamurl\r\n"; // Start of the header $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n"; // Which useragent. XP, English, Firefox 2.0 $header .= "Referer: $referer\r\nConnection: Close\r\n\r\n"; // Which referer to use and close the connection |
When connecting with a socket you need to know which port you should pass through. PHP has a function to do this, called getservbyname. This will most likely use port 80. A full list of which service for which port is found here. We also convert the spam location site to an IP address.
9 10 | $port = getservbyname('www', 'tcp'); // Get the port to use when connecting to the www using tcp. $ip = gethostbyname($spamsite); //Gives you the IP instead of DNS |
So now we have finally got to the action part. We start with a for-loop that makes this sequence the number of times we wrote in the configuration part. After that, we create a socket with AF_INET, SOCK_STREAM and SOL_TCP.
AF_INET shows that we are using a IPv4 Internet based protocol.
SOCK_STREAM gives us a reliable, sequenced full-duplex stream which the TCP protocol are based on.
SOL_TCP basically means that we use the TCP protocol.
Then we initiates a connection using socket_connect with our socket we created and the ip address of the target site along with their www port, usually port 80.
A couple of error reports later we find the code “socket_write(..” which is a function that writes the socket with the header we have written before and the length of the buffer. This is followed up by socket_close() which just closes the connection, and then by the randomization part that just makes the script sleep for some milliseconds.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | for ($i = 1; $i <= $times; $i++) { echo "Number: $i\n"; // Create the socket! $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) echo "socket_create() failed:\n".socket_strerror($socket)."\n"; // If something fails, what? // Connect to site using the socket you created $result = socket_connect($socket, $ip, $port); if ($result < 0) echo "socket_connect() failed ($result):\n".socket_strerror($result)."\n"; // If something fails, what? socket_write($socket, $header, strlen($header)); socket_close($socket); // Closes the socket $sleep = rand (10, 70); // For randomization echo "Sleeping: $sleep\n\n"; sleep ($sleep); } ?> |
It wasn’t harder then this!
Now you can use this code to create some more funny scripts that are not lame by default (spamming is).
Remember to turn on the sockets extension in your php.ini file if you didn’t have that before. Uncomment the extension=php_sockets.dll line.
The whole source-code is here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <?php ini_set('error_reporting', E_ALL); // Give you all PHP errors reported // ////Some of the configurations // $referer = "http://thereferersite.com"; // Where the traffic should be sent from $spamsite = "http://www.thespamsite.com"; // The spam site location $times = 1; // Number of times you want to traffic spam a site // //// Now we'll write the header that should be sent // $header = "GET / HTTP/1.1\r\nHost: $siteurl\r\n"; // Start of the header $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n"; // Which useragent. XP, English, Firefox 2.0 $header .= "Referer: $referer\r\nConnection: Close\r\n\r\n"; // Which referer to use and close the connection // //// A couple of more facts before the action statrs // $port = getservbyname('www', 'tcp'); // Get the port to use when connecting to the www using tcp. $ip = gethostbyname($spamsite); //Gives you the IP instead of DNS // ////Let's spam the site with the $times number of times! // for ($i = 0; $i < $times; $i++) { echo "Number: $i\n"; // Create the socket! $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);// AF_INET means IPv4 Internet based protocols. // SOCK_STREAM = sequenced, reliable, full-duplex stream. The TCP protocol is based on this. // SOL_TCP means that TCP will be used. if ($socket < 0) echo "socket_create() failed:\n".socket_strerror($socket)."\n"; // If something fails, what? // Connect to site using the socket you created $result = socket_connect($socket, $ip, $port); if ($result < 0) echo "socket_connect() failed ($result):\n".socket_strerror($result)."\n"; // If something fails, what? socket_write($socket, $header, strlen($header)); // Writes the socket, using the header we wrote earlier and the length of the buffer socket_close($socket); // Closes the socket $sleep = rand (10, 70); // For randomization echo "Sleeping: $sleep\n\n"; sleep ($sleep); } ?> |
There are plenty of people out there searching for a script to get the alexa ranking for a site. Last time I looked I didn’t even find a free function to get the data, just some expensive solutions.
So anyway, here’s a PHP coded function we have made that collects the alexa-data with the SimpleXML function. It’s very easily coded so everyone should understand what it does. However, since it uses the SimpleXML function, it can only be used if you run PHP5. That’s a requirement.
Please give us some credit if you use the function. A comment or anything will work!
1 2 3 4 5 6 7 8 9 10 | <?php function getalexa($url){ // cdsrc.com $request_url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=".$url; $xml = simplexml_load_file($request_url) or die("feed not loading"); return $xml->SD->POPULARITY['TEXT']; } ?> |
And here’s a little description of how to use it:
11 12 13 14 | <?php echo getalexa("http://cdsrc.com"); // This would print the alexaranking of cdsrc.com ?> |
Simple huh?
SimpleXML intro:
PHP4 had one pretty big drawback when you had to use external libraries to parse XML files. PHP5 had a number of XML libraries that solve this problem and one of the easiest is SimpleXML.
To test and use the function, a XML document is needed.
In this post we will use our own sitemap, located here: http://cdsrc.com/sitemap.xml.
As we write this (the document will change in future since it’s a sitemap), the document looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="http://cdsrc.com/wp-content/plugins/google-sitemap-generator/sitemap.xsl"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/09/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://cdsrc.com/</loc> <lastmod>2007-09-10T11:31:33+00:00</lastmod> <changefreq>daily</changefreq> <priority>1.0</priority> </url> <url> <loc>http://cdsrc.com/programming/php-random-password-generator-function.html</loc> <lastmod>2007-09-10T11:31:33+00:00</lastmod> <changefreq>monthly</changefreq> <priority>0.3</priority> </url> <url> <loc>http://cdsrc.com/programming/php-and-database-space-saving-tips.html</loc> <lastmod>2007-09-09T13:06:17+00:00</lastmod> <changefreq>monthly</changefreq> <priority>0.2</priority> </url> <url> <loc>http://cdsrc.com/linux/linuxbiggerthanwindows.html</loc> <lastmod>2007-09-09T12:45:00+00:00</lastmod> <changefreq>monthly</changefreq> <priority>0.3</priority> </url> </urlset> |
The documents structure is pretty easy to understand. All URL’s has a
There are a couple of methods you can use to load the XML file, one of them are to use file_get_contents() and another one, which we will use, will be shown here:
1 2 3 4 5 6 7 8 | <?php $url_location = 'http://cdsrc.com/sitemap.xml'; $sitemap = new SimpleXMLElement($url_location,null,true); foreach($sitemap as $url) { echo "Url: {$url->loc}<br />Lastmod: {$url->lastmod}<br />Changefreq: {$url->changefreq}</br>Priority: {$url->priority}<br /><br />"; } ?> |
There are no necessary comments to this as the code is pretty simple to understand. You access the “subfields” using $url->”subfield” and the counter goes through all the posts in the whole sitemap.
If we now would execute that script, we will get this output:
Url: http://cdsrc.com/ Lastmod: 2007-09-10T11:31:33+00:00 Changefreq: daily Priority: 1.0 Url: http://cdsrc.com/programming/php-random-password-generator-function.html Lastmod: 2007-09-10T11:31:33+00:00 Changefreq: monthly Priority: 0.3 Url: http://cdsrc.com/programming/php-and-database-space-saving-tips.html Lastmod: 2007-09-09T13:06:17+00:00 Changefreq: monthly Priority: 0.2 Url: http://cdsrc.com/linux/linuxbiggerthanwindows.html Lastmod: 2007-09-09T12:45:00+00:00 Changefreq: monthly Priority: 0.3
Thats a very great and easy way of using the “new” SimpleXML PHP 5.0 function!