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

#
# 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
31 32
define("CHECKLOGIN_STATUSMASK",		0x0000ff);
define("CHECKLOGIN_MODMASK",		0xffff00);
33 34 35 36 37
#
# 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. 
#
38 39 40 41 42 43 44 45 46 47
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);
48
define("CHECKLOGIN_ADMINON",		0x020000);
49 50 51
define("CHECKLOGIN_WEBONLY",		0x040000);
define("CHECKLOGIN_PLABUSER",		0x080000);
define("CHECKLOGIN_STUDLY",		0x100000);
52
define("CHECKLOGIN_WIKIONLY",		0x200000);
53 54
define("CHECKLOGIN_OPSGUY",		0x400000);	# Member of emulab-ops.
define("CHECKLOGIN_ISFOREIGN_ADMIN",	0x800000);	# Admin of another Emulab. 
55

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
62 63 64 65 66 67 68
# Return codes for DOLOGIN so that the caller can say something helpful.
#
define("DOLOGIN_STATUS_OKAY",		0);
define("DOLOGIN_STATUS_ERROR",		-1);
define("DOLOGIN_STATUS_IPFREEZE",	-2);
define("DOLOGIN_STATUS_WEBFREEZE",	-3);

69 70 71 72 73 74 75 76 77
#
# 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
78
    $random_bytes = fread($fp, 128);
79 80
    fclose($fp);

81
    $hash  = mhash (MHASH_MD5, bin2hex($random_bytes) . " " . microtime());
82 83 84
    return bin2hex($hash);
}

85 86 87 88 89 90 91 92 93 94 95 96 97
#
# Return the value of what we told the browser to remember for the login.
# Currently, this is an email address, stored in a long term cookie.
#
function REMEMBERED_ID() {
    global $TBEMAILCOOKIE;

    if (isset($_COOKIE[$TBEMAILCOOKIE])) {
	return $_COOKIE[$TBEMAILCOOKIE];
    }
    return null;
}

