PHP Generate Random Passwords

This is a small script written in PHP which will help you to generate N passwords of N length in less than 1ms 😛

Make sure you have PHP installed, then copy this code to a file called randompass.php

#!/usr/bin/php -q
<?
// no i,l,o keep passwords easy
$chars = "abcdefghjkmnpqrstuvwxyz0123456789";
$passlen = (intval($argv[1])? intval($argv[1]):6);
$passnum = (intval($argv[2])? intval($argv[2]):1);

echo "Generating $passnum passwords of $passlen letters/numbers\n";
// feed the random God :P
srand(((int)((double)microtime()*1000003)));

for ($i=1;$i<=$passnum;$i++) _gen_pass();

function _gen_pass() {
  global $chars, $passlen;
  $cnt = 1;
  while ($cnt <= $passlen) {
    $myrand = rand() % 33;
    $tmp = substr($chars, $myrand, 1);
    if (rand(0,1)) $tmp = strtoupper($tmp);
    $pass = $pass . $tmp;
    $cnt++;
  }
  echo $pass . "\n";
}

?>

Now you have the file don’t forget to make it executable:

chmod +x randompass.php

How it works? See some examples:

Usage: ./randompass.php [password_length] [password_number]

# The default execution will drop 1 password of 6 letters/numbers
./randompass.php
Generating 1 passwords of 6 letters/numbers
9hBEq1

# want 5 passwords of 12 letters/numbers ?
./randompass.php 12 5
Generating 5 passwords of 12 letters/numbers
ug5Tj8fP3w26
Tn9fnSjy2PmJ
NRqC6m8J0svn
YFQ6g3WnHH8r
ds56SnQvsBEq

That’s all, use it for what you need, don’t try to break it or find stupid bugs 😛

Easy RRDtool Install (1.2.27)

As you should know RRDtool is the OpenSource industry standard, high performance data logging and graphing system for time series data. Use it to write your custom monitoring shell scripts or create whole applications using its Perl, Python, Ruby, TCL or PHP bindings.

This post will guide you to setup RRDtool 1.2.27 on your Linux server without pain 😉 I have tested this configuration on CentOS 4,5, RHEL 3,4

Before you start make sure you install the following apps:

  • libart_lgpl-2.3.16-3
  • libart_lgpl-devel-2.3.16-3
  • zlib-1.2.1.2-1.2
  • zlib-devel-1.2.1.2-1.2
  • freetype-2.1.9-6.el4
  • freetype-devel-2.1.9-6.el4
  • libpng-1.2.7-3.el4_5.1
  • libpng-devel-1.2.7-3.el4_5.1

Use the power of yum to get them on your system… if you ran into trouble then you shouldn’t continue unless you get someone to fix your mess 😛

Now, you need to download and install RRDtool

cd /usr/local/src
wget http://oss.oetiker.ch/rrdtool/pub/rrdtool-1.2.27.tar.gz
tar -zxf rrdtool-1.2.27.tar.gz
cd rrdtool-1.2.27
./configure --disable-tcl
# if you get an error while configuring make sure you read
# what caused that, and try to fix it
make
make install
ln -s /usr/local/rrdtool-1.2.27/bin/rrdtool /usr/bin/rrdtool
ln -s /usr/local/rrdtool-1.2.27/bin/rrdupdate /usr/bin/rrdupdate
ln -s /usr/local/rrdtool-1.2.27/bin/rrdcgi /usr/bin/rrdcgi

Was that hard? I don’t think so, actually it was pretty easy and now you can start coding your own graphs 😀

You need to start diggin’ the Tutorials, Documentation and Wiki provided by Tobias Oetiker in order to start with your own cool graphs, and remember, RRDtool is FREE and if it helps you and saves you time/money you should really consider make Tobi happy 😉

I’ll be posting later some basic examples for RRDtool graphs and other scripts, be patient 🙂

IP updater for EditDNS.net

As anyone know (and should know) EditDNS it’s the best alternative for DNS Management and the best of all it is FREE 😉

Here I wrote/adapted some code which will allow you to update your dynamic IP through EditDNS’s API.

Requirements:

  • You need to register first! (duh)
  • Donations are optional, but if it makes your life easier you should consider it and you’ll also get more services.
  • Perl!

File: editdns.pl

#!/usr/bin/perl

use strict;

## Configure ONLY this 2 variables
my $editdns_pass   = "a"; # put your password
my $editdns_record = "b"; # put the record you wish to update

## ###############
## Nothing else should be changed unless you know what to do
## ###############

my $host = "DynDNS.EditDNS.net";
my $port = 80;
my $editdns_post = "p=$editdns_pass&r=$editdns_record";

my $editdns_req = join("",
  "POST /api/dynLinux.php HTTP/1.0\r\n",
  "Host: $host:$port\r\n",
  "User-Agent: EditDNS Browser 0.1\r\n",
  "Referer: http://www.editdns.net\r\n",
  "Content-Type: application/x-www-form-urlencoded\r\n",
  "Content-Length: ".length($editdns_post)."\r\n\r\n",
  "$editdns_post\n"
);

my $hostaddr = (gethostbyname($host))[4] || &error("Couldn't get IP for $host");
my $remotehost= pack('S n a4 x8',2,$port,$hostaddr);
socket(S,2,1,6) || &error("Couldn't create socket");
connect(S,$remotehost) || &error("Couldn't connect to $host:$port");
select((select(S),$|=1)[0]);
print S $editdns_req;
vec(my $rin='',fileno(S),1)= 1 ;
select($rin,undef,undef,60) || &error("No response from $host:$port");
undef($/);
close(S);
print "[DONE]\n";
exit;

sub error {
        print "[ERROR] $_[0]\n";
        exit;
}

Next and once you have configured the script:

