tbauth.php3 29.2 KB
Newer Older
1 2
<?php
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
3
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2006 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
# These global are to prevent repeated calls to the DB. 
#
$CHECKLOGIN_STATUS		= -1;
$CHECKLOGIN_UID			= 0;
$CHECKLOGIN_NOLOGINS		= -1;
16
$CHECKLOGIN_WIKINAME            = "";
17
$CHECKLOGIN_IDLETIME            = 0;
18 19
$CHECKLOGIN_HASHKEY             = null;
$CHECKLOGIN_HASHHASH            = null;
20 21 22 23 24 25 26 27 28

#
# New Mapping. 
#
define("CHECKLOGIN_NOSTATUS",		-1);
define("CHECKLOGIN_NOTLOGGEDIN",	0);
define("CHECKLOGIN_LOGGEDIN",		1);
define("CHECKLOGIN_TIMEDOUT",		2);
define("CHECKLOGIN_MAYBEVALID",		4);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
29 30
define("CHECKLOGIN_STATUSMASK",		0x0000ff);
define("CHECKLOGIN_MODMASK",		0xffff00);
31 32 33 34 35
#
# 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. 
#
36 37 38 39 40 41 42 43 44 45
define("CHECKLOGIN_NEWUSER",		0x000100);
define("CHECKLOGIN_UNVERIFIED",		0x000200);
define("CHECKLOGIN_UNAPPROVED",		0x000400);
define("CHECKLOGIN_ACTIVE",		0x000800);
define("CHECKLOGIN_USERSTATUS",		0x000f00);
define("CHECKLOGIN_PSWDEXPIRED",	0x001000);
define("CHECKLOGIN_FROZEN",		0x002000);
define("CHECKLOGIN_ISADMIN",		0x004000);
define("CHECKLOGIN_TRUSTED",		0x008000);
define("CHECKLOGIN_CVSWEB",		0x010000);
46
define("CHECKLOGIN_ADMINON",		0x020000);
47 48 49
define("CHECKLOGIN_WEBONLY",		0x040000);
define("CHECKLOGIN_PLABUSER",		0x080000);
define("CHECKLOGIN_STUDLY",		0x100000);
50
define("CHECKLOGIN_WIKIONLY",		0x200000);
51 52
define("CHECKLOGIN_OPSGUY",		0x400000);	# Member of emulab-ops.
define("CHECKLOGIN_ISFOREIGN_ADMIN",	0x800000);	# Admin of another Emulab. 
53

54 55 56
#
# Constants for tracking possible login attacks.
#
57 58
define("DOLOGIN_MAXUSERATTEMPTS",	15);
define("DOLOGIN_MAXIPATTEMPTS",		25);
59

60 61 62 63 64 65 66 67 68
#
# 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
69
    $random_bytes = fread($fp, 128);
70 71 72 73 74 75
    fclose($fp);

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

76 77 78
#
# 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
79
# and HASH back, and then check the DB to see if the user is really
80 81 82 83 84 85
# logged in.
# 
function GETLOGIN() {
    if (($uid = GETUID()) == FALSE)
	    return FALSE;

86 87
    $check = CHECKLOGIN($uid);

88
    if ($check & (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_MAYBEVALID))
89 90 91 92 93 94 95 96 97 98 99
	    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
100
    global $TBNAMECOOKIE;
Chad Barb's avatar
 
Chad Barb committed
101
    global $nocookieuid;
102

Leigh B. Stoller's avatar
Leigh B. Stoller committed
103
    $curname = FALSE;
Chad Barb's avatar
 
Chad Barb committed
104

Leigh B. Stoller's avatar
Leigh B. Stoller committed
105 106 107
    # XXX - nocookieuid is sent by netbuild applet in URL.
    if (isset($_GET['nocookieuid'])) {
	$curname = $_GET['nocookieuid'];
Chad Barb's avatar
 
Chad Barb committed
108
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
109 110 111 112 113
    elseif (isset($_COOKIE[$TBNAMECOOKIE])) {
	$curname = $_COOKIE[$TBNAMECOOKIE];
    }
    else
	return FALSE;
Chad Barb's avatar
 
Chad Barb committed
114

Leigh B. Stoller's avatar
Leigh B. Stoller committed
115
    # Verify valid string (no special chars like single/double quotes!).
Leigh B. Stoller's avatar
Leigh B. Stoller committed
116 117 118 119
    # 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
120 121
	return FALSE;
    }
122 123 124
    return $curname;
}