98 99
#
# Return the value of the currently logged in uid, or null if not
100
# logged in. This interface is deprecated and being replaced.
101 102
# 
function GETLOGIN() {
103 104 105 106
    global $CHECKLOGIN_USER;
    
    if (CheckLogin($status))
	return $CHECKLOGIN_USER->uid();
107 108 109 110 111 112 113 114 115 116

    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
117
    global $TBNAMECOOKIE;
118
    $status_archived = TBDB_USERSTATUS_ARCHIVED;
119
    $status_nonlocal = TBDB_USERSTATUS_NONLOCAL;
120

Leigh B. Stoller's avatar
Leigh B. Stoller committed
121
    if (isset($_GET['nocookieuid'])) {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	$uid = $_GET['nocookieuid'];
	
	#
	# XXX - nocookieuid is sent by netbuild applet in URL. A few other java
        # apps as well, and we retain this for backwards compatability.
	#
        # Pedantic check
	if (! preg_match("/^[-\w]+$/", $uid)) {
	    return FALSE;
	}
	$safe_uid = addslashes($uid);

	#
	# Map this to an index (from a uid).
	#
	$query_result =
138 139
	    DBQueryFatal("select uid_idx from users ".
			 "where uid='$safe_uid' and ".
140 141
			 "      status!='$status_archived' and ".
			 "      status!='$status_nonlocal'");
142 143 144 145 146 147
    
	if (! mysql_num_rows($query_result))
	    return FALSE;
	
	$row = mysql_fetch_array($query_result);
	return $row[0];
Chad Barb's avatar
 
Chad Barb committed
148
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
149
    elseif (isset($_COOKIE[$TBNAMECOOKIE])) {
150 151 152 153 154 155 156 157
	$idx = $_COOKIE[$TBNAMECOOKIE];

        # Pedantic check
	if (! preg_match("/^[-\w]+$/", $idx)) {
	    return FALSE;
	}

	return $idx;
Chad Barb's avatar
 
Chad Barb committed
158
    }
159
    return FALSE;
160 161
}

162
#
163
# Verify a login by sucking UIDs current hash value out of the database.
164 165 166
# 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.
#
167
# Returns a combination of the CHECKLOGIN values above.
168
#
169
function LoginStatus() {
170
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $HTTP_COOKIE_VARS, $TBAUTHTIMEOUT;
171
    global $CHECKLOGIN_STATUS, $CHECKLOGIN_UID, $CHECKLOGIN_NODETYPES;
172
    global $CHECKLOGIN_WIKINAME, $TBOPSPID;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
173
    global $EXPOSEARCHIVE, $EXPOSETEMPLATES;
174
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_HASHHASH;
175
    global $CHECKLOGIN_IDX, $CHECKLOGIN_USER;
176
    
177 178 179 180 181 182
    #
    # If we already figured this out, do not duplicate work!
    #
    if ($CHECKLOGIN_STATUS != CHECKLOGIN_NOSTATUS) {
	return $CHECKLOGIN_STATUS;
    }
183 184 185 186 187 188 189

    # No UID in the browser? Obviously not logged in!
    if (($uid_idx = GETUID()) == FALSE) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
    $CHECKLOGIN_IDX = $uid_idx;
190

Chad Barb's avatar
 
Chad Barb committed
191 192
    # for java applet, we can send the key in the $auth variable,
    # rather than passing it is a cookie.
193 194
    if (isset($_GET['nocookieauth'])) {
	$curhash = $_GET['nocookieauth'];
195 196
    }
    elseif (array_key_exists($TBAUTHCOOKIE, $HTTP_COOKIE_VARS)) {
Chad Barb's avatar
 
Chad Barb committed
197 198
	$curhash = $HTTP_COOKIE_VARS[$TBAUTHCOOKIE];
    }
199 200 201
    if (array_key_exists($TBLOGINCOOKIE, $HTTP_COOKIE_VARS)) {
	$hashhash = $HTTP_COOKIE_VARS[$TBLOGINCOOKIE];
    }
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

    #
    # 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;
    }
221 222 223 224 225 226 227

    if (isset($curhash)) {
	$CHECKLOGIN_HASHKEY = $safe_curhash = addslashes($curhash);
    }
    if (isset($hashhash)) {
	$CHECKLOGIN_HASHHASH = $safe_hashhash = addslashes($hashhash);
    }
228
    $safe_idx = addslashes($uid_idx);
Chad Barb's avatar
 
Chad Barb committed
229
    
230 231 232 233
    #
    # Note that we get multiple rows back because of the group_membership
    # join. No big deal.
    # 
234
    $query_result =
235
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout, ".
236
		     "       status,admin,cvsweb,g.trust,l.adminon,webonly, " .
237
		     "       user_interface,n.type,u.stud,u.wikiname, ".
238
		     "       u.wikionly,g.pid,u.foreign_admin,u.uid_idx, " .
Leigh B. Stoller's avatar
Leigh B. Stoller committed
239
		     "       p.allow_workbench,u.weblogin_frozen ".
240
		     " from users as u ".
241 242
		     "left join login as l on l.uid_idx=u.uid_idx ".
		     "left join group_membership as g on g.uid_idx=u.uid_idx ".
243
		     "left join projects as p on p.pid_idx=g.pid_idx ".
244
		     "left join nodetypeXpid_permissions as n on g.pid=n.pid ".
245
		     "where u.uid_idx='$safe_idx' and ".
246 247 248
		     (isset($curhash) ?
		      "l.hashkey='$safe_curhash'" :
		      "l.hashhash='$safe_hashhash'"));
249

250
    # No such user.
251 252 253 254 255 256 257
    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
258
    # values and the pid. pid is a hack.
259
    #
260 261 262
    $trusted   = 0;
    $opsguy    = 0;
    $workbench = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
263
    $frozen    = 0;
264
    
265 266 267 268 269 270 271 272 273 274 275 276
    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;
	}
277
	$adminon  = $row[7];
278
	$webonly  = $row[8];
279
	$interface= $row[9];
280 281

	$type     = $row[10];
282
	$stud     = $row[11];
283
	$wikiname = $row[12];
284
	$wikionly = $row[13];
285

286 287 288 289 290
	# Check for an ops guy.
	$pid = $row[14];
	if ($pid == $TBOPSPID) {
	    $opsguy = 1;
	}
291 292 293

	# Set foreign_admin=1 for admins of another Emulab.
	$foreign_admin   = $row[15];
294
	$uid_idx         = $row[16];
295
	$workbench      += $row[17];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
296
	$frozen          = $row[18];
297

298
	$CHECKLOGIN_NODETYPES[$type] = 1;
299
    }
300 301 302 303

    #
    # If user exists, but login has no entry, quit now.
    #
304 305 306 307
    if (!$hashkey) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
308

309
    #
310
    # Check for frozen account. Might do something interesting later.