chmod +x editdns.pl
pico /etc/crontab
# Add editdns.pl to execute every 15 minutes
*/15 * * * * root /path/editdns.pl > /dev/null 2>&1

Do not set intervals lower than 15 minutes, since it can be considered as an abuse and you’ll get banned.

Part of this code was taken from James Marshal, happy coding!

*** If you are looking for SSL support and multiple records you might want to check http://xux.in/blog/post/php-editdns-updater-for-linux/

Monitor open ports using PHP (snippet)

How can you really know if a port is open or closed? Most of the scripts around the web fail doing it’s job, not because they are wrong but because they are not doing their job as they should.

Am I on drugs? No, not now 😉 basicly, what all scripts do is:

[root@local]# telnet yourhost port

That will tell you if yourhost is open on that port but sometimes it will just hang there, why? there are many reasons why a server or service could hang (I’m not covering that part … at least not for free :P), but the only thing you really need to know is, IT HAPPENS… when? how? why? it will.

So, if you are in the middle of coding some script that let’s you monitor your servers / services without worrying about that “small particular issue”, you are in the right place, check out the code:

function check_port($ip="",$port="",$request="",$replies="") {
  if (!$ip || !$port) {
    echo "No ip/port to check";
	  return;
  }
	if (!($fp = @fsockopen($ip,$port,$junk,$junk,10)) {
	  echo "Connection DOWN!";
		return;
	}
	if (!$request && !$replies) {
	  echo "Connection UP! (open socket)";
		return;
	}
	if ($request) {
	  fputs($fp,$request,strlen($request));
		fputs($fp,"\r\n\r\n",8);
	}
	stream_set_timeout($fp,10);
	do {
		$response .= fgets($fp);
	} while (!feof($fp));
	@fclose($fp);
	$response = preg_replace("/\n|\r/","",$response);
	$result = false;
	$error = $response;
	$array_replies = explode(",",$replies);
	if (is_array($array_replies)) {
	  foreach ($array_replies as $v) {
		  if (!$v) continue;
			if (preg_match("/$v/i",$response)) {
			  $result = true;
                          break;
			}
		}
	}
	if ($result) {
	  echo "Connection UP!";
		return;
	}
	echo "Connection error: $response");
	return;
}

That’s a mess! Yes I know, it is dirty and uggly but it works. That function takes 4 arguments, $ip (server’s IP), $port (server’s port), $request and $replies (you can use comma delimited here in case you need to receive one or more answers).

How it works? Well copy that piece of code to any php file and call it this way:

// This first example will tell us if google.com is up ;)
// it sends the request "HEAD / HTTP/1.0" to the IP 72.14.207.99 on the port 80
// and expects 2 answers: "200" or "OK"
check_port("72.14.207.99",80,"HEAD / HTTP/1.0","200,OK");
// it sends the request "HEAD / HTTP/1.0" to the IP 72.14.207.99 on the port 80
// and expects 2 answers: "200" or "OK"

// another example?
check_port("148.235.52.179",110,"","\+OK");
// this one will check port 110 (pop3) on that IP, it won't send a request but
// it will sit till gets a "\+OK"

Remember, all requests and replies depends on the server’s side, be aware of that 😉

mod_security 2 for Ensim X CentOs 4.6

ModSecurity is a great application which will help you to prevent attacks (including injections) to your webserver. On this article I’ll cover the installation of ModSecurity 2.5.1 on CentOS 4.6 with Apache2 running Ensim X.

First you need to meet the requirements:

  • libxml2
  • libxml2-devel
  • httpd-devel
  • apr-devel
  • apr-util-devel
  • pcre-devel

You can use yum in order to install/upgrade the mentioned packages.

Once you met the requirements you can go and download mod_security from here.

wget http://www.modsecurity.org/download/modsecurity-apache_2.5.1.tar.gz
tar -zxvf modsecurity-apache_2.5.1.tar.gz
cd modsecurity-apache_2.5.1/apache2
./configure
make
make install

By now mod_security should be installed on your system and we are just 1 step away from glory. You need to modify your apache config’s file /etc/httpd/conf/httpd.conf (backup your config first!!!).

Edit your /etc/httpd/conf/httpd.conf file and locate the LoadModule’s section (DSO) and at the following lines:

# load libxml2.so before any other module
LoadFile /usr/lib/libxml2.so
# here goes the rest of the default modules, I'm only pasting a few as an example
LoadModule access_module modules/mod_access.so
LoadModule auth_module modules/mod_auth.so .........
# and at the end add the lines needed for mod_security
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so
Include conf/modsecurity/*.conf

We are almost done, we have mod_security installed and Apache configured to load mod_security. If you noticed, the last line we added (Include conf/modsecurity/*.conf) makes reference to the default rules mod_security includes in another file modsecurity-core-rules_2.5-1.6.0.tar.gz

cd /usr/local/src
wget http://www.modsecurity.org/download/modsecurity-core-rules_2.5-1.6.0.tar.gz
mkdir /etc/httpd/conf/modsecurity
cd /etc/httpd/conf/modsecurity
tar -zxvf /usr/local/src/modsecurity-core-rules_2.5-1.6.0.tar.gz
service httpd restart

If you didn’t get any error/warning check your logs just to make sure apache restarted without issues. If no errors then that means you’ve succesfully installed mod_security on your server hurray! 🙂

Take note that mod_security 2 has it’s default rules which are completely different than mod_security 1, you are free to go to /etc/httpd/conf/modsecurity and change/add rules according to your needs, and I highly recommend you to read ModSecurity documentation before doing that.

I took the best of the following sites to bring you this small HOWTO:

http://www.eth0.us/mod_security
http://carrero.es/instalar-modsecurity-2-en-plesk/1374

That’s all for today, I’m outta here 😉