Thursday, January 21, 2010

Squid Proxy Authentication With PHP/MySQL

Many methods to do authentication in Squid, ie basic, ncsa, ntlm, kerberos, radius,.... But what about authenticate a user by looking in a MySQL table? More convenience if the language is PHP, as everybody language in the Web B-). So, after some quick googling results many clues, I picked one here and added some lines for data retrieval from MySQL. Here they are:

#!/usr/bin/php
mysql_connect("localhost","root","password");
if (! defined(STDIN)) {
define("STDIN", fopen("php://stdin", "r"));
}
while (!feof(STDIN)) {
$line = trim(fgets(STDIN));
$fields = explode(' ', $line);
$username = rawurldecode($fields[0]); //1738
$password = rawurldecode($fields[1]); //1738
$db=mysql("auth","select * from user where nama='$username' and passwd='$password'");
if(mysql_num_rows($db)>0){
fwrite(STDOUT, "OK\n");
} else {
// failed miserably
fwrite(STDOUT, "ERR\n");
}
}
?>

Very simple as we write. Next, chmod the script, eg auth.php with execute permission. Copy/move the script into any folder accessible by squid, just place it in /etc/squid is very well.

Edit /etc/squid/squid.conf, add the following lines:

auth_param basic program /etc/squid/auth.php
auth_param basic children 20
auth_param basic realm FKM HotSpot
auth_param basic credentialsttl 2 hours
auth_param basic casesensitive off

And allow only authenticated user:

acl AuthenticatedUsers proxy_auth REQUIRED
http_access allow AuthenticatedUsers
http_access deny all

Restart squid. One major drawback is we have to manually set the browser using the squid address and port, the authentication can't be done in a transparent proxy mode.

No comments:

Post a Comment