311
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
312 313
    if ($frozen ||
	$status == TBDB_USERSTATUS_FROZEN) {
314
	DBQueryFatal("DELETE FROM login WHERE uid_idx='$uid_idx'");
315 316
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
317 318
    }

319
    #
320 321
    # Check for expired login. Remove this entry from the logins table to
    # keep it from getting cluttered.
322
    #
323
    if (time() > $timeout) {
324 325
	DBQueryFatal("delete from login where ".
		     "uid_idx='$uid_idx' and hashkey='$hashkey'");
326 327 328
	$CHECKLOGIN_STATUS = CHECKLOGIN_TIMEDOUT;
	return $CHECKLOGIN_STATUS;
    }
329
    $CHECKLOGIN_IDLETIME = time() - ($timeout - $TBAUTHTIMEOUT);
330 331

    #
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    # 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).
347
	#
348 349 350 351 352 353 354 355 356
	if ($curhash != $hashkey) {
	    #
	    # User is not logged in from this browser. Must be stale.
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
	else {
            #
357 358
	    # User is logged in.
	    #
359 360
	    $CHECKLOGIN_STATUS = CHECKLOGIN_LOGGEDIN;
	}
361 362
    }
    else {
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	#
	# 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;
	}
384 385
    }

386 387 388 389 390 391 392
    # Cache this now; someone will eventually want it.
    $CHECKLOGIN_USER = User::Lookup($uid_idx);
    if (! $CHECKLOGIN_USER) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }

393
    #
394
    # Now add in the modifiers.
395
    #
396 397
    # Do not expire passwords for admin users.
    if ($expired && !$admin)