125
#
126
# Verify a login by sucking a UIDs current hash value out of the database.
127 128 129
# 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.
#
130
# Returns a combination of the CHECKLOGIN values above.
131
#
132
function CHECKLOGIN($uid) {
133
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $HTTP_COOKIE_VARS, $TBAUTHTIMEOUT;
134
    global $CHECKLOGIN_STATUS, $CHECKLOGIN_UID, $CHECKLOGIN_NODETYPES;
135
    global $CHECKLOGIN_WIKINAME, $TBOPSPID;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
136
    global $EXPOSEARCHIVE, $EXPOSETEMPLATES;
137
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_HASHHASH;
Chad Barb's avatar
 
Chad Barb committed
138
    global $nocookieauth;
139
    
140 141 142 143 144 145 146
    #
    # If we already figured this out, do not duplicate work!
    #
    if ($CHECKLOGIN_STATUS != CHECKLOGIN_NOSTATUS) {
	return $CHECKLOGIN_STATUS;
    }
    $CHECKLOGIN_UID = $uid;
147

Chad Barb's avatar
 
Chad Barb committed
148 149 150 151 152 153 154
    # 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];
    }
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    $hashhash = $HTTP_COOKIE_VARS[$TBLOGINCOOKIE];

    #
    # We have to get at least one of the hashes. The Java applets do not
    # send it, but web browsers will.
    #
    if (!isset($curhash) && !isset($hashhash)) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
    if (isset($curhash) &&
	! preg_match("/^[\w]+$/", $curhash)) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
    if (isset($hashhash) &&
	! preg_match("/^[\w]+$/", $hashhash)) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
175 176 177 178 179 180 181 182

    if (isset($curhash)) {
	$CHECKLOGIN_HASHKEY = $safe_curhash = addslashes($curhash);
    }
    if (isset($hashhash)) {
	$CHECKLOGIN_HASHHASH = $safe_hashhash = addslashes($hashhash);
    }
    $safe_uid = addslashes($uid);
Chad Barb's avatar
 
Chad Barb committed
183
    
184 185 186 187
    #
    # Note that we get multiple rows back because of the group_membership
    # join. No big deal.
    # 
188
    $query_result =
189
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout, ".
190
		     "       status,admin,cvsweb,g.trust,l.adminon,webonly, " .
191
		     "       user_interface,n.type,u.stud,u.wikiname, ".
192
		     "       u.wikionly,g.pid,u.foreign_admin " .
193 194
		     " from users as u ".
		     "left join login as l on l.uid=u.uid ".
195
		     "left join group_membership as g on g.uid=u.uid ".
196 197 198 199 200
		     "left join nodetypeXpid_permissions as n on g.pid=n.pid ".
		     "where u.uid='$safe_uid' and ".
		     (isset($curhash) ?
		      "l.hashkey='$safe_curhash'" :
		      "l.hashhash='$safe_hashhash'"));
201

202
    # No such user.
203 204 205 206 207 208 209
    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
210
    # values and the pid. pid is a hack.
211 212
    #
    $trusted = 0;
213
    $opsguy  = 0;
214
    
215 216 217 218 219 220 221 222 223 224 225 226
    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;
	}
227
	$adminon  = $row[7];
228
	$webonly  = $row[8];
229
	$interface= $row[9];
230 231

	$type     = $row[10];
232
	$stud     = $row[11];
233
	$wikiname = $row[12];
234
	$wikionly = $row[13];
235

236 237 238 239 240
	# Check for an ops guy.
	$pid = $row[14];
	if ($pid == $TBOPSPID) {
	    $opsguy = 1;
	}
241 242 243 244

	# Set foreign_admin=1 for admins of another Emulab.
	$foreign_admin   = $row[15];

245
	$CHECKLOGIN_NODETYPES[$type] = 1;
246
    }
247 248 249 250

    #
    # If user exists, but login has no entry, quit now.
    #
