Preventing DOS Attacks with mod_evasive

Posted by Nessa | Tags: ,, | Posted on March 18, 2007


I recently had to deal with a guy whos VPS was constantly being hit by the same IPs over and over until the server crapped out and refused to do anything…it was royally a pain in the ass because I literally had about 10 seconds between starting up the server and having it crash again. Needless to say that those 10 seconds were spent stopping Apache to give me enough time to do a netstat -n and block the assholes who were flooding the server. I then decided to installed mod_evasive, which is a simple Apache module that monitors the amount of connections from one IP and blocks any that reach a set limit. Here’s how you do it via SSH:

tar -xvzf mod_evasive_1.10.1.tar.gz
cd mod_evasive_1.10.1
/usr/local/apache/bin/apxs -cia mod_evasive.c

Once the module is compiled, restart Apache and add this to your httpd.conf:

<IfModule mod_evasive.c>
DOSHashTableSize 3097
DOSPageCount 6
DOSSiteCount 50
DOSPageInterval 2
DOSSiteInterval 2
DOSBlockingPeriod 600

DOSHashTableSize – Size of the hash table. The greater this setting, the more memory is required – faster

DOSPageCount – Max number of requests for the same page within the ‘DOSPageInterval’ interval

DOSSiteCount – Max number of requests for a given site, uses the ‘DOSSiteInterval’ interval.

DOSPageInterval - Interval for the ‘DOSPageCount’ threshold in second intervals.

DOSSiteInterval- Interval for the ‘DOSSiteCount’ threshold in second intervals.

DOSBlockingPeriod – Blocking period in seconds if any of the thresholds are met. The user will recieve a 403 (Forbidden) when blocked, and the timer will be reset each time the site gets hit when the user is still blocked.

A good supplementary script to mod_evasive is ddos, which will send you an email whenever an IP is blocked for too many connections. It also works as a backup in case Apache gets too hammered with connections. All you have to do is:


Now you just edit /usr/local/ddos/ddos.conf .

How to Install PHP6

Posted by Nessa | Tags: ,, | Posted on February 26, 2007


This was a little experiment gone somewhat wrong, when I tried to upgrade my VPS to PHP6. I swear it worked, but I should have known that nothing supports it — WordPress just crapped out a bunch of errors. On a higher note though, it seems to be hella secure as you can no longer use magic quotes or globals, otherwise Apache will fail. So if you really want to be on the bleeding edge, here’s how you install PHP6:

I didn’t really need to install a whole bunch of stuff, but depending on how your webserver is already set up you may need to install extra dependencies, but this will become obvious during the compile.

1) Make sure your autoconf version is up to date with version 2.13 or higher:

autoconf -V

2) Install ICU…you can find your version here.

tar -xzvf icu4c-3_6-src.tgz
cd icu*/source
mkdir /usr/local/icu
./configure --prefix=/usr/local/icu && make && make install

3) Git yur PHP! You can find the latest dev release of PHP6 at Your wget and tar targets will be different, as the development version changes frequently.

tar -xvzf php6.0-200702230530.tar.gz
cd php6.0-200702230530

This will build the configuration and let you know if something is missing. Once this is complete, run the configure script…I’ve the mandatory stuff in there, but you’ll also want to include any PHP modules that you need. You may find it easier to copy this from a phpinfo file, minus the quotes.

./configure --with-apxs=/usr/local/apache/bin/apxs --prefix=/usr/local/ --with-icu-dir=/usr/local/icu

You’ll probably get build errors, which is usually due to 1) a particular module no longer being supported or 2) PHP cannot find that module’s files on the server. In this case you’ll want to see which module the configure command stops at, then either leave it out or make sure the module is compatible with the correct location specification in the configure command. For instance, I have Ming installed and this is the directive in my configure command:


Once you have a good build, you can install your PHP:

make && make install

4) Configure Apache

Usually the PHP installation with the –with-apxs switch will add the necessary entries to your httpd.conf, but if not you will need to comment out the loaders for php4/php5 and add the one for php6:

