This code is a beta release of the authentication class I’ve been developing for some time. Expect this page to be fairly dynamic while I complete it and work out the last of the ‘features’.
It’s now easily extendable and I’ve included an extended include file as well as the main class file. Granted I still have some work to do on making the authentication functions themselves simple enough to extend without any challenges. (And then of course to document them.)
Please feel free to contact me if you’re planning on trying it out. Use the contact form on the left. For the moment I’m more than happy to work with people on getting it running in a grander effort to ensure it’s 100% ready.
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
<? require 'phpauth.class'; Class Auth extends PHPAuth { // The following parameters should be set to match // your database and server. public $session_name = '***'; protected $dbhost = '***'; protected $database = '***'; protected $dbuser = '***'; protected $dbpass = '***'; protected $dbusertable = '***'; public $reqlogin = 0; public $retainrequest = 0; public $promptlogin = 'http://www.domain.dom/loginform.html'; public $postlogin = ''; public $postlogout = 'http://www.domain.dom'; public $postfailure = 'http://www.domain.dom/authfailed.html'; public $accessdenied = 'http://www.domain.dom/403.html'; public $reqperm = 0; protected $debug = 0; } $auth = new Auth(); if(isset($postlogin) && is_string($postlogin)) $auth->postlogin = $postlogin; if(isset($retainrequest) && $retainrequest) $auth->retainrequest = 1; $auth->setup_login(); $auth->showsetup(); $auth->start_login(); ?> phpauth.class <? /* * * Copyright (C) 2005 James Bly * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Version 0.91.1 * * Todo (by priority): * Make auth function calls easily extendable * Fix timeouts * Get rid of postgres error messages in dbstatus * Check all calls under request() for possible injection points * Add line number to all log messages * Add comments to all functions/variables * Configuration flag to enforce SSL auth * * WARNING: This code is beta and shouldn't be used for * production purposes. It also might have holes and security * issues as only a cursory review has been done prior to its * release. Use it at your own risk. * */ class PHPAuth { // Variable holders for the current page and session protected $sessid = ''; protected $sess_timeout = 20; protected $auth_timeout = 20; public $reqlogin = 0; public $retainrequest = 0; public $promptlogin = ''; public $postlogin = ''; public $postlogout = ''; public $postfailure = ''; public $accessdenied = ''; public $reqperm = 0; protected $timeout = 1200; // 20 minute (1200 second) timeout private $phpauthaction = ''; // login, logout, etc private $instance = 0; private $action = ''; private $requested = ''; // The following parameters should be set to match // your database and server. protected $session_name = 'extend this class!'; protected $dbhost = 'extend this class!'; protected $database = 'extend this class!'; protected $dbuser = 'extend this class!'; protected $dbpass = 'extend this class!'; protected $dbusertable = 'extend this class!'; protected $debug = 0; // added calls to self::logger if set to 2, just comment info if 1 private $special = array(); // For tracking special debug messages in showsetup() private $logauth = 1; private $conn = null; // holder for the database connection private $authkey = ''; private $authuser = ''; private $authpass = ''; // Variable holders for the server settings private $method = ''; private $host = ''; private $file = ''; private $params = array(); function __construct() { $this->instance = rand(1000,9999); self::debug("__construct", "start for instance %s", $this->instance); self::get_vars(); // setup all the variables that auth needs self::debug("__construct", "received request for %s", $this->requested); if(!self::checkrequired()) // check that required details are present { self::logger("checkrequired - requirements not met"); exit("phpauth requirements not met"); } error_reporting(E_ALL); } public function setup_login() { self::authsession(); // startup the session if($this->reqlogin && !$this->getuser()) $this->action = 'login'; } public function start_login() { if(strlen($this->action) > 0) switch($this->action) { case 'login': if(!$this->authuser || !$this->authpass) { self::debug("__construct", "finish for instance %s, sending to promptlogin", $this->instance); self::redirect("promptlogin", array('redirect'=> urlencode($_SESSION['requested']))); exit; } else { self::dologin($this->authuser, $this->authpass); self::debug("__construct", "dologin returned %s for %s", $this->authkey, $this->authuser); if(!$this->authkey || strlen($this->authkey) <= 0) { self::debug("__construct", "finish for instance %s, sending to postfailure", $this->instance); self::debug("__construct", "-------------------------------------------------------"); self::debug("__construct", "authentication failed for user: %s", $this->authuser); self::redirect("postfailure"); exit; } else { self::debug("__construct", "setting up authenticated session"); $_SESSION['authkey'] = $this->authkey; $_SESSION['authuser'] = $this->authuser; self::debug("__construct", "finish for instance %s, sending to postlogin", $this->instance); self::debug("__construct", "-------------------------------------------------------"); if(self::is_key("redirect", $_SESSION) && $_SESSION['redirect']) { self::debug("__construct", "postlogin redirecting to session redirect"); $redir = self::request_session("redirect"); session_unregister("redirect"); self::redirect($redir); } else { self::debug("__construct", "postlogin redirecting to supplied redirect"); self::redirect($this->postlogin); } exit; } } break; case 'logout': self::dologout($this->authuser); self::debug("__construct", "construct finish for instance %s, logout completed", $this->instance); self::debug("__construct", "-------------------------------------------------------"); exit; break; default: self::debug("__construct", "Unknown authentication: %s", $this->action); self::debug("__construct", "construct finish for instance %s, action request failure", $this->instance); self::debug("__construct", "-------------------------------------------------------"); exit("Unknown authentication: " . $this->action); break; } if(self::is_key("authkey", $_SESSION) && self::is_key("authuser", $_SESSION)) { if(self::validateauth($_SESSION['authuser'], $_SESSION['authkey'])) { self::updateauth($_SESSION['authuser'], $_SESSION['authkey']); if(self::getperm($_SESSION['authuser']) < $this->reqperm) { self::debug("__construct", "%s failed required permissions level for %s", $this->authuser, $this->file); self::debug("__construct", "construct finish for instance %s, sending to accessdenied", $this->instance); self::debug("__construct", "-------------------------------------------------------"); if($this->accessdenied) self::redirect("accessdenied"); else self::redirect(sprintf("%s://%s", $this->method, $this->host)); exit; } } else { self::debug("__construct", "construct finish for instance %s, forcing logout", $this->instance); self::dologout($_SESSION['authuser']); } } self::debug("__construct", "construct finish for instance %s, reached end", $this->instance); self::debug("__construct", "-------------------------------------------------------"); } private function dologin($user, $pass, $case = 0) { switch($case) { case '1'; break; case '2': $user = strtolower($user); $pass = strtolower($pass); break; default: $user = strtolower($user); break; } self::dbconnect(); if(self::dbstatus()) { $sql = sprintf("select id,lower(userid),password from %s where lower(userid) = '%s'", $this->dbusertable, $user); self::debug("dologin", "calling dbquery(%s)", $sql); $data = self::dbquery($sql); self::dbclose(); $x = count($data); if($x > 1) { self::logger(sprintf("dologin error: dbquery returned more than one match for %s", $user)); return 0; } else if ($x == 0) { self::logger(sprintf("dologin error: dbquery cannot find user %s", $user)); return 0; } $dbpass = $data[0]['password']; if(preg_match("/(md5|sha1)?:?(.*)/", $dbpass, $matches)) { if($matches[1] == '') $matches[1] = 'md5'; $hashmeth = $matches[1]; $truehash = $matches[2]; } $hashpass = self::mkhashpass($pass, $hashmeth); if($hashpass == $truehash) { self::debug("dologin", "authentication successful for %s", $user); $this->authkey = self::genauthkey(); $sql = sprintf("update %s set authkey = '%s', timeexp = %d, lastauth = %d where lower(userid) = '%s'", $this->dbusertable, $this->authkey, time() + $this->timeout, time(), $user); self::debug("dologin", "calling dbquery(%s)", $sql); self::dbquery($sql); self::debug("dologin", "setting authkey to %s", $this->authkey); if($this->logauth) self::logger(sprintf("authentication successful for %s", $user)); return $this->authkey; } return 0; } } private function dologout() { if(self::is_key("authkey", $_SESSION) && self::is_key("authuser", $_SESSION)) { self::dbconnect(); $sql = sprintf("update %s set authkey = '' where lower(userid) = '%s'", $this->dbusertable, $_SESSION['authuser']); self::debug("dologout", "calling dbquery(%s)", $sql); self::dbquery($sql); self::dbclose(); if($this->logauth) self::logger(sprintf("authentication logout for %s", $_SESSION['authuser'])); session_unregister('authkey'); session_unregister('authuser'); } if($this->postlogout) self::redirect("postlogout"); else self::redirect(sprintf("%s://%s", $this->method, $this->host)); } public function getperm($userid = 0) { if(!$userid) $userid = self::getuser(); $sql = sprintf("select permissions from %s where lower(userid) = '%s'", $this->dbusertable, $userid); self::debug("getperm", "calling dbquery(%s)", $sql); $data = self::dbquery($sql); if($data < 1) return -1; else return $data[0]["permissions"]; } private function updateauth($userid, $authkey) { $sql = sprintf("update %s set timeexp = %d, authkey = '%s' where lower(userid) = '%s'", $this->dbusertable, (time() + $this->timeout), $authkey, $userid); self::debug("updateauth", "calling dbquery(%s)", $sql); self::dbquery($sql); } private function validateauth($userid, $authkey) { $opendb = 0; if(!self::dbstatus()) $opendb = 1; if($opendb) self::dbconnect(); $sql = sprintf("select id from %s where lower(userid) = '%s' and authkey = '%s'", $this->dbusertable, $userid, $authkey); self::debug("validateauth", "calling dbquery(%s)", $sql); $data = self::dbquery($sql); if(count($data) < 1) return 0; self::updateauth($userid, $authkey); if($opendb) self::dbclose(); return 1; } public function getuser() { if(self::is_key("authuser", $_SESSION)) return $_SESSION['authuser']; else return null; } private function dbconnect() { $constr = sprintf("host=%s port=5432 dbname=%s user=%s password=%s", $this->dbhost, $this->database, $this->dbuser, $this->dbpass); if(!self::dbstatus()) $this->conn = pg_connect($constr); if(!self::dbstatus()) self::logger("dbconnect: connection failed"); } private function dbclose() { if(self::dbstatus()) pg_close($this->conn); } private function dbstatus() { error_reporting(E_ALL ^ E_WARNING); if(pg_connection_status($this->conn) === PGSQL_CONNECTION_OK) { self::debug("dbstatus", "connection ok"); error_reporting(E_ALL); return 1; } else { self::debug("dbstatus", "connection failed"); error_reporting(E_ALL); return 0; } } private function dbquery($sql) { $data = array(); $opendb = 0; if(!self::dbstatus()) $opendb = 1; if($opendb) self::dbconnect(); if(!self::dbstatus()) { self::debug("dbquery", "can't find connection"); return null; } $result = pg_query($this->conn, $sql); self::debug(sprintf("dbquery", "check status: %s", pg_connection_status($this->conn))); $data = pg_fetch_all($result); if($opendb) self::dbclose(); return $data; } public function get_settings() { return array('promptlogin' => $this->promptlogin, 'postlogin' => $this->postlogin, 'postfailure' => $this->postfailure, 'accessdenied' => $this->accessdenied, 'reqperm' => $this->reqperm, 'phpauthaction' => $this->phpauthaction); } private function redirect($where, $vars = array()) { $split = 1; self::debug("redirect", "sending to %s with vars:\n%s", $where, var_export($vars, 1)); if(!$where) { self::debug("redirect", "received null where value"); exit; } if(self::is_prop($where)) { if(strstr($this->$where, "?")) $split = 0; $qs = self::query_string($vars, array(), $split); self::debug(sprintf("redirect", "is_prop: sending %s%s", $this->$where, $qs)); header("Location: " . $this->$where . $qs); } else { if(strstr($where, "?")) $split = 0; $qs = self::query_string($vars, array(), $split); self::debug(sprintf("redirect", "not is_prop: sending %s%s", $where, $qs)); header(sprintf("Location: %s", $where . $qs)); } } private function is_prop($what) { if(in_array($what, array('promptlogin', 'postlogin', 'postlogout', 'postfailure', 'accessdenied', 'reqperm', 'phpauthaction', 'instance', 'reqlogin', 'action'))) return true; return false; } private function rebuildrequest($uri, $params = array()) { $uri .= self::query_string($params, array("phpauth")); return $uri; } private function query_string($vars = array(), $filter = array(), $split = 1) { $uri = ''; $final = array(); $x = count($vars); if($x == 0) return $uri; if($split) $uri .= '?'; else $uri .= '&'; foreach(array_keys($vars) as $p) { if(in_array($p, $filter)) { self::debug("query_string", "filtering out %s", $p); continue; } $final[$p] = $vars[$p]; } $uri .= http_build_query($final); self::debug("query_string", "built %s", $uri); return $uri; } public function mkhashpass($password, $hash = 'md5', $header = 0) { switch($hash) { case 'md5': return sprintf("%s%s", ($header)?'md5:':'', bin2hex(mhash(MHASH_MD5, $password))); case 'sha1': return sprintf("%s%s", ($header)?'sha1:':'', bin2hex(mhash(MHASH_SHA1, $password))); } } private function request($item, $len = 0, $regex = '') { $data = ''; if(isset($_GET[$item])) $data = ($len)?substr($_GET[$item], 0, $len):$_GET[$item]; if(isset($_POST[$item])) $data = ($len)?substr($_POST[$item], 0, $len):$_POST[$item]; if(strlen($regex) && !preg_match($regex, $data)) return FALSE; if($data) return $data; return FALSE; } private function request_session($item, $len = 0, $regex = '') { $data = ''; if(isset($_SESSION[$item])) $data = ($len)?substr($_SESSION[$item], 0, $len):$_SESSION[$item]; if(strlen($regex) && !preg_match($regex, $data)) return FALSE; if($data) return $data; return FALSE; } private function checkrequired() { return 1; // alls well that ends well - holder } public function showsetup($return = 0) { $settings = array(); $settings['special'] = $this->special; $settings['get_settings'] = self::get_settings(); $settings['reqlogin'] = $this->reqlogin; $settings['retainrequest'] = $this->retainrequest; $settings['reqperm'] = $this->reqperm; $settings['timeout'] = $this->timeout; $settings['phpauthaction'] = $this->phpauthaction; $settings['action'] = $this->action; $settings['requested'] = $this->requested; $settings['session_name'] = $this->session_name; $settings['dbhost'] = $this->dbhost; $settings['database'] = $this->database; $settings['dbuser'] = $this->dbuser; $settings['dbpass'] = $this->dbpass; $settings['dbusertable'] = $this->dbusertable; $settings['authkey'] = $this->authkey; $settings['authuser'] = $this->authuser; $settings['authpass'] = $this->authpass; $settings['SESSION'] = $_SESSION; $settings['COOKIE'] = $_COOKIE; $settings['SERVER'] = $_SERVER; if($return) return $settings; else printf("<!--\n%s\n-->", var_export($settings, 1)); } private function get_vars() { $qs = array(); if($_SERVER['SERVER_PORT'] == 443) $this->method="https"; else $this->method="http"; $this->host = $_SERVER['SERVER_NAME']; $this->file = preg_replace("/(.*)\?.*/", "$1", $_SERVER['REQUEST_URI']); parse_str($_SERVER['QUERY_STRING'], $qs); self::debug("get_vars", "parse_str provides: %s for %s", var_export($qs, 1), $_SERVER['QUERY_STRING']); $this->requested = sprintf("%s://%s%s%s", $this->method, $this->host, $this->file, self::query_string($qs, array("phpauth", "as"), 1)); self::debug("get_vars", "set requested: %s", $this->requested); $this->authuser = strtolower(self::request("authuser", 60, '/^[A-Za-z0-9\@\.\-]*$/')); $this->authpass = self::request("authpass", 40); } private function authsession() { if(is_array($_COOKIE) && in_array('sessid', array_keys($_COOKIE))) $this->sessid = $_COOKIE['sessid']; if(strlen($this->sessid) < 32) { $this->sessid = self::genauthkey(); setcookie("sessid", $this->sessid); session_id($this->sessid); session_set_cookie_params(60*$this->sess_timeout, '/', $this->host, 0); } session_name($this->session_name); session_start(); $_SESSION['sessid'] = $this->sessid; $_SESSION['testkey'] = self::genauthkey(); $_SESSION['requested'] = $this->requested; $this->action = self::request("phpauth", 30, '/^[A-Za-z]*$/'); if(self::is_key("authkey", $_SESSION)) $this->authkey = self::request_session("authkey", 40, '/^[A-Za-z0-9]*$/'); if(self::is_key("authuser", $_SESSION)) $this->authuser = self::request_session("authuser", 40, '/^[A-Za-z0-9\@\.\-]*$/'); self::debug("authsession", "set SESSION to: " . var_export($_SESSION, 1)); if(!$this->retainrequest && self::is_key('requested', $_SESSION) && $_SESSION['requested']) { $_SESSION['redirect'] = self::request_session("requested"); } else if(!$this->retainrequest && $this->postlogin) { $_SESSION['redirect'] = $this->postlogin; } } public function genauthkey() { $ip = $_SERVER['REMOTE_ADDR']; $seed = rand(100000000,999999999); return bin2hex(mhash(MHASH_MD5, $ip . $seed)); } public function is_key($needle = '', $haystack = array()) { if(is_array($haystack) && strlen($needle) > 0 && count($haystack) > 0) if(in_array($needle, array_keys($haystack))) return true; else return false; else return false; } public function plogger($message) { self::logger("public $message"); } private function logger($message) { //syslog(LOG_NOTICE, sprintf("phpauth[%s]: %s", $this->instance, $message)); //file_put_contents("/tmp/authout.log", sprintf("phpauth[%s]: %s\n", $this->instance, $message), FILE_APPEND); array_push($this->special, $message); } private function debug() { if($this->debug < 2) return; $a = func_get_args(); $fn = sprintf("%s():", array_shift($a)); $f = array_shift($a); self::logger(vsprintf(sprintf("%-20s%s", $fn, $f), $a)); } } ?> |