251 252 253 254
    if (!$hashkey) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
255

256
    #
257
    # Check for frozen account. Might do something interesting later.
258
    #
259
    if (! strcmp($status, TBDB_USERSTATUS_FROZEN)) {
260
	DBQueryFatal("DELETE FROM login WHERE uid='$safe_uid'");
261 262
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
263 264
    }

265
    #
266 267
    # Check for expired login. It does not matter if the cookie matches,
    # kill the entry anyway so the user is officially logged out.
268
    #
269
    if (time() > $timeout) {
270
	DBQueryFatal("DELETE FROM login WHERE uid='$safe_uid'");
271 272 273
	$CHECKLOGIN_STATUS = CHECKLOGIN_TIMEDOUT;
	return $CHECKLOGIN_STATUS;
    }
274
    $CHECKLOGIN_IDLETIME = time() - ($timeout - $TBAUTHTIMEOUT);
275 276

    #
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    # 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).
292
	#
293 294 295 296 297 298 299 300 301
	if ($curhash != $hashkey) {
	    #
	    # User is not logged in from this browser. Must be stale.
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
	else {
            #
302 303
	    # User is logged in.
	    #
304 305
	    $CHECKLOGIN_STATUS = CHECKLOGIN_LOGGEDIN;
	}
306 307
    }
    else {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	#
	# 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!
	#
	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;
	}
329 330 331
    }

    #
332
    # Now add in the modifiers.
333
    #
334 335 336 337
    if ($expired)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PSWDEXPIRED;
    if ($admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISADMIN;
338 339
    if ($adminon)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ADMINON;
340 341
    if ($webonly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WEBONLY;
342 343
    if ($wikionly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WIKIONLY;
344 345
    if ($trusted)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_TRUSTED;
346 347
    if ($stud)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_STUDLY;
348 349
    if ($cvsweb)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_CVSWEB;
350
    if ($interface == TBDB_USER_INTERFACE_PLAB)
351
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PLABUSER;
352 353 354 355 356 357 358 359
    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;
360 361
    if (isset($wikiname) && $wikiname != "")
	$CHECKLOGIN_WIKINAME = $wikiname;
362 363
    if ($opsguy)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_OPSGUY;
364 365
    if ($foreign_admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISFOREIGN_ADMIN;
366

367 368 369
    #
    # Set the magic enviroment variable, if appropriate, for the sake of
    # any processes we might spawn. We prepend an HTTP_ on the front of
370
    # the variable name, so that it will get through suexec.
371
    #
372
    if ($admin && $adminon) {
373 374
    	putenv("HTTP_WITH_TB_ADMIN_PRIVS=1");
    }
375 376 377
    # XXX Temporary.
    if ($stud) {
	$EXPOSEARCHIVE = 1;
378
	$EXPOSETEMPLATES = 1;
379
    }
380
    return $CHECKLOGIN_STATUS;
381 382 383 384
}

#
# This one checks for login, but then dies with an appropriate error
385 386
# message. The modifier allows you to turn off checks for specified
# conditions. 
387
#
388
function LOGGEDINORDIE($uid, $modifier = 0, $login_url = NULL) {
389
    global $TBBASE, $BASEPATH, $HTTP_COOKIE_VARS, $TBNAMECOOKIE;
390
    global $TBAUTHTIMEOUT, $CHECKLOGIN_HASHKEY;
391

Leigh B. Stoller's avatar
Leigh B. Stoller committed
392
    # If our login is not valid, then the uid is already set to "",
393
    # so refresh it to the cookie value. Then we can pass the right
394 395 396 397
    # uid to checklogin, so we can give the right error message.
    if ($uid == "") {
	$uid = $HTTP_COOKIE_VARS[$TBNAMECOOKIE];

Leigh B. Stoller's avatar
Leigh B. Stoller committed
398 399 400 401 402 403 404 405
	if ($uid == "") {
		$uid = FALSE;
	}
	else {
            # Verify valid string (no special chars like single/double quotes!)
	    if (! preg_match("/^[-\w]+$/", $uid)) {
		TBERROR("LOGGEDINORDIE: Illegal characters in $uid", 1);
	    }
406 407
	}
    }
408

409 410 411 412 413 414 415 416 417
    #
    # 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 ".
418
	"log in again.</a>\n";
419

420
    if ($uid == FALSE)
421
        USERERROR("You do not appear to be logged in! $link", 1);
422
    
423
    $status = CHECKLOGIN($uid);
424 425 426

    switch ($status & CHECKLOGIN_STATUSMASK) {
    case CHECKLOGIN_NOTLOGGEDIN:
427
        USERERROR("You do not appear to be logged in! $link", 1);
428
        break;
429
    case CHECKLOGIN_TIMEDOUT:
430
        USERERROR("Your login has timed out! $link", 1);
431
        break;
432 433
    case CHECKLOGIN_MAYBEVALID:
        USERERROR("Your login cannot be verified. Are cookies turned on? ".
434
		  "Are you using https? Are you logged in using another ".
435
		  "browser or another machine? $link", 1);
436
        break;
437
    case CHECKLOGIN_LOGGEDIN:
438 439 440 441 442 443
        #
	# 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.
        #
444 445
	if (! is_null($CHECKLOGIN_HASHKEY)) {
	    $timeout = time() + $TBAUTHTIMEOUT;
446

447 448 449
	    DBQueryFatal("UPDATE login set timeout='$timeout' ".
			 "where uid='$uid' and hashkey='$CHECKLOGIN_HASHKEY'");
	}
450 451 452
	break;
    default:
	TBERROR("LOGGEDINORDIE failed mysteriously", 1);
453
    }
454 455 456 457 458 459 460

    $status = $status & ~$modifier;

    #
    # Check other conditions.
    #
    if ($status & CHECKLOGIN_PSWDEXPIRED)
461 462
        USERERROR("Your password has expired. ".
		  "<a href=moduserinfo.php3>Please change it now!</a>", 1);
463 464 465 466 467 468
    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);
469
    if (($status & CHECKLOGIN_WEBONLY) && ! ISADMIN($uid))
470
        USERERROR("Your account does not permit you to access this page!", 1);
471 472
    if (($status & CHECKLOGIN_WIKIONLY) && ! ISADMIN($uid))
        USERERROR("Your account does not permit you to access this page!", 1);
473 474 475 476 477 478 479 480 481 482

    #
    # 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;
483 484 485
}

#
486 487 488 489
# 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.
490
#
491
function ISADMIN($uid = 1) {
492 493
    global $CHECKLOGIN_STATUS;
    
494
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
495
	return 0;
496
    }
497

498
    return (($CHECKLOGIN_STATUS &
499 500
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON)) ==
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON));
501 502
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

