05 December 2009

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.

1 tanggapan:

Unknown said...

tnx for your post
question: i did all procedure steps and i can connect with username and password just once.when i exit from firefox and return to enter user/pass not acccept.when i restart squidproxy server works again just for one account.what i do?