398 399 400
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PSWDEXPIRED;
    if ($admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISADMIN;
401 402
    if ($adminon)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ADMINON;
403 404
    if ($webonly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WEBONLY;
405 406
    if ($wikionly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WIKIONLY;
407 408
    if ($trusted)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_TRUSTED;
409 410
    if ($stud)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_STUDLY;
411 412
    if ($cvsweb)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_CVSWEB;
413
    if ($interface == TBDB_USER_INTERFACE_PLAB)
414
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PLABUSER;
415 416 417 418 419 420 421 422
    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;
423 424
    if (isset($wikiname) && $wikiname != "")
	$CHECKLOGIN_WIKINAME = $wikiname;
425 426
    if ($opsguy)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_OPSGUY;
427 428
    if ($foreign_admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISFOREIGN_ADMIN;
429

430 431 432
    #
    # Set the magic enviroment variable, if appropriate, for the sake of
    # any processes we might spawn. We prepend an HTTP_ on the front of
433
    # the variable name, so that it will get through suexec.
434
    #
435
    if ($admin && $adminon) {
436 437
    	putenv("HTTP_WITH_TB_ADMIN_PRIVS=1");
    }
438 439 440 441 442 443 444 445 446
    #
    # This environment variable is likely to become the new method for
    # specifying the credentials of the invoking user. Still thinking
    # about this, but the short story is that the web interface should
    # not invoke so much stuff as the user, but rather as a neutral user
    # with implied credentials. 
    #
    putenv("HTTP_INVOKING_USER=" . $CHECKLOGIN_USER->webid());
    
447 448 449
    # XXX Temporary.
    if ($stud) {
	$EXPOSEARCHIVE = 1;
450 451 452
    }
    if ($workbench) {
	$EXPOSETEMPLATES = $EXPOSEARCHIVE = 1;
453
    }
454
    return $CHECKLOGIN_STATUS;
455 456 457 458
}

#
# This one checks for login, but then dies with an appropriate error
459 460
# message. The modifier allows you to turn off checks for specified
# conditions. 
461
#
462
function LOGGEDINORDIE($uid, $modifier = 0, $login_url = NULL) {
463
    global $TBBASE, $BASEPATH;
464
    global $TBAUTHTIMEOUT, $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
465 466 467 468 469 470 471 472 473 474 475
    global $drewheader;

    if ($drewheader) {
	trigger_error(
	    "PAGEHEADER called before LOGGEDINORDIE ".
	    "(called by CheckLoginOrDie). ".
	    "Won't be able to redirect to the login page or ".
            "return proper HTTP status code on Error ".
	    "in ". $_SERVER['SCRIPT_FILENAME'] . ",",
	    E_USER_WARNING);
    }
476

477
    #
478 479 480 481 482
    # We now ignore the $uid argument and let LoginStatus figure it out.
    #
    
    #
    # Allow the caller to specify a different URL to direct the user to
483
    #
484
    $redirect_url = null;
485 486
    if (!$login_url) {
	$login_url = "$TBBASE/login.php3?refer=1";
487 488 489 490 491 492
        if ($uid || REMEMBERED_ID()) {
	    # HTTP_REFERER will not work reliably when redirecting so
	    # pass in the URI for this page as an argument
	    $redirect_url = "$TBBASE/login.php3?referrer=".
                            urlencode($_SERVER['REQUEST_URI']);
	}
493 494 495
    }

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

498
    $status = LoginStatus();
499 500 501

    switch ($status & CHECKLOGIN_STATUSMASK) {
    case CHECKLOGIN_NOTLOGGEDIN:
502 503 504 505 506 507 508
	if ($redirect_url) {
	    header("Location: $redirect_url&error=notloggedin");
	    exit;
        } else {
            USERERROR("You do not appear to be logged in! $link",
		      1, HTTP_403_FORBIDDEN);
        }
509
        break;
510
    case CHECKLOGIN_TIMEDOUT:
511 512 513 514 515 516 517
	if ($redirect_url) {
	    header("Location: $redirect_url&error=timedout");
	    exit;
        } else {
            USERERROR("Your login has timed out! $link",
		      1, HTTP_403_FORBIDDEN);
        }
518
        break;
519
    case CHECKLOGIN_MAYBEVALID:
520 521 522 523
	# This error can happen if a user tries to access a page with
	# via http instead of https, so try to redirect to https first
	RedirectHTTPS(); # will not return if accesses via http
	USERERROR("Your login cannot be verified. Are cookies turned on? ".
524
		  "Are you using https? Are you logged in using another ".
525
		  "browser or another machine? $link", 1, HTTP_403_FORBIDDEN);
526
        break;
527
    case CHECKLOGIN_LOGGEDIN:
528 529 530 531 532 533
        #
	# 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.
        #
534 535
	if (! is_null($CHECKLOGIN_HASHKEY)) {
	    $timeout = time() + $TBAUTHTIMEOUT;
536

537
	    DBQueryFatal("UPDATE login set timeout='$timeout' ".
538 539
			 "where uid_idx='$CHECKLOGIN_IDX' and ".
			 "      hashkey='$CHECKLOGIN_HASHKEY'");
540
	}
541 542 543
	break;
    default:
	TBERROR("LOGGEDINORDIE failed mysteriously", 1);
544
    }
545 546 547 548 549 550 551

    $status = $status & ~$modifier;

    #
    # Check other conditions.
    #
    if ($status & CHECKLOGIN_PSWDEXPIRED)
552
        USERERROR("Your password has expired. ".
553 554
		  "<a href=moduserinfo.php3>Please change it now!</a>",
		  1, HTTP_403_FORBIDDEN);
555
    if ($status & CHECKLOGIN_FROZEN)
556 557
        USERERROR("Your account has been frozen!",
		  1, HTTP_403_FORBIDDEN);
558
    if ($status & (CHECKLOGIN_UNVERIFIED|CHECKLOGIN_NEWUSER))
559 560
        USERERROR("You have not verified your account yet!",
		  1, HTTP_403_FORBIDDEN);
561
    if ($status & CHECKLOGIN_UNAPPROVED)
562 563
        USERERROR("Your account has not been approved yet!",
		  1, HTTP_403_FORBIDDEN);
564
    if (($status & CHECKLOGIN_WEBONLY) && ! ISADMIN())
565 566
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
567
    if (($status & CHECKLOGIN_WIKIONLY) && ! ISADMIN())
568 569
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
570 571 572 573 574

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

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
    # No one should ever look at the return value of this function.
    return null;
}

#
# This is the new interface to the above function. 
#
function CheckLoginOrDie($modifier = 0, $login_url = NULL)
{
    global $CHECKLOGIN_USER;
    
    LOGGEDINORDIE(GETUID(), $modifier, $login_url);

    #
    # If this returns, login is valid. Return the user object to caller.
    #
    return $CHECKLOGIN_USER;
}

#
# This interface allows the return of the actual status. I know, its a
# global variable, but this interface is cleaner. 
#
function CheckLogin(&$status)
{
    global $CHECKLOGIN_USER;

    $status = LoginStatus();

    # If login looks valid, return the user. 
    if ($status & (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_MAYBEVALID))
	    return $CHECKLOGIN_USER;

    return null;
613 614 615
}

#
616 617 618 619
# 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.
620
#
621
function ISADMIN() {
622 623
    global $CHECKLOGIN_STATUS;
    
624
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
625
	return 0;
626
    }
627

628
    return (($CHECKLOGIN_STATUS &
629 630
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON)) ==
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON));
631 632
}

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