# Is this user an admin of another Emulab.
function ISFOREIGN_ADMIN($uid = 1) {
    global $CHECKLOGIN_STATUS;

    # Definitely not, if not logged in.
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	return 0;
    }

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

518 519 520 521 522 523 524 525 526 527 528 529 530
function STUDLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	$uid=GETUID();
	TBERROR("STUDLY: $uid is not logged in!", 1);
    }

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

531 532 533 534 535 536 537 538 539 540 541 542 543
function OPSGUY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	$uid=GETUID();
	TBERROR("OPSGUY: $uid is not logged in!", 1);
    }

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

544 545 546 547 548 549 550 551 552 553 554 555 556
function WIKIONLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	$uid=GETUID();
	TBERROR("WIKIONLY: $uid is not logged in!", 1);
    }

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

557
# Is this user a real administrator (ignore onoff bit).
558
function ISADMINISTRATOR() {
559 560 561 562 563 564 565 566 567 568
    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));
}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
#
# Toggle current login admin bit. Must be an administrator of course!
#
function SETADMINMODE($uid, $onoff) {
    global $HTTP_COOKIE_VARS, $TBAUTHCOOKIE;
    
    # This makes sure the user is actually logged in secure (https).
    if (! ISADMINISTRATOR())
	return;

    $curhash = $HTTP_COOKIE_VARS[$TBAUTHCOOKIE];

    if (!isset($curhash) ||
	!preg_match("/^[\w]+$/", $curhash)) {
	return;
    }
    $onoff   = addslashes($onoff);
    $curhash = addslashes($curhash);
    $uid     = addslashes($uid);
    
    DBQueryFatal("update login set adminon='$onoff' ".
		 "where uid='$uid' and hashkey='$curhash'");
}

593
# Is this user a planetlab user? Returns 1 if they are, 0 if not.
594 595 596
function ISPLABUSER() {
    global $CHECKLOGIN_STATUS;

597 598 599 600 601 602 603 604 605
    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 =
606
	    DBQueryFatal("SELECT user_interface FROM users WHERE uid='$uid'");
607 608 609
	if (!mysql_num_rows($query_result)) {
	    return 0;
	}
610

611 612
	$row = mysql_fetch_row($query_result);
	if ($row[0]) {
613
	    return ($row[0] == TBDB_USER_INTERFACE_PLAB);
614 615 616
	} else {
	    return 0;
	}
617
    } else {
618
	#
619
	# For logged-in users, we recorded it in the the login status
620 621
	#
	return (($CHECKLOGIN_STATUS &
622 623
		 (CHECKLOGIN_PLABUSER)) ==
		(CHECKLOGIN_PLABUSER));
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
#
# Check to see if a user is allowed, in some project, to use the given node
# type. Returns 1 if allowed, 0 if not.
#
# NOTE: This is NOT intended as a real permissions check. It is intended only
# for display purposes (ie. deciding whether or not to give the user a link to
# the plab_ez page.) It does not require the user to be actually logged in, so
# that it still works for pages fetched through http. Thus, it may be possible
# for a clever user to fake it out.
#
function NODETYPE_ALLOWED($type) {
    global $CHECKLOGIN_NODETYPES;
    $uid = GETUID();
    if (!$uid) {
	return 0;
    }
    if ($CHECKLOGIN_NODETYPES[$type]) {
	return 1;
    } else {
	return 0;
    }
}

650 651 652
#
# Attempt a login.
# 
653
function DOLOGIN($token, $password, $adminmode = 0) {
654 655
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
656
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
657
    global $WIKISUPPORT, $WIKICOOKIENAME;
658
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
659 660
    
    # Caller makes these checks too.
661 662
    if ((!TBvalid_uid($token) && !TBvalid_email($token)) ||
	!isset($password) || $password == "") {
663 664
	return -1;
    }
665
    $now = time();
666

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    #
    # 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 =
693
	DBQueryFatal("select uid,usr_pswd,admin,weblogin_frozen,".
694
		     "       weblogin_failcount,weblogin_failstamp, ".
695
		     "       usr_email,usr_name,unix_uid ".
696 697 698 699
		     "from users where ".
		     (TBvalid_email($token) ?
		      "usr_email='$token'" :
		      "uid='$token'"));
700 701 702 703

    #
    # Check password in the database against provided. 
    #
704 705
    do {
      if ($row = mysql_fetch_array($user_result)) {
706
	$uid         = $row['uid'];
707 708 709 710 711 712 713
        $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'];
714
	$uid_idx     = $row['unix_uid'];
715

716 717
	# Check for frozen accounts. We do not update the IP record when
	# an account is frozen.
718
	if ($frozen) {
719
	    DBQueryFatal("update users set ".
720 721 722 723 724 725
			 "       weblogin_failcount=weblogin_failcount+1, ".
			 "       weblogin_failstamp='$now' ".
			 "where uid='$uid'");
	    return -1;
	}
	
726
        $encoding = crypt("$password", $db_encoding);
727
        if (strcmp($encoding, $db_encoding)) {
728
	    #
729
	    # Bump count and check for too many consecutive failures.
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
	    #
	    $failcount++;
	    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', ".
748
			 "       weblogin_failstamp='$now' ".
749 750
			 "where uid='$uid'");
            break;
751
        }
752
	#
753
	# Pass!
754 755
	#

756
	#
757
	# Set adminmode off on new logins, unless user requested to be
758 759 760 761
	# 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. 
762
	#
763
	$adminon = 0;
764
	if ($adminmode && $isadmin) {
765
	    $adminon = 1;
766
	}
767 768 769 770

        #
        # Insert a record in the login table for this uid.
	#
771
	if (DOLOGIN_MAGIC($uid, $adminon) < 0) {
772 773 774 775 776 777 778 779 780 781
	    return -1;
	}

	#
	# Usage stats. 
	#
	DBQueryFatal("update user_stats set ".
		     " weblogin_count=weblogin_count+1, ".
		     " weblogin_last=now() ".
		     "where uid_idx='$uid_idx'");
782

783 784 785 786
	# Clear IP record since we have a sucessful login from the IP.
	if (isset($IP)) {
	    DBQueryFatal("delete from login_failures where IP='$IP'");
	}
787
	return 0;
788 789
      }
    } while (0);
790 791 792
    #
    # No such user
    #
793
    if (!isset($IP)) {
794
	return -1;
795 796 797
    }
	
    $ipfrozen = 0;
798 799 800 801
    if (isset($iprow)) {
	$ipfailcount = $iprow['failcount'];

        #
802
        # Bump count.
803 804 805 806
        #
	$ipfailcount++;
    }
    else {
807 808 809
	#
	# First failure.
	# 
810 811
	$ipfailcount = 1;
    }
812 813 814 815

    #
    # Check for too many consecutive failures.
    #
816 817 818 819 820 821
    if ($ipfailcount > DOLOGIN_MAXIPATTEMPTS) {
	$ipfrozen = 1;
	    
	TBMAIL($TBMAIL_OPS,
	       "Web Login Freeze: '$IP'",
	       "Logins has been frozen because there were too many login\n".
822
	       "failures from $IP. Last attempted uid was '$token'.\n\n",
823 824 825 826 827 828 829 830
	       "From: $TBMAIL_OPS\n".
	       "Bcc: $TBMAIL_AUDIT\n".
	       "Errors-To: $TBMAIL_WWW");
    }
    DBQueryFatal("replace into login_failures set ".
		 "       IP='$IP', ".
		 "       frozen='$ipfrozen', ".
		 "       failcount='$ipfailcount', ".
831
		 "       failstamp='$now'");
832 833 834
    return -1;
}

835
function DOLOGIN_MAGIC($uid, $adminon = 0)
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
{
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
    global $WIKISUPPORT, $WIKICOOKIENAME;
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME;
    
    # Caller makes these checks too.
    if (!TBvalid_uid($uid)) {
	return -1;
    }
    $now = time();

    #
    # 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. 
    #
    $timeout = $now + $TBAUTHTIMEOUT;
    $hashkey = GENHASH();
856 857 858 859
    $crc     = bin2hex(mhash(MHASH_CRC32, $hashkey));

    DBQueryFatal("replace into login (uid,hashkey,hashhash,timeout,adminon) ".
		 "values ('$uid', '$hashkey', '$crc', '$timeout', $adminon)");
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

    #
    # Issue the cookie requests so that subsequent pages come back
    # with the hash value and auth usr embedded.

    #
    # 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.
    #
    setcookie($TBAUTHCOOKIE, $hashkey, 0, "/",
	      $TBAUTHDOMAIN, $TBSECURECOOKIES);

    #
    # 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. 
    #
    setcookie($TBLOGINCOOKIE, $crc, 0, "/", $TBAUTHDOMAIN, 0);

    #
    # 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.
    # 
    $timeout = $now + (60 * 60 * 24 * 32);
    setcookie($TBNAMECOOKIE, $uid, $timeout, "/", $TBAUTHDOMAIN, 0);

    #
    # Clear the existing Wiki cookie so that there is not an old one
    # for a different user, sitting in the brower. 
    # 
    if ($WIKISUPPORT) {
	$flushtime = time() - 1000000;
	    
	setcookie($WIKICOOKIENAME, "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
    }
	
    #
    # Ditto for bugdb
    # 
    if ($BUGDBSUPPORT) {
	$flushtime = time() - 1000000;
	    
	setcookie($BUGDBCOOKIENAME, "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
    }
	
916
    DBQueryFatal("update users set ".
917 918 919 920 921
		 "       weblogin_failcount=0,weblogin_failstamp=0 ".
		 "where uid='$uid'");

    return 0;
}
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

#
# 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];
940
        $encoding = crypt("$password", $db_encoding);
941 942 943 944 945 946 947 948 949
	
        if (strcmp($encoding, $db_encoding)) {
            return -1;
	}
	return 0;
    }
    return -1;
}

950
#
951
# Log out a UID.
952 953
#
function DOLOGOUT($uid) {
954
    global $CHECKLOGIN_STATUS, $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHDOMAIN;
955
    global $WIKISUPPORT, $WIKICOOKIENAME, $HTTP_COOKIE_VARS;
956
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME;
957

958 959 960 961
    # Pedantic check.
    if (!TBvalid_uid($uid)) {
	return 1;
    }
962 963
    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;

964 965 966 967 968 969 970
    $curhash = $HTTP_COOKIE_VARS[$TBAUTHCOOKIE];
    $hashhash = $HTTP_COOKIE_VARS[$TBLOGINCOOKIE];
    
    #
    # We have to get at least one of the hashes. 
    #
    if (!isset($curhash) && !isset($hashhash)) {
971
	return 1;
972
    }
973 974 975 976 977 978 979 980 981 982
    if (isset($curhash) &&
	! preg_match("/^[\w]+$/", $curhash)) {
	return 1;
    }
    if (isset($hashhash) &&
	! preg_match("/^[\w]+$/", $hashhash)) {
	return 1;
    }
    $safe_curhash  = addslashes($curhash);
    $safe_hashhash = addslashes($hashhash);
983

984 985 986 987 988
    DBQueryFatal("delete from login ".
		 " where uid='$uid' and ".
		 (isset($curhash) ?
		  "hashkey='$safe_curhash'" :
		  "hashhash='$safe_hashhash'"));
989 990

    #
991
    # Issue a cookie request to delete the cookies. 
992
    #
993
    setcookie($TBAUTHCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
994
    setcookie($TBLOGINCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
995 996 997
    if ($WIKISUPPORT) {
	setcookie($WIKICOOKIENAME, "", $timeout, "/", $TBAUTHDOMAIN, 0);
    }
998 999 1000
    if ($BUGDBSUPPORT) {
	setcookie($BUGDBCOOKIENAME, "", $timeout, "/", $TBAUTHDOMAIN, 0);
    }
1001 1002 1003 1004

    return 0;
}

1005
#
Chad Barb's avatar
 
Chad Barb committed
1006
# Simple "nologins" support.
1007 1008
#
function NOLOGINS() {
1009
    global $CHECKLOGIN_NOLOGINS;
1010

Chad Barb's avatar
 
Chad Barb committed
1011 1012
    if ($CHECKLOGIN_NOLOGINS == -1) {
	$CHECKLOGIN_NOLOGINS = TBGetSiteVar("web/nologins");
1013
    }
Chad Barb's avatar
 
Chad Barb committed
1014
	
1015
    return $CHECKLOGIN_NOLOGINS;
1016 1017
}

1018 1019 1020
function LASTWEBLOGIN($uid) {
    global $TBDBNAME;

1021
    $query_result =
1022 1023 1024
        DBQueryFatal("select weblogin_last from users as u ".
		     "left join user_stats as s on s.uid_idx=u.unix_uid ".
		     "where u.uid='$uid'");
1025 1026 1027
    
    if (mysql_num_rows($query_result)) {
	$lastrow      = mysql_fetch_array($query_result);
1028
	return $lastrow[weblogin_last];
1029 1030 1031 1032
    }
    return 0;
}

1033 1034
function HASREALACCOUNT($uid) {
    $query_result =
1035 1036
	DBQueryFatal("select status,webonly,wikionly from users ".
		     "where uid='$uid'");
1037 1038 1039 1040 1041

    if (!mysql_num_rows($query_result)) {
	return 0;
    }
    $row = mysql_fetch_array($query_result);
1042 1043 1044
    $status   = $row[0];
    $webonly  = $row[1];
    $wikionly = $row[2];
1045

1046
    if ($webonly || $wikionly ||
1047 1048
	(strcmp($status, TBDB_USERSTATUS_ACTIVE) &&
	 strcmp($status, TBDB_USERSTATUS_FROZEN))) {
1049 1050 1051 1052 1053
	return 0;
    }
    return 1;
}

1054 1055 1056 1057
#
# Beware empty spaces (cookies)!
# 
?>