tbauth.php3 22.4 KB
Newer Older
1 2
<?php
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
3
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5 6 7
# All rights reserved.
#
#
8
# Login support: Beware empty spaces (cookies)!
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
# These global are to prevent repeated calls to the DB. 
#
$CHECKLOGIN_STATUS		= -1;
$CHECKLOGIN_UID			= 0;
$CHECKLOGIN_NOLOGINS		= -1;

#
# New Mapping. 
#
define("CHECKLOGIN_NOSTATUS",		-1);
define("CHECKLOGIN_NOTLOGGEDIN",	0);
define("CHECKLOGIN_LOGGEDIN",		1);
define("CHECKLOGIN_TIMEDOUT",		2);
define("CHECKLOGIN_MAYBEVALID",		4);
define("CHECKLOGIN_STATUSMASK",		0x000ff);
define("CHECKLOGIN_MODMASK",		0xfff00);
#
# These are modifiers of the above status fields. They are stored
# as a bit field in the top part. This is intended to localize as
# many queries related to login as possible. 
#
define("CHECKLOGIN_NEWUSER",		0x00100);
define("CHECKLOGIN_UNVERIFIED",		0x00200);
define("CHECKLOGIN_UNAPPROVED",		0x00400);
define("CHECKLOGIN_ACTIVE",		0x00800);
define("CHECKLOGIN_USERSTATUS",		0x00f00);
define("CHECKLOGIN_PSWDEXPIRED",	0x01000);
define("CHECKLOGIN_FROZEN",		0x02000);
define("CHECKLOGIN_ISADMIN",		0x04000);
define("CHECKLOGIN_TRUSTED",		0x08000);
define("CHECKLOGIN_CVSWEB",		0x10000);
42
define("CHECKLOGIN_ADMINOFF",		0x20000);
43
define("CHECKLOGIN_WEBONLY",		0x40000);
44
define("CHECKLOGIN_PLABUSER",		0x80000);
45

46 47 48
#
# Constants for tracking possible login attacks.
#
49 50
define("DOLOGIN_MAXUSERATTEMPTS",	8);
define("DOLOGIN_MAXUSERWAITTIME",	100);	# Seconds
51 52 53
define("DOLOGIN_MAXIPATTEMPTS",		8);
define("DOLOGIN_MAXIPWAITTIME",		120);	# Seconds