# 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));
}

648 649 650 651
function STUDLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
652
	TBERROR("STUDLY: user is not logged in!", 1);
653 654 655 656 657 658 659
    }

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

660 661 662 663
function OPSGUY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
664
	TBERROR("OPSGUY: user is not logged in!", 1);
665 666 667 668 669 670 671
    }

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

672 673 674 675
function WIKIONLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
676
	TBERROR("WIKIONLY: user is not logged in!", 1);
677 678 679 680 681 682 683
    }

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

684
# Is this user a real administrator (ignore onoff bit).
685
function ISADMINISTRATOR() {
686 687 688 689 690 691 692 693 694 695
    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));
}

696 697 698
#
# Toggle current login admin bit. Must be an administrator of course!
#
699 700
function SETADMINMODE($onoff) {
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
701 702 703 704 705
    
    # This makes sure the user is actually logged in secure (https).
    if (! ISADMINISTRATOR())
	return;

706 707
    # Be pedantic.
    if (! ($CHECKLOGIN_HASHKEY && $CHECKLOGIN_IDX))
708
	return;
709

710
    $onoff   = addslashes($onoff);
711 712
    $curhash = addslashes($CHECKLOGIN_HASHKEY);
    $uid_idx = $CHECKLOGIN_IDX;
713 714
    
    DBQueryFatal("update login set adminon='$onoff' ".
715
		 "where uid_idx='$uid_idx' and hashkey='$curhash'");
716 717
}

718
# Is this user a planetlab user? Returns 1 if they are, 0 if not.
719 720 721
function ISPLABUSER() {
    global $CHECKLOGIN_STATUS;

722 723 724 725 726 727 728 729
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	#
	# For users who are not logged in, we need to check the database
	#
	$uid = GETUID();
	if (!$uid) {
	    return 0;
	}
730 731
	# Lookup sanitizes argument.
	if (! ($user = User::Lookup($uid)))
732
	    return 0;
733

734 735 736 737
	if ($user->user_interface()) {
	    return ($user->user_interface() == TBDB_USER_INTERFACE_PLAB);
	}
	else {
738 739
	    return 0;
	}
740
    } else {
741
	#
742
	# For logged-in users, we recorded it in the the login status
743 744
	#
	return (($CHECKLOGIN_STATUS &
745 746
		 (CHECKLOGIN_PLABUSER)) ==
		(CHECKLOGIN_PLABUSER));
747 748 749
    }
}

750 751 752 753 754 755 756 757 758 759 760 761
#
# 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;
762 763

    if (! GETUID())
764
	return 0;
765

Leigh B. Stoller's avatar
Leigh B. Stoller committed
766
    if (isset($CHECKLOGIN_NODETYPES[$type])) {
767 768 769 770 771 772
	return 1;
    } else {
	return 0;
    }
}

773 774 775
#
# Attempt a login.
# 
776
function DOLOGIN($token, $password, $adminmode = 0) {
777 778
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
779
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
780
    global $WIKISUPPORT, $WIKICOOKIENAME;
781
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
782 783
    
    # Caller makes these checks too.
784 785
    if ((!TBvalid_uid($token) && !TBvalid_email($token)) ||
	!isset($password) || $password == "") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
786
	return DOLOGIN_STATUS_ERROR;
787
    }
788
    $now = time();
789

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    #
    # 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'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
810
		return DOLOGIN_STATUS_IPFREEZE;
811 812 813 814
	    }
	}
    }

815 816 817 818 819 820 821
    if (TBvalid_email($token)) {
	$user = User::LookupByEmail($token);
    }
    else {
	$user = User::Lookup($token);
    }
	    
822 823 824
    #
    # Check password in the database against provided. 
    #