/etc/init.d/httpd restart (or whatever command you use to restart Apache)

LoadModule php5_module libexec/
AddModule mod_php6.c

Now…twenty bucks says that there is now something on the server that doesn’t work, which will be obvious with the Apache restart you just did. You’ll want to check your error logs for the obvious problems, then correct the issues in your php.ini and other files it mentions. The most common issue is with the magic quotes gpc and register globals.

If you have any third-party extensions like Zend. IonCube, or eAccelerator, you’ll need to re-install those as well.

There you have it…you now have PHP6 installed on your server…and now your apps don’t work! You can admire your work next time you try to load your site.

Be sure to make a pretty phpinfo() file to check the installation.

<?php phpinfo() ?>

How to Make a Sexy Tag Cloud with PHP and MySQL

Posted by Nessa | Tags: ,,,, | Posted on February 12, 2007


Tag CloudWell it seems that everyone has one, and I’d have to admit that a tag cloud is a good way to spice up your site a little bit. I first thought of this when setting up a friend’s site… he wasn’t using a CMS like WordPress or anything that I could find a quick tag cloud plugin for, so I figured I could probably just make my own. Well, I did and now I shall share it.

This tutorial will show you how to set up a simple tag cloud using PHP and MySQL, with a little bit of Ajax effects
Before we get started, take a quick look at the sample cloud.

Script Kiddy Killjoy

Posted by Nessa | Tags: ,, | Posted on January 22, 2007


If your site has ever been hacked, it will have most likely showed up in the zone-h database. This is the site where all the little script kiddies get together to brag about their “hacking” skills and such. Basically, whenever they deface a site they report it to zone-h, who then check to make sure they aren’t full of shizit. Well, in efforts to keep the script-kiddies from getting credit, I’ve devised discovered a way to make sure that zone-h’s bots can’t check the submissions. All you have to do is add this to your root .htaccess file:

<Files 403.shtml>
order allow,deny
allow from all

# zone-h
deny from
deny from
deny from 213.219.122.

deny from
deny from
deny from

The Basic MySQL Injection

Posted by Nessa | Tags: ,,, | Posted on January 17, 2007


Ahhhh the classic hack that doesn’t work anymore… which is why I’m posting it here. I always thought it was kind of an interesting concept but no one ever made it simple for me, so I shall do this for you.

How to do a simple MySQL Injection

Ok, so this is your basic PHP login script that asks for your username and password, which would then query the database to authenticate you:

$user = $_POST["username"];
$pass = $_POST["password"];
$query = mysql_query(“SELECT * FROM users WHERE user=’$user’ AND password=’$password’”);
$rows = mysql_fetch_row($query);
if ($rows == 0) {
die (‘Login Incorrect!’); }

Assuming that register_globals are enabled on the server, this script will work and in return use the POST variable to query the database for an already-defined row to see if both conditions are being met, which are obviously the username/password fields. If the input does not meet this requirement, then the connection dies and returns the “Login Incorrect” error. So assume I log in with the username “nessa” and the password “sexy.” The $query string will pass this command to MySQL:

$query = mysql_query("SELECT * FROM users WHERE user='nessa' AND password=" OR"=' OR '1'='1'");

Since I used the OR clause in the password field, that can leave a few possibilities up to the database to determine whether a statement is true or false. As you can see, will always be equal to , and 1 is always equal to 1, so MySQL is happy as long as these requirements are met.

So what does that tell you? You can easily replace either the username or password fields withe a or a ” OR 1 and you will have a successful login each time. Of course there are a lot more combinations that will work — you might want to check out this site:

Now seeing that this site is powered by PHP and MySQL, you probably think I’m stupid by posting this. Well quite frankly, MySQL injections are old and nearly impossible with well-scripted PHP software and good PHP environment. If you’re running a custom script or old software, here’s how you can protect your crappy software from being exploited:
Check your magic quotes setting in php.ini or .htaccess:

magic_quotes_gpc should be turned on, as this automatically slash-escapes your codes so MySQL is less likely to make a false positive. As of PHP4, this setting is enabled by default.

If you don’t want to use magic quotes, use mysql_real_escape_string():

Here’s a simple script you can use as an include to automatically escape null characters:

// Quote variable to make safe
function quote_smart($value
// Stripslashes
if (get_magic_quotes_gpc
()) {
$value = stripslashes($value
// Quote if not integer
if (!is_numeric($value
)) {
$value = “‘” . mysql_real_escape_string($value) . “‘”

And the obvious, if you’re using bundled software make sure you keep it up to date. New exploits are being found all the time, so don’t put yourself out there by not updating your shit.

Messing with PHP and MySQL

Posted by Nessa | Tags: , | Posted on January 16, 2007


This just a simple tutorial on how to connect to MySQL with PHP, as well as using a MySQL query to create simple database.

The first thing you would want to do is create the database so PHP can access it. My preferred method is through phpMyAdmin or cPanel (if your host provides this)…or you can run a simple query via MySQL command line:

USE `liquor`;
CREATE TABLE `brands` (
`brand` varchar(40),
`type` varchar(50),
INSERT INTO cars VALUES(1,'skyy','vodka');
INSERT INTO cars VALUES(2,'cpt. morgan','rum');
INSERT INTO cars VALUES(3,'ice 101','schnapps');

This code will basically create a database named “liquor” with the table “brands” that lists three of my favorite liquors in order with the type of liquor that they are. From here, you’ll want to create a database user and add it to the database with the appropriate privileges. You can usually do this in your MySQL management interface provided by your hosting company, but if not you can check this site for information on users and privileges.

Now for the PHP code, you declare your database variable and use to mysql_connect function to establish a database connection:

$db_user = "user_name";
$db_pass = "password";
$db_host = "localhost";

//connection string
$dbconn = mysql_connect($db_host, $db_user, $db_pass)
or die("Cannot connect to database");
echo "Connected to the database!<br>";

Once you’ve verified that you can connect to the database, you now need to tell PHP what table you want to work with. Let’s use the one we just created:

//select a database to work with
$selected = mysql_select_db("brands",$dbconn)
or die("Could not select liquor");

Now here’s the complex part of the code where we create a loop to pull the data from the three rows we created:

//execute the SQL query and return records
$result = mysql_query("SELECT id, brand,type FROM brands");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'brand}."

Of course, this example is just a dummy one that returns the same records we’re querying –so it’s not really useful in real life.

Once you have the information you need from the database, try to make it a habit of closing the connection. Using persistant connections can cause issues on the server and is not recommended for a live production site.

//close the connection

Radiant CMS is Gorgeous

Posted by Nessa | Tags: , | Posted on January 15, 2007


Radiant CMSIf you haven’t heard the news, Radiant CMS is finally making its presence on the internet. Of course, you wouldn’t have heard the news unless you’re a dork like me. Anyways, I thought it would be worth mentioning as this is probably one of the sexiest content management systems I’ve seen yet. But really, I just like the color. And the logo’s nice too.

Check out Chris and Luke’s sites, which are currently running Radiant with Ruby on Rails.

Installing Ruby on cPanel

Posted by Nessa | Tags: , | Posted on January 15, 2007


Here’s how to install Ruby on Rails on a cPanel system:

Update: These instructions were modified for Ruby 1.8.6, since 1.8.5 is no longer available!

First install Ruby:

tar -xvzf ruby-1.8.6.tar.gz
cd ruby-1.8.6
make install

Now, install the Gems and Rails:

tar -xvzf rubygems-0.9.0.tgz
cd rubygems-0.9.0
ruby setup.rb
gem install rails

Install Fast CGI

tar -xvzf fcgi-2.4.0.tar.gz
cd fcgi-2.4.0
make install

tar -xvzf mod_fastcgi-2.4.2.tar.gz
cd mod_fastcgi-2.4.2
/usr/local/apache/bin/apxs -o -c *.c
/usr/local/apache/bin/apxs -i -a -n fastcgi
gem install fcgi

Edit the Apache config file and add the fcgi module:

pico /usr/local/apache/conf/httpd.conf

LoadModule fastcgi_module libexec/
FastCgiIpcDir /tmp/fcgi_ipc/
AddHandler fastcgi-script .fcgi
< /IfModule>

Then restart Apache

Install RMagick and GetText:

tar -xvzf GraphicsMagick-1.1.7.tar.gz
cd GraphicsMagick-1.1.7
make install

Install MySQL for Ruby:

gem install mysql

Now make the test Installation. To do this, log in as your user (not root)

su user
cd ~
rails test
cd public_html
ln -s ../test/public/ rails
cd ../test/
chmod -Rf 777 tmp/
cd public
chmod 755 dispatch.fcgi
pico .htaccess

Now, find the line in the .htaccess that looks something like this:

RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

And change “dispatch.cgi” to “dispatch.fcgi”

To see if you’ve installed everything properly, just browse to the Rails folder:

Setting up an Access Log with PHP

Posted by Nessa | Tags: ,,, | Posted on January 14, 2007


I set this up back in July when my site was hosted with H-Insiders and I didn’t have direct access to my Apache logs. I figured that I could do this myself with a few basic PHP functions, and by doing so I was able to set up my own access log in a static text file that I could download whenever I wanted. This first example is to log unique visitors to your site as well as gather some important information about them. Here is the code:

$user = $_SERVER['PHP_AUTH_USER'];
$dtime = date('r');

if($ref == ""){
$ref = "None";
if($user == ""){
$user = "None";

$entry_line = "$dtime - IP: $ip | Agent: $agent | URL: $uri | Referrer: $ref | Username: $user n";
$fp = fopen("access_log.txt", "a");
fputs($fp, $entry_line);

Basically, this is what the code it doing:


First, we have to create a session so that the script will only log this visitor’s activity until the session expires


This snippet checks to see if there is a session variable anywhere, and there is it executes the next section of code.

$user = $_SERVER['PHP_AUTH_USER'];
$dtime = date('r');

This is where the information is collected:

HTTP_USER_AGENT logs the browser type of the visitor

REQUEST_URI logs the page request

PHP_AUTH_USER shows the login credentials used if a user is being authenticated

REMOTE_ADDR shows the IP address of the visitor

HTTP_REFERER shows where the visitor was referred from

Now, to write to the logfile we see this code:

$entry_line = "$dtime - IP: $ip | Agent: $agent | URL: $uri | Referrer: $ref | Username: $user n";
$fp = fopen("access_log.txt", "a");
fputs($fp, $entry_line);

You’ll see that the first line is simply printing out the variables defined above as labels, which can be modifed to whatever you want. fopen and fclose are simple php commands used to open and close a file, while fputs will write the variable $entry_line to the file, with $entry_line being equal to all the information collected by the script. The name of the file we are writing to is “access_log.txt” and the path in the script should reflect the location of where you want that file to be on your server.

But what if you want to bypass sessions and log every single page hit? First of all, your log file is going to become massive, but if you would like to keep more extensive logs all you have to do is exclude this code from the script:



Now you have set up a simple logging system to keep your own Apache access logs. Just make sure you set the text file location to where you want the script to write on your webserver, preferrabled somewhere outside your document root folder.

Hotlink Block

Posted by Nessa | Tags: | Posted on January 14, 2007


So I finally figured out what caused the huge bandwidth spike on my site last month.  Seems some idiot was hotlinking my MP3s and old images from the Jukebox and gallery on my previous site…I guess he’s out of luck now that they’re gone.  Anywho, for those who don’t have the luxury of cPanel, here’s a simple Apache rewrite to keep people from jacking your images and stuff:


RewriteEngine on
RewriteCond %{HTTP_REFERER} .
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site\.com [NC]
RewriteRule \.(jpe?g|gif|png|bmp|mp3)$ – [NC,F]