54 55 56 57 58 59 60 61 62
#
# Generate a hash value suitable for authorization. We use the results of
# microtime, combined with a random number.
# 
function GENHASH() {
    $fp = fopen("/dev/urandom", "r");
    if (! $fp) {
        TBERROR("Error opening /dev/urandom", 1);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
63
    $random_bytes = fread($fp, 128);
64 65 66 67 68 69
    fclose($fp);

    $hash  = mhash (MHASH_MD5, bin2hex($retval) . " " . microtime());
    return bin2hex($hash);
}

70 71 72
#
# Return the value of the currently logged in uid, or null if not
# logged in. Basically, check the browser to see if its sending a UID
73
# and HASH back, and then check the DB to see if the user is really
74 75 76 77 78 79
# logged in.
# 
function GETLOGIN() {
    if (($uid = GETUID()) == FALSE)
	    return FALSE;

80 81
    $check = CHECKLOGIN($uid);

82
    if ($check & (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_MAYBEVALID))
83 84 85 86 87 88 89 90 91 92 93
	    return $uid;

    return FALSE;
}

#
# Return the value of the UID cookie. This does not check to see if
# this person is currently logged in. We just want to know what the
# browser thinks, if anything.
# 
function GETUID() {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
94
    global $TBNAMECOOKIE;
Chad Barb's avatar
 
Chad Barb committed
95
    global $nocookieuid;
96

Leigh B. Stoller's avatar
Leigh B. Stoller committed
97
    $curname = FALSE;
Chad Barb's avatar
 
Chad Barb committed
98

Leigh B. Stoller's avatar
Leigh B. Stoller committed
99 100 101
    # XXX - nocookieuid is sent by netbuild applet in URL.
    if (isset($_GET['nocookieuid'])) {
	$curname = $_GET['nocookieuid'];
Chad Barb's avatar
 
Chad Barb committed
102
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
103 104 105 106 107
    elseif (isset($_COOKIE[$TBNAMECOOKIE])) {
	$curname = $_COOKIE[$TBNAMECOOKIE];
    }
    else
	return FALSE;
Chad Barb's avatar
 
Chad Barb committed
108

Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
    # Verify valid string (no special chars like single/double quotes!).
Leigh B. Stoller's avatar
Leigh B. Stoller committed
110 111 112 113
    # We do not use the standard check function here, since we want to
    # avoid a DB access on each page until its required. Thats okay since
    # since we just need to ensure that we feed to the DB query is safe.
    if (! preg_match("/^[-\w]+$/", $curname)) {
Chad Barb's avatar
 
Chad Barb committed
114 115
	return FALSE;
    }
116 117 118
    return $curname;
}

119
#
120
# Verify a login by sucking a UIDs current hash value out of the database.
121 122 123
# If the login has expired, or of the hashkey in the database does not
# match what came back in the cookie, then the UID is no longer logged in.
#
124
# Returns a combination of the CHECKLOGIN values above.
125
#
126
function CHECKLOGIN($uid) {
127
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $HTTP_COOKIE_VARS, $TBAUTHTIMEOUT;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
128
    global $CHECKLOGIN_STATUS, $CHECKLOGIN_UID;
Chad Barb's avatar
 
Chad Barb committed
129
    global $nocookieauth;
130 131 132 133 134 135 136
    #
    # If we already figured this out, do not duplicate work!
    #
    if ($CHECKLOGIN_STATUS != CHECKLOGIN_NOSTATUS) {
	return $CHECKLOGIN_STATUS;
    }
    $CHECKLOGIN_UID = $uid;
137

Chad Barb's avatar
 
Chad Barb committed
138 139 140 141 142 143 144 145
    # for java applet, we can send the key in the $auth variable,
    # rather than passing it is a cookie.
    if (isset($nocookieauth)) {
	$curhash = $nocookieauth;
    } else {
	$curhash = $HTTP_COOKIE_VARS[$TBAUTHCOOKIE];
    }
    
146 147 148 149
    #
    # Note that we get multiple rows back because of the group_membership
    # join. No big deal.
    # 
150
    $query_result =
151
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout, ".
152 153
		     "       status,admin,cvsweb,g.trust,adminoff,webonly, " .
		     "       plab_user " .
154 155
		     " from users as u ".
		     "left join login as l on l.uid=u.uid ".
156
		     "left join group_membership as g on g.uid=u.uid ".
157
		     "where u.uid='$uid'");
158

159
    # No such user.
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    if (! mysql_num_rows($query_result)) { 
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
    
    #
    # Scan the rows. All the info is duplicate, except for the trust
    # values. 
    #
    $trusted = 0;
    while ($row = mysql_fetch_array($query_result)) {
	$expired = $row[0];
	$hashkey = $row[1];
	$timeout = $row[2];
	$status  = $row[3];
	$admin   = $row[4];
	$cvsweb  = $row[5];

	if (! strcmp($row[6], "project_root") ||
	    ! strcmp($row[6], "group_root")) {
	    $trusted = 1;
	}
182 183
	$adminoff = $row[7];
	$webonly  = $row[8];
184
	$plab     = $row[9];
185
    }
186 187 188 189

    #
    # If user exists, but login has no entry, quit now.
    #
190 191 192 193
    if (!$hashkey) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
194

195
    #
196
    # Check for frozen account. Might do something interesting later.
197
    #
198
    if (! strcmp($status, TBDB_USERSTATUS_FROZEN)) {
199
	DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
200 201
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
202 203
    }

204
    #
205 206
    # Check for expired login. It does not matter if the cookie matches,
    # kill the entry anyway so the user is officially logged out.
207
    #
208
    if (time() > $timeout) {
209 210 211 212 213 214
	DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
	$CHECKLOGIN_STATUS = CHECKLOGIN_TIMEDOUT;
	return $CHECKLOGIN_STATUS;
    }

    #
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    # We know the login has not expired. The problem is that we might not
    # have received a cookie since that is set to transfer only when using
    # https. However, we do not want the menu to be flipping back and forth
    # each time the user uses http (say, for documentation), and so the lack
    # of a cookie does not provide enough info to determine if the user is
    # logged in or not from the current browser. Also, we want to allow for
    # a user to switch browsers, and not get confused by getting a uid but
    # no valid cookie from the new browser. In that case the user should just
    # be able to login from the new browser; gets a standard not-logged-in
    # front page. In order to accomplish this, we need another cookie that is
    # set on login, cleared on logout.
    #
    if (isset($curhash)) {
	#
	# Got a cookie (https).
230
	#
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	if ($curhash != $hashkey) {
	    #
	    # User is not logged in from this browser. Must be stale.
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
	else {
            #
	    # User is logged in. Update the time in the database.
	    # Basically, each time the user does something, we bump the
	    # logout further into the future. This avoids timing them
	    # out just when they are doing useful work.
            #
	    $timeout = time() + $TBAUTHTIMEOUT;
246 247 248 249

	    DBQueryFatal("UPDATE login set timeout='$timeout' ".
			 "WHERE uid='$uid'");

250 251
	    $CHECKLOGIN_STATUS = CHECKLOGIN_LOGGEDIN;
	}
252 253
    }
    else {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
	#
	# No cookie. Might be because its http, so there is no way to tell
	# if user is not logged in from the current browser without more
	# information. We use another cookie for this, which is a crc of
	# of the real hash, and simply tells us what menu to draw, but does
	# not impart any privs!
	#
	$hashhash = $HTTP_COOKIE_VARS[$TBLOGINCOOKIE];
	
	if (isset($hashhash) &&
	    $hashhash == bin2hex(mhash(MHASH_CRC32, $hashkey))) {
            #
            # The login is probably valid, but we have no proof yet. 
            #
	    $CHECKLOGIN_STATUS = CHECKLOGIN_MAYBEVALID;
	}
	else {
	    #
	    # No hash of the hash, so assume no real cookie either. 
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
277 278 279
    }

    #
280
    # Now add in the modifiers.
281
    #
282 283 284 285
    if ($expired)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PSWDEXPIRED;
    if ($admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISADMIN;
286 287
    if ($adminoff)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ADMINOFF;
288 289
    if ($webonly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WEBONLY;
290 291 292 293
    if ($trusted)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_TRUSTED;
    if ($cvsweb)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_CVSWEB;
294 295
    if ($plab)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PLABUSER;
296 297 298 299 300 301 302 303 304
    if (strcmp($status, TBDB_USERSTATUS_NEWUSER) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_NEWUSER;
    if (strcmp($status, TBDB_USERSTATUS_UNAPPROVED) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_UNAPPROVED;
    if (strcmp($status, TBDB_USERSTATUS_UNVERIFIED) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_UNVERIFIED;
    if (strcmp($status, TBDB_USERSTATUS_ACTIVE) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ACTIVE;

305 306 307
    #
    # Set the magic enviroment variable, if appropriate, for the sake of
    # any processes we might spawn. We prepend an HTTP_ on the front of
308
    # the variable name, so that it will get through suexec.
309 310 311 312 313
    #
    if ($admin && !$adminoff) {
    	putenv("HTTP_WITH_TB_ADMIN_PRIVS=1");
    }

314
    return $CHECKLOGIN_STATUS;
315 316 317 318
}

#
# This one checks for login, but then dies with an appropriate error
319 320
# message. The modifier allows you to turn off checks for specified
# conditions. 
321
#
322
function LOGGEDINORDIE($uid, $modifier = 0, $login_url = NULL) {
323 324
    global $TBBASE, $BASEPATH, $HTTP_COOKIE_VARS, $TBNAMECOOKIE;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
325
    # If our login is not valid, then the uid is already set to "",
326 327 328 329
    # so refresh it to the cookie value. Then we can pass the right
    # uid to hcecklogin, so we can give the right error message.
    if ($uid=="") { $uid=$HTTP_COOKIE_VARS[$TBNAMECOOKIE]; }

330 331 332 333 334 335 336 337 338
    #
    # Allow the caller to specify a different URL to direct the user
    # to
    #
    if (!$login_url) {
	$login_url = "$TBBASE/login.php3?refer=1";
    }

    $link = "\n<a href=\"$login_url\">Please ".
339
	"log in again.</a>\n";
340

341
    if ($uid == FALSE)
342
        USERERROR("You do not appear to be logged in! $link", 1);
343
    
344
    $status = CHECKLOGIN($uid);
345 346 347

    switch ($status & CHECKLOGIN_STATUSMASK) {
    case CHECKLOGIN_NOTLOGGEDIN:
348
        USERERROR("You do not appear to be logged in! $link", 1);
349
        break;
350
    case CHECKLOGIN_TIMEDOUT:
351
        USERERROR("Your login has timed out! $link", 1);
352
        break;
353 354
    case CHECKLOGIN_MAYBEVALID:
        USERERROR("Your login cannot be verified. Are cookies turned on? ".
355
		  "Are you using https? Are you logged in using another ".
356
		  "browser or another machine? $link", 1);
357
        break;
358 359 360 361
    case CHECKLOGIN_LOGGEDIN:
	break;
    default:
	TBERROR("LOGGEDINORDIE failed mysteriously", 1);
362
    }
363 364 365 366 367 368 369

    $status = $status & ~$modifier;

    #
    # Check other conditions.
    #
    if ($status & CHECKLOGIN_PSWDEXPIRED)
370 371
        USERERROR("Your password has expired. ".
		  "<a href=moduserinfo.php3>Please change it now!</a>", 1);
372 373 374 375 376 377
    if ($status & CHECKLOGIN_FROZEN)
        USERERROR("Your account has been frozen!", 1);
    if ($status & (CHECKLOGIN_UNVERIFIED|CHECKLOGIN_NEWUSER))
        USERERROR("You have not verified your account yet!", 1);
    if ($status & CHECKLOGIN_UNAPPROVED)
        USERERROR("Your account has not been approved yet!", 1);
378 379
    if ($status & CHECKLOGIN_WEBONLY)
        USERERROR("Your account does not permit you to access this page!", 1);
380 381 382 383 384 385 386 387 388 389

    #
    # Lastly, check for nologins here. This heads off a bunch of other
    # problems and checks we would need.
    #
    if (NOLOGINS() && !ISADMIN($uid))
        USERERROR("Sorry. The Web Interface is ".
		  "<a href=nologins.php3>Temporarily Unavailable!</a>", 1);

    return $uid;
390 391 392
}

#
393 394 395 396
# Is this user an admin type, and is his admin bit turned on.
# Its actually incorrect to look at the $uid. Its the currently logged
# in user that has to be admin. So ignore the uid and make sure
# there is a login status.
397
#
398
function ISADMIN($uid = 1) {
399 400
    global $CHECKLOGIN_STATUS;
    
401 402
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	$uid=GETUID();
403
	TBERROR("ISADMIN: $uid is not logged in!", 1);
404
    }
405

406
    return (($CHECKLOGIN_STATUS &
407
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINOFF)) ==
408
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN));
409 410
}

411
# Is this user a real administrator (ignore onoff bit).
412
function ISADMINISTRATOR() {
413 414 415 416 417 418 419 420 421 422
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS)
	TBERROR("ISADMIN: $uid is not logged in!", 1);

    return (($CHECKLOGIN_STATUS &
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN)) ==
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN));
}

423
# Is this user a planetlab user? Returns 1 if they are, 0 if not.
424 425 426
function ISPLABUSER() {
    global $CHECKLOGIN_STATUS;

427 428 429 430 431 432 433 434 435 436 437 438 439
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	#
	# For users who are not logged in, we need to check the database
	#
	$uid = GETUID();
	if (!$uid) {
	    return 0;
	}
	$query_result =
	    DBQueryFatal("SELECT plab_user FROM users WHERE uid='$uid'");
	if (!mysql_num_rows($query_result)) {
	    return 0;
	}
440

441 442 443 444 445 446
	$row = mysql_fetch_row($query_result);
	if ($row[0]) {
	    return 1;
	} else {
	    return 0;
	}
447
    } else {
448 449 450 451 452 453
	#
	# For logged-in users, we've recorded it in the the login status
	#
	return (($CHECKLOGIN_STATUS &
		 (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_PLABUSER)) ==
		(CHECKLOGIN_LOGGEDIN|CHECKLOGIN_PLABUSER));
454 455 456
    }
}

457 458 459
#
# Attempt a login.
# 
460
function DOLOGIN($token, $password, $adminmode = 0) {
461 462
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
463
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
464 465
    
    # Caller makes these checks too.
466 467
    if ((!TBvalid_uid($token) && !TBvalid_email($token)) ||
	!isset($password) || $password == "") {
468 469
	return -1;
    }
470
    $now = time();
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
    #
    # Check for a frozen IP address; too many failures.
    #
    unset($iprow);
    unset($IP);
    if (isset($_SERVER['REMOTE_ADDR'])) {
	$IP = $_SERVER['REMOTE_ADDR'];
	
	$ip_result =
	    DBQueryFatal("select * from login_failures ".
			 "where IP='$IP'");

	if ($iprow = mysql_fetch_array($ip_result)) {
	    $ipfrozen = $iprow['frozen'];

	    if ($ipfrozen) {
		DBQueryFatal("update login_failures set ".
			     "       failcount=failcount+1, ".
			     "       failstamp='$now' ".
			     "where IP='$IP'");
		return -1;
	    }
	}
    }

    $user_result =
498
	DBQueryFatal("select uid,usr_pswd,admin,weblogin_frozen,".
499 500
		     "       weblogin_failcount,weblogin_failstamp, ".
		     "       usr_email,usr_name ".
501 502 503 504
		     "from users where ".
		     (TBvalid_email($token) ?
		      "usr_email='$token'" :
		      "uid='$token'"));
505 506 507 508

    #
    # Check password in the database against provided. 
    #
509 510
    do {
      if ($row = mysql_fetch_array($user_result)) {
511
	$uid         = $row['uid'];
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        $db_encoding = $row['usr_pswd'];
	$isadmin     = $row['admin'];
	$frozen      = $row['weblogin_frozen'];
	$failcount   = $row['weblogin_failcount'];
	$failstamp   = $row['weblogin_failstamp'];
	$usr_email   = $row['usr_email'];
	$usr_name    = $row['usr_name'];

	# Check for frozen accounts, and for too many failures within
	# the last N minutes.
	if ($frozen) {
	    DBQueryFatal("update users set , ".
			 "       weblogin_failcount=weblogin_failcount+1, ".
			 "       weblogin_failstamp='$now' ".
			 "where uid='$uid'");
	    return -1;
	}
	
530
        $encoding = crypt("$password", $db_encoding);
531
        if (strcmp($encoding, $db_encoding)) {
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
	    #
	    # Bump count and check for too many failures within the
	    # last minute.
	    #
	    $failcount++;
	    if (($failstamp && $now - $failstamp > DOLOGIN_MAXUSERWAITTIME) ||
		!$failstamp) {
		$failstamp = $now;
		$failcount = 1;
	    }

	    if ($failcount > DOLOGIN_MAXUSERATTEMPTS) {
		$frozen = 1;
	    
		TBMAIL("$usr_name '$uid' <$usr_email>",
		   "Web Login Freeze: '$uid'",
		   "Your login has been frozen because there were too many\n".
		   "login failures from " . $_SERVER['REMOTE_ADDR'] . ".\n\n".
		   "Testbed Operations has been notified.\n",
		   "From: $TBMAIL_OPS\n".
		   "Cc: $TBMAIL_OPS\n".
		   "Bcc: $TBMAIL_AUDIT\n".
		   "Errors-To: $TBMAIL_WWW");
	    }

	    DBQueryFatal("update users set weblogin_frozen='$frozen', ".
			 "       weblogin_failcount='$failcount', ".
			 "       weblogin_failstamp='$failstamp' ".
			 "where uid='$uid'");
            break;
562 563 564 565 566 567
        }
        #
        # Pass! Insert a record in the login table for this uid with
        # the new hash value. If the user is already logged in, thats
        # okay; just update it in place with a new hash and timeout. 
        #
568
	$timeout = $now + $TBAUTHTIMEOUT;
569
	$hashkey = GENHASH();
570 571 572
        $query_result =
	    DBQueryFatal("SELECT timeout FROM login WHERE uid='$uid'");
	
573
	if (mysql_num_rows($query_result)) {
574 575 576
	    DBQueryFatal("UPDATE login set ".
			 "timeout='$timeout', hashkey='$hashkey' ".
			 "WHERE uid='$uid'");
577 578
	}
	else {
579 580
	    DBQueryFatal("INSERT into login (uid, hashkey, timeout) ".
			 "VALUES ('$uid', '$hashkey', '$timeout')");
581 582
	}

583
	#
584
	# Usage stats. 
585
	#
586 587 588 589
	DBQueryFatal("update user_stats set ".
		     " weblogin_count=weblogin_count+1, ".
		     " weblogin_last=now() ".
		     "where uid='$uid'");
590

591
	#
592 593 594 595
	# Issue the cookie requests so that subsequent pages come back
	# with the hash value and auth usr embedded.

	#
596 597 598 599 600
	# For the hashkey, we use a zero timeout so that the cookie is
	# a session cookie; killed when the browser is exited. Hopefully this
	# keeps the key from going to disk on the client machine. The cookie
	# lives as long as the browser is active, but we age the cookie here
	# at the server so it will become invalid at some point.
601
	#
602
	setcookie($TBAUTHCOOKIE, $hashkey, 0, "/",
603
                  $TBAUTHDOMAIN, $TBSECURECOOKIES);
604

605 606 607 608 609 610 611 612 613 614
	#
	# Another cookie, to help in menu generation. See above in
	# checklogin. This cookie is a simple hash of the real hash,
	# intended to indicate if the current browser holds a real hash.
	# All this does is change the menu options presented, imparting
	# no actual privs. 
	#
	$crc = bin2hex(mhash(MHASH_CRC32, $hashkey));
	setcookie($TBLOGINCOOKIE, $crc, 0, "/", $TBAUTHDOMAIN, 0);

615 616 617 618 619 620 621 622
	#
	# We give this a really long timeout. We want to remember who the
	# the user was each time they load a page, and more importantly,
	# each time they come back to the main page so we can fill in their
	# user name. NOTE: This cookie is integral to authorization, since
	# we do not pass around the UID anymore, but look for it in the
	# cookie.
	# 
623
	$timeout = $now + (60 * 60 * 24 * 32);
624 625
	setcookie($TBNAMECOOKIE, $uid, $timeout, "/", $TBAUTHDOMAIN, 0);

626
	#
627 628 629 630 631
	# Set adminoff on new logins, unless user requested to be
	# logged in as admin (and is an admin of course!). This is
	# primarily to bypass the nologins directive which makes it
	# impossible for an admin to login when the web interface is
	# turned off. 
632
	#
633 634 635 636
	$adminoff = 1;
	if ($adminmode && $isadmin) {
	    $adminoff = 0;
	}
637 638 639
	DBQueryFatal("update users set adminoff=$adminoff, ".
		     "       weblogin_failcount=0,weblogin_failstamp=0 ".
		     "where uid='$uid'");
640

641
	return 0;
642 643
      }
    } while (0);
644 645 646
    #
    # No such user
    #
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    if (!isset($IP))
	return -1;
    
    if (isset($iprow)) {
	$ipfailcount = $iprow['failcount'];
	$ipfailstamp = $iprow['failstamp'];

        #
        # Bump count and check for too many (8) failures within the
        # last 2 minutes. Note that aging is passive; we do not have
        # a daemon cleaning out old records, so we have to age on the fly. 
        #
	$ipfailcount++;
	if (($ipfailstamp && $now - $ipfailstamp > DOLOGIN_MAXIPWAITTIME) ||
	    !$ipfailstamp) {
	    $ipfailstamp = $now;
	    $ipfailcount = 1;
	}
    }
    else {
	$ipfailcount = 1;
	$ipfailstamp = $now;
	$ipfrozen    = 0;
    }
    
    if ($ipfailcount > DOLOGIN_MAXIPATTEMPTS) {
	$ipfrozen = 1;
	    
	TBMAIL($TBMAIL_OPS,
	       "Web Login Freeze: '$IP'",
	       "Logins has been frozen because there were too many login\n".
678
	       "failures from $IP. Last attempted uid was '$token'.\n\n",
679 680 681 682 683 684 685 686 687
	       "From: $TBMAIL_OPS\n".
	       "Bcc: $TBMAIL_AUDIT\n".
	       "Errors-To: $TBMAIL_WWW");
    }
    DBQueryFatal("replace into login_failures set ".
		 "       IP='$IP', ".
		 "       frozen='$ipfrozen', ".
		 "       failcount='$ipfailcount', ".
		 "       failstamp='$ipfailstamp'");
688 689 690
    return -1;
}

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

#
# Verify a password
# 
function VERIFYPASSWD($uid, $password) {
    if (! isset($password) ||
	strcmp($password, "") == 0) {
	return -1;
    }

    $query_result =
	DBQueryFatal("SELECT usr_pswd FROM users WHERE uid='$uid'");

    #
    # Check password in the database against provided. 
    #
    if ($row = mysql_fetch_row($query_result)) {
        $db_encoding = $row[0];
709
        $encoding = crypt("$password", $db_encoding);
710 711 712 713 714 715 716 717 718
	
        if (strcmp($encoding, $db_encoding)) {
            return -1;
	}
	return 0;
    }
    return -1;
}

719
#
720
# Log out a UID.
721 722
#
function DOLOGOUT($uid) {
723
    global $CHECKLOGIN_STATUS, $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHDOMAIN;
724

725 726 727 728 729
    # Pedantic check.
    if (!TBvalid_uid($uid)) {
	return 1;
    }

730 731 732 733
    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;

    $query_result =
	DBQueryFatal("SELECT hashkey timeout FROM login WHERE uid='$uid'");
734 735 736

    # Not logged in.
    if (($row = mysql_fetch_array($query_result)) == 0) {
737
	return 1;
738 739 740
    }

    $hashkey = $row[hashkey];
741
    $timeout = time() - 1000000;
742

743
    DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
744 745

    #
746
    # Issue a cookie request to delete the cookies. 
747
    #
748
    setcookie($TBAUTHCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
749
    setcookie($TBLOGINCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
750 751 752 753

    return 0;
}

754
#
Chad Barb's avatar
 
Chad Barb committed
755
# Simple "nologins" support.
756 757
#
function NOLOGINS() {
758
    global $CHECKLOGIN_NOLOGINS;
759

Chad Barb's avatar
 
Chad Barb committed
760 761
    if ($CHECKLOGIN_NOLOGINS == -1) {
	$CHECKLOGIN_NOLOGINS = TBGetSiteVar("web/nologins");
762
    }
Chad Barb's avatar
 
Chad Barb committed
763
	
764
    return $CHECKLOGIN_NOLOGINS;
765 766
}

767 768 769
function LASTWEBLOGIN($uid) {
    global $TBDBNAME;

770
    $query_result =
771
        DBQueryFatal("SELECT weblogin_last from user_stats where uid='$uid'");
772 773 774
    
    if (mysql_num_rows($query_result)) {
	$lastrow      = mysql_fetch_array($query_result);
775
	return $lastrow[weblogin_last];
776 777 778 779
    }
    return 0;
}

780 781 782 783 784 785 786 787 788 789 790
function HASREALACCOUNT($uid) {
    $query_result =
	DBQueryFatal("select status,webonly from users where uid='$uid'");

    if (!mysql_num_rows($query_result)) {
	return 0;
    }
    $row = mysql_fetch_array($query_result);
    $status  = $row[0];
    $webonly = $row[1];

791 792 793
    if ($webonly ||
	(strcmp($status, TBDB_USERSTATUS_ACTIVE) &&
	 strcmp($status, TBDB_USERSTATUS_FROZEN))) {
794 795 796 797 798
	return 0;
    }
    return 1;
}

799 800 801 802
#
# Beware empty spaces (cookies)!
# 
?>