825
    do {
826 827 828 829 830 831 832 833 834
      if ($user) {
	$uid         = $user->uid();
        $db_encoding = $user->pswd();
	$isadmin     = $user->admin();
	$frozen      = $user->weblogin_frozen();
	$failcount   = $user->weblogin_failcount();
	$failstamp   = $user->weblogin_failstamp();
	$usr_email   = $user->email();
	$usr_name    = $user->name();
835
	$uid_idx     = $user->uid_idx();
836
	$usr_email   = $user->email();
837

838 839
	# Check for frozen accounts. We do not update the IP record when
	# an account is frozen.
840
	if ($frozen) {
841
	    $user->UpdateWebLoginFail();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
842
	    return DOLOGIN_STATUS_WEBFREEZE;
843 844
	}
	
845
        $encoding = crypt("$password", $db_encoding);
846
        if (strcmp($encoding, $db_encoding)) {
847
	    #
848
	    # Bump count and check for too many consecutive failures.
849 850 851
	    #
	    $failcount++;
	    if ($failcount > DOLOGIN_MAXUSERATTEMPTS) {
852 853
		$user->SetWebFreeze(1);
		
854 855 856 857 858 859 860 861 862 863
		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");
	    }
864
	    $user->UpdateWebLoginFail();
865
            break;
866
        }
867
	#
868
	# Pass!
869 870
	#

871
	#
872
	# Set adminmode off on new logins, unless user requested to be
873 874 875 876
	# 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. 
877
	#
878
	$adminon = 0;
879
	if ($adminmode && $isadmin) {
880
	    $adminon = 1;
881
	}
882 883 884 885

        #
        # Insert a record in the login table for this uid.
	#
886
	if (DOLOGIN_MAGIC($uid, $uid_idx, $usr_email, $adminon) < 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
887
	    return DOLOGIN_STATUS_ERROR;
888 889 890 891 892 893 894 895 896
	}

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

898 899 900 901
	# Clear IP record since we have a sucessful login from the IP.
	if (isset($IP)) {
	    DBQueryFatal("delete from login_failures where IP='$IP'");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
902
	return DOLOGIN_STATUS_OKAY;
903 904
      }
    } while (0);
905 906 907
    #
    # No such user
    #
908
    if (!isset($IP)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
909
	return DOLOGIN_STATUS_ERROR;
910
    }
911

912
    $ipfrozen = 0;
913 914 915 916
    if (isset($iprow)) {
	$ipfailcount = $iprow['failcount'];

        #
917
        # Bump count.
918 919 920 921
        #
	$ipfailcount++;
    }
    else {
922 923 924
	#
	# First failure.
	# 
925 926
	$ipfailcount = 1;
    }
927 928 929 930

    #
    # Check for too many consecutive failures.
    #
931 932 933 934 935 936
    if ($ipfailcount > DOLOGIN_MAXIPATTEMPTS) {
	$ipfrozen = 1;
	    
	TBMAIL($TBMAIL_OPS,
	       "Web Login Freeze: '$IP'",
	       "Logins has been frozen because there were too many login\n".
937
	       "failures from $IP. Last attempted uid was '$token'.\n\n",
938 939 940 941 942 943 944 945
	       "From: $TBMAIL_OPS\n".
	       "Bcc: $TBMAIL_AUDIT\n".
	       "Errors-To: $TBMAIL_WWW");
    }
    DBQueryFatal("replace into login_failures set ".
		 "       IP='$IP', ".
		 "       frozen='$ipfrozen', ".
		 "       failcount='$ipfailcount', ".
946
		 "       failstamp='$now'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
947
    return DOLOGIN_STATUS_ERROR;
948 949
}

950
function DOLOGIN_MAGIC($uid, $uid_idx, $email = null, $adminon = 0)
951
{
952
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT, $WWWHOST;
953
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES, $TBEMAILCOOKIE;
954 955
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
    global $WIKISUPPORT, $WIKICOOKIENAME;
956
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME, $TRACSUPPORT, $TRACCOOKIENAME;
957
    global $TBLIBEXEC_DIR, $EXP_VIS;
958 959 960 961 962
    
    # Caller makes these checks too.
    if (!TBvalid_uid($uid)) {
	return -1;
    }
963 964 965
    if (!TBvalid_uididx($uid_idx)) {
	return -1;
    }
966 967 968 969 970 971 972 973 974
    $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();
975
    $crc     = bin2hex(mhash(MHASH_CRC32, $hashkey));
976
    $opskey  = GENHASH();
977

978
    DBQueryFatal("replace into login ".
979 980
		 "  (uid,uid_idx,hashkey,hashhash,timeout,adminon,opskey) values ".
		 "  ('$uid', $uid_idx, '$hashkey', '$crc', '$timeout', $adminon, '$opskey')");