tbauth.php3 42.6 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2017 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
23 24
#
#
25
# Login support: Beware empty spaces (cookies)!
26 27
#

28 29 30 31
# These global are to prevent repeated calls to the DB. 
#
$CHECKLOGIN_STATUS		= -1;
$CHECKLOGIN_UID			= 0;
32
$CHECKLOGIN_IDX			= null;
33
$CHECKLOGIN_NOLOGINS		= -1;
34
$CHECKLOGIN_WIKINAME            = "";
35 36
$CHECKLOGIN_HASHKEY             = null;
$CHECKLOGIN_HASHHASH            = null;
37
$CHECKLOGIN_USER                = null;
38 39 40 41 42 43 44 45 46

#
# New Mapping. 
#
define("CHECKLOGIN_NOSTATUS",		-1);
define("CHECKLOGIN_NOTLOGGEDIN",	0);
define("CHECKLOGIN_LOGGEDIN",		1);
define("CHECKLOGIN_TIMEDOUT",		2);
define("CHECKLOGIN_MAYBEVALID",		4);
47 48
define("CHECKLOGIN_STATUSMASK",		0x00000ff);
define("CHECKLOGIN_MODMASK",		0xfffff00);
49 50 51 52 53
#
# 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. 
#
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
define("CHECKLOGIN_NEWUSER",		0x0000100);
define("CHECKLOGIN_UNVERIFIED",		0x0000200);
define("CHECKLOGIN_UNAPPROVED",		0x0000400);
define("CHECKLOGIN_ACTIVE",		0x0000800);
define("CHECKLOGIN_USERSTATUS",		0x0000f00);
define("CHECKLOGIN_PSWDEXPIRED",	0x0001000);
define("CHECKLOGIN_FROZEN",		0x0002000);
define("CHECKLOGIN_ISADMIN",		0x0004000);
define("CHECKLOGIN_TRUSTED",		0x0008000);
define("CHECKLOGIN_CVSWEB",		0x0010000);
define("CHECKLOGIN_ADMINON",		0x0020000);
define("CHECKLOGIN_WEBONLY",		0x0040000);
define("CHECKLOGIN_PLABUSER",		0x0080000);
define("CHECKLOGIN_STUDLY",		0x0100000);
define("CHECKLOGIN_WIKIONLY",		0x0200000);
define("CHECKLOGIN_OPSGUY",		0x0400000);  # Member of emulab-ops.
define("CHECKLOGIN_ISFOREIGN_ADMIN",	0x0800000);  # Admin of another Emulab.
define("CHECKLOGIN_NONLOCAL",		0x1000000);
72
define("CHECKLOGIN_INACTIVE",		0x2000000);
73

74 75 76
#
# Constants for tracking possible login attacks.
#
77 78
define("DOLOGIN_MAXUSERATTEMPTS",	10);
define("DOLOGIN_MAXIPATTEMPTS",		15);
79

Leigh B. Stoller's avatar
Leigh B. Stoller committed
80 81 82 83 84 85
# 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);
86
define("DOLOGIN_STATUS_INACTIVE",	-4);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
87

88 89 90
# So we can redefine this in the APT pages.
$CHANGEPSWD_PAGE = "moduserinfo.php3";

91 92 93 94 95 96 97 98 99
#
# 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
100
    $random_bytes = fread($fp, 128);
101 102
    fclose($fp);

103
    $hash  = mhash (MHASH_MD5, bin2hex($random_bytes) . " " . microtime());
104 105 106
    return bin2hex($hash);
}

107 108 109 110 111 112 113 114 115 116 117 118
#
# 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;
}
119 120 121 122 123 124
function ClearRememberedID()
{
    global $TBEMAILCOOKIE, $WWWHOST;
    
    setcookie($TBEMAILCOOKIE, '', 1, "/", $WWWHOST, 0);
}
125

126 127
#
# Return the value of the currently logged in uid, or null if not
128
# logged in. This interface is deprecated and being replaced.
129 130
# 
function GETLOGIN() {
131 132 133 134
    global $CHECKLOGIN_USER;
    
    if (CheckLogin($status))
	return $CHECKLOGIN_USER->uid();
135 136 137 138 139 140 141 142 143 144

    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
145
    global $TBNAMECOOKIE;
146
    $status_archived = TBDB_USERSTATUS_ARCHIVED;
147
    $status_nonlocal = TBDB_USERSTATUS_NONLOCAL;
148

Leigh B. Stoller's avatar
Leigh B. Stoller committed
149
    if (isset($_GET['nocookieuid'])) {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
	$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 =
166 167
	    DBQueryFatal("select uid_idx from users ".
			 "where uid='$safe_uid' and ".
168 169
			 "      status!='$status_archived' and ".
			 "      status!='$status_nonlocal'");
170 171 172 173 174 175
    
	if (! mysql_num_rows($query_result))
	    return FALSE;
	
	$row = mysql_fetch_array($query_result);
	return $row[0];
Chad Barb's avatar
 
Chad Barb committed
176
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
177
    elseif (isset($_COOKIE[$TBNAMECOOKIE])) {
178 179 180 181 182 183 184 185
	$idx = $_COOKIE[$TBNAMECOOKIE];

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

	return $idx;
Chad Barb's avatar
 
Chad Barb committed
186
    }
187
    return FALSE;
188 189
}

190
#
191
# Verify a login by sucking UIDs current hash value out of the database.
192 193 194
# 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.
#
195
# Returns a combination of the CHECKLOGIN values above.
196
#
197
function LoginStatus() {
198
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHTIMEOUT;
199
    global $CHECKLOGIN_STATUS, $CHECKLOGIN_UID, $CHECKLOGIN_NODETYPES;
200
    global $CHECKLOGIN_WIKINAME, $TBOPSPID;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201
    global $EXPOSEARCHIVE, $EXPOSETEMPLATES;
202
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_HASHHASH;
203
    global $CHECKLOGIN_IDX, $CHECKLOGIN_USER;
204
    
205 206 207 208 209 210
    #
    # If we already figured this out, do not duplicate work!
    #
    if ($CHECKLOGIN_STATUS != CHECKLOGIN_NOSTATUS) {
	return $CHECKLOGIN_STATUS;
    }
211 212 213 214 215 216 217

    # 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;
218

Chad Barb's avatar
 
Chad Barb committed
219 220
    # for java applet, we can send the key in the $auth variable,
    # rather than passing it is a cookie.
221 222
    if (isset($_GET['nocookieauth'])) {
	$curhash = $_GET['nocookieauth'];
223
    }
224 225
    elseif (array_key_exists($TBAUTHCOOKIE, $_COOKIE)) {
	$curhash = $_COOKIE[$TBAUTHCOOKIE];
Chad Barb's avatar
 
Chad Barb committed
226
    }
227 228
    if (array_key_exists($TBLOGINCOOKIE, $_COOKIE)) {
	$hashhash = $_COOKIE[$TBLOGINCOOKIE];
229
    }
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

    #
    # 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;
    }
249 250 251 252 253 254 255

    if (isset($curhash)) {
	$CHECKLOGIN_HASHKEY = $safe_curhash = addslashes($curhash);
    }
    if (isset($hashhash)) {
	$CHECKLOGIN_HASHHASH = $safe_hashhash = addslashes($hashhash);
    }
256
    $safe_idx = addslashes($uid_idx);
Chad Barb's avatar
 
Chad Barb committed
257
    
258 259 260 261
    #
    # Note that we get multiple rows back because of the group_membership
    # join. No big deal.
    # 
262
    $query_result =
263
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout, ".
264
		     "       status,admin,cvsweb,g.trust,l.adminon,webonly, " .
265
		     "       user_interface,n.type,u.stud,u.wikiname, ".
266
		     "       u.wikionly,g.pid,u.foreign_admin,u.uid_idx, " .
267 268
		     "       p.allow_workbench,u.weblogin_frozen, ".
                     "       u.nonlocal_id ".
269
		     " from users as u ".
270 271
		     "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 ".
272
		     "left join projects as p on p.pid_idx=g.pid_idx ".
273
		     "left join nodetypeXpid_permissions as n on g.pid=n.pid ".
274
		     "where u.uid_idx='$safe_idx' and ".
275 276 277
		     (isset($curhash) ?
		      "l.hashkey='$safe_curhash'" :
		      "l.hashhash='$safe_hashhash'"));
278

279
    # No such user.
280 281 282 283 284 285 286
    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
287
    # values and the pid. pid is a hack.
288
    #
289 290 291
    $trusted   = 0;
    $opsguy    = 0;
    $workbench = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
292
    $frozen    = 0;
293
    $nonlocal  = 0;
294
    
295 296 297 298 299 300 301 302 303 304 305 306
    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;
	}
307
	$adminon  = $row[7];
308
	$webonly  = $row[8];
309
	$interface= $row[9];
310 311

	$type     = $row[10];
312
	$stud     = $row[11];
313
	$wikiname = $row[12];
314
	$wikionly = $row[13];
315

316 317 318 319 320
	# Check for an ops guy.
	$pid = $row[14];
	if ($pid == $TBOPSPID) {
	    $opsguy = 1;
	}
321 322 323

	# Set foreign_admin=1 for admins of another Emulab.
	$foreign_admin   = $row[15];
324
	$uid_idx         = $row[16];
325
	$workbench      += $row[17];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
326
	$frozen          = $row[18];
327
	$nonlocal        = $row[19] ? 1 : 0;
328

329
	$CHECKLOGIN_NODETYPES[$type] = 1;
330
    }
331 332 333 334

    #
    # If user exists, but login has no entry, quit now.
    #
335 336 337 338
    if (!$hashkey) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
339

340
    #
341
    # Check for frozen account. Might do something interesting later.
342
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
343 344
    if ($frozen ||
	$status == TBDB_USERSTATUS_FROZEN) {
345
	DBQueryFatal("DELETE FROM login WHERE uid_idx='$uid_idx'");
346 347
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
348
    }
349 350 351 352 353
    if ($status == TBDB_USERSTATUS_INACTIVE) {
	DBQueryFatal("DELETE FROM login WHERE uid_idx='$uid_idx'");
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
354

355
    #
356 357
    # Check for expired login. Remove this entry from the logins table to
    # keep it from getting cluttered.
358
    #
359
    if (time() > $timeout) {
360 361
	DBQueryFatal("delete from login where ".
		     "uid_idx='$uid_idx' and hashkey='$hashkey'");
362 363 364 365 366
	$CHECKLOGIN_STATUS = CHECKLOGIN_TIMEDOUT;
	return $CHECKLOGIN_STATUS;
    }

    #
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    # 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).
382
	#
383 384 385 386 387 388 389 390 391
	if ($curhash != $hashkey) {
	    #
	    # User is not logged in from this browser. Must be stale.
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
	else {
            #
392 393
	    # User is logged in.
	    #
394 395
	    $CHECKLOGIN_STATUS = CHECKLOGIN_LOGGEDIN;
	}
396 397
    }
    else {
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
	#
	# 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;
	}
418
	return $CHECKLOGIN_STATUS;
419 420
    }

421 422 423 424 425 426
    # Cache this now; someone will eventually want it.
    $CHECKLOGIN_USER = User::Lookup($uid_idx);
    if (! $CHECKLOGIN_USER) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
427 428 429 430 431 432
    $ga_userid = $CHECKLOGIN_USER->ga_userid();
    if (!$ga_userid) {
        $ga_userid = substr(GENHASH(), 0, 32);
        $CHECKLOGIN_USER->SetGaUserid($ga_userid);
    }
    
433
    #
434
    # Now add in the modifiers.
435
    #
436
    # Do not expire passwords for admin users.
437
    if (!is_null($expired) && $expired && !$admin)
438 439 440
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PSWDEXPIRED;
    if ($admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISADMIN;
441 442
    if ($adminon)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ADMINON;
443 444
    if ($webonly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WEBONLY;
445 446
    if ($wikionly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WIKIONLY;
447 448
    if ($trusted)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_TRUSTED;
449 450
    if ($stud)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_STUDLY;
451 452
    if ($cvsweb)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_CVSWEB;
453
    if ($interface == TBDB_USER_INTERFACE_PLAB)
454
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PLABUSER;
455 456 457 458 459 460 461 462
    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;
463 464
    if (strcmp($status, TBDB_USERSTATUS_INACTIVE) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_INACTIVE;
465 466
    if (isset($wikiname) && $wikiname != "")
	$CHECKLOGIN_WIKINAME = $wikiname;
467 468
    if ($opsguy)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_OPSGUY;
469 470
    if ($foreign_admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISFOREIGN_ADMIN;
471 472
    if ($nonlocal)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_NONLOCAL;
473

474 475 476
    #
    # Set the magic enviroment variable, if appropriate, for the sake of
    # any processes we might spawn. We prepend an HTTP_ on the front of
477
    # the variable name, so that it will get through suexec.
478
    #
479
    if ($admin && $adminon) {
480 481
    	putenv("HTTP_WITH_TB_ADMIN_PRIVS=1");
    }
482 483 484 485 486 487 488 489 490
    #
    # 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());
    
491 492 493
    # XXX Temporary.
    if ($stud) {
	$EXPOSEARCHIVE = 1;
494 495 496
    }
    if ($workbench) {
	$EXPOSETEMPLATES = $EXPOSEARCHIVE = 1;
497
    }
498
    return $CHECKLOGIN_STATUS;
499 500 501 502
}

#
# This one checks for login, but then dies with an appropriate error
503 504
# message. The modifier allows you to turn off checks for specified
# conditions. 
505
#
506
function LOGGEDINORDIE($uid, $modifier = 0, $login_url = NULL) {
507
    global $TBBASE, $BASEPATH;
508
    global $TBAUTHTIMEOUT, $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
509 510 511 512 513 514 515 516 517 518 519
    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);
    }
520

521
    #
522 523 524 525 526
    # 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
527
    #
528
    $redirect_url = null;
529 530
    if (!$login_url) {
	$login_url = "$TBBASE/login.php3?refer=1";
531 532 533 534 535 536
        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']);
	}
537 538 539
    }

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

542
    $status = LoginStatus();
543 544 545

    switch ($status & CHECKLOGIN_STATUSMASK) {
    case CHECKLOGIN_NOTLOGGEDIN:
546 547 548 549 550 551 552
	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);
        }
553
        break;
554
    case CHECKLOGIN_TIMEDOUT:
555 556 557 558 559 560 561
	if ($redirect_url) {
	    header("Location: $redirect_url&error=timedout");
	    exit;
        } else {
            USERERROR("Your login has timed out! $link",
		      1, HTTP_403_FORBIDDEN);
        }
562
        break;
563
    case CHECKLOGIN_MAYBEVALID:
564 565 566 567
	# 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? ".
568
		  "Are you using https? Are you logged in using another ".
569
		  "browser or another machine? $link", 1, HTTP_403_FORBIDDEN);
570
        break;
571
    case CHECKLOGIN_LOGGEDIN:
572
	BumpLogoutTime();
573 574 575
	break;
    default:
	TBERROR("LOGGEDINORDIE failed mysteriously", 1);
576
    }
577

578
    CheckLoginConditions($status & ~$modifier);
579

580 581 582 583 584 585 586 587 588
    # No one should ever look at the return value of this function.
    return null;
}

#
# Check other conditions.
#
function CheckLoginConditions($status)
{
589
    global $CHANGEPSWD_PAGE, $TBMAILADDR;
590
    
591
    if ($status & CHECKLOGIN_PSWDEXPIRED)
592
        USERERROR("Your password has expired. ".
593
		  "<a href='$CHANGEPSWD_PAGE'>Please change it now.</a>",
594
		  1, HTTP_403_FORBIDDEN);
595
    if ($status & CHECKLOGIN_FROZEN)
596 597
        USERERROR("Your account has been frozen!",
		  1, HTTP_403_FORBIDDEN);
598
    if ($status & CHECKLOGIN_INACTIVE)
599 600
        USERERROR("Your account has gone inactive since your last login was ".
                  "so long ago. Please contact $TBMAILADDR to restore it.",
601
		  1, HTTP_403_FORBIDDEN);
602
    if ($status & (CHECKLOGIN_UNVERIFIED|CHECKLOGIN_NEWUSER))
603 604
        USERERROR("You have not verified your account yet!",
		  1, HTTP_403_FORBIDDEN);
605
    if ($status & CHECKLOGIN_UNAPPROVED)
606 607 608 609
        USERERROR("Your account has not been approved yet! ".
                  "<br>Please wait till ".
                  "your account is approved (you will receive email) and then ".
                  "reload this page.",
610
		  1, HTTP_403_FORBIDDEN);
611
    if (($status & CHECKLOGIN_WEBONLY) && ! ISADMIN())
612 613
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
614 615 616
    if ($status & CHECKLOGIN_NONLOCAL)
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
617
    if (($status & CHECKLOGIN_WIKIONLY) && ! ISADMIN())
618 619
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
620 621 622 623 624

    #
    # Lastly, check for nologins here. This heads off a bunch of other
    # problems and checks we would need.
    #
625
    if (NOLOGINS() && !ISADMIN())
626
        USERERROR("Sorry. The Web Interface is ".
627
		  "temporarily unavailable. Please check back later.", 1);
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
}

#
# 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)
{
651
    global $CHECKLOGIN_USER, $CHECKLOGIN_STATUS;
652 653 654 655

    $status = LoginStatus();

    # If login looks valid, return the user. 
656 657 658 659 660 661 662 663 664 665 666
    if ($status & (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_MAYBEVALID)) {
	#
        # Check for NOLOGINS. 
        # We want to allow admin types to continue using the web interface,
        # and logout anyone else that is currently logged in!
	#
	if (NOLOGINS() && !ISADMIN()) {
	    DOLOGOUT($CHECKLOGIN_USER);
	    $status = $CHECKLOGIN_STATUS;
	    return null;
	}
667 668 669 670 671
	if ($status & CHECKLOGIN_LOGGEDIN) {
	    BumpLogoutTime();
	}
	return $CHECKLOGIN_USER;
    }
672
    return null;
673 674 675
}

#
676 677 678 679
# 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.
680
#
681
function ISADMIN() {
682 683
    global $CHECKLOGIN_STATUS;
    
684
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
685
	return 0;
686
    }
687

688
    return (($CHECKLOGIN_STATUS &
689 690
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON)) ==
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON));
691 692
}

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

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

708 709 710 711
function STUDLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
712
	TBERROR("STUDLY: user is not logged in!", 1);
713 714 715 716 717 718 719
    }

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

720 721 722 723
function OPSGUY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
724
	TBERROR("OPSGUY: user is not logged in!", 1);
725 726 727 728 729 730 731
    }

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

732 733 734 735
function WIKIONLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
736
	TBERROR("WIKIONLY: user is not logged in!", 1);
737 738 739 740 741 742 743
    }

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

744
# Is this user a real administrator (ignore onoff bit).
745
function ISADMINISTRATOR() {
746 747 748
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS)
Leigh B Stoller's avatar
Leigh B Stoller committed
749
	TBERROR("ISADMINISTRATOR: $uid is not logged in!", 1);
750 751 752 753 754 755

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

756 757 758
#
# Toggle current login admin bit. Must be an administrator of course!
#
759 760
function SETADMINMODE($onoff) {
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
761 762 763 764 765
    
    # This makes sure the user is actually logged in secure (https).
    if (! ISADMINISTRATOR())
	return;

766 767
    # Be pedantic.
    if (! ($CHECKLOGIN_HASHKEY && $CHECKLOGIN_IDX))
768
	return;
769

770
    $onoff   = addslashes($onoff);
771 772
    $curhash = addslashes($CHECKLOGIN_HASHKEY);
    $uid_idx = $CHECKLOGIN_IDX;
773 774
    
    DBQueryFatal("update login set adminon='$onoff' ".
775
		 "where uid_idx='$uid_idx' and hashkey='$curhash'");
776 777
}

778
# Is this user a planetlab user? Returns 1 if they are, 0 if not.
779 780 781
function ISPLABUSER() {
    global $CHECKLOGIN_STATUS;

782 783 784 785 786 787 788 789
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	#
	# For users who are not logged in, we need to check the database
	#
	$uid = GETUID();
	if (!$uid) {
	    return 0;
	}
790 791
	# Lookup sanitizes argument.
	if (! ($user = User::Lookup($uid)))
792
	    return 0;
793

794 795 796 797
	if ($user->user_interface()) {
	    return ($user->user_interface() == TBDB_USER_INTERFACE_PLAB);
	}
	else {
798 799
	    return 0;
	}
800
    } else {
801
	#
802
	# For logged-in users, we recorded it in the the login status
803 804
	#
	return (($CHECKLOGIN_STATUS &
805 806
		 (CHECKLOGIN_PLABUSER)) ==
		(CHECKLOGIN_PLABUSER));
807 808 809
    }
}

810 811 812 813 814 815 816 817 818 819 820 821
#
# 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;
822 823

    if (! GETUID())
824
	return 0;
825

Leigh B. Stoller's avatar
Leigh B. Stoller committed
826
    if (isset($CHECKLOGIN_NODETYPES[$type])) {
827 828 829 830 831 832
	return 1;
    } else {
	return 0;
    }
}

833 834 835
#
# Attempt a login.
# 
836
function DOLOGIN($token, $password, $adminmode = 0, $nopassword = 0) {
837 838
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
839
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
840
    global $WIKISUPPORT, $WIKICOOKIENAME;
841
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME, $CHECKLOGIN_USER;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
842 843
    
    # Caller makes these checks too.
844
    if ((!TBvalid_uid($token) && !TBvalid_email($token)) ||
845
	((!isset($password) || $password == "") && !$nopassword)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
846
	return DOLOGIN_STATUS_ERROR;
847
    }
848
    $now = time();
849

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    #
    # 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
870
		return DOLOGIN_STATUS_IPFREEZE;
871 872 873 874
	    }
	}
    }

875 876 877 878 879 880 881
    if (TBvalid_email($token)) {
	$user = User::LookupByEmail($token);
    }
    else {
	$user = User::Lookup($token);
    }
	    
882 883 884
    #
    # Check password in the database against provided. 
    #
885
    do {
886 887 888 889 890 891 892 893 894
      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();
895
	$uid_idx     = $user->uid_idx();
896
	$usr_email   = $user->email();
897
        $ga_userid   = $user->ga_userid();
898
        $lastlogin   = $user->weblogin_last();
899

900 901
	# Check for frozen accounts. We do not update the IP record when
	# an account is frozen.
902
	if ($frozen) {
903
	    $user->UpdateWebLoginFail();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
904
	    return DOLOGIN_STATUS_WEBFREEZE;
905
	}
906 907 908 909 910 911 912 913 914
	if (!$nopassword) {
	    $encoding = crypt("$password", $db_encoding);
	    if (strcmp($encoding, $db_encoding)) {
		#
                # Bump count and check for too many consecutive failures.
	        #
		$failcount++;
		if ($failcount > DOLOGIN_MAXUSERATTEMPTS) {
		    $user->SetWebFreeze(1);
915
		
916 917 918 919
		    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".
920 921 922 923 924
			   "Testbed Operations has been notified.\n".
                           (isset($PORTAL_GENESIS) ?
                            "Portal: $PORTAL_GENESIS" :
                            "Classic Interface") . "\n",
                           
925 926 927 928 929 930 931
			   "From: $TBMAIL_OPS\n".
			   "Cc: $TBMAIL_OPS\n".
			   "Bcc: $TBMAIL_AUDIT\n".
			   "Errors-To: $TBMAIL_WWW");
		}
		$user->UpdateWebLoginFail();
		break;
932
	    }
933
	}
934
	#
935
	# Pass!
936
	#
937 938 939 940
        if (!$ga_userid) {
            $ga_userid = substr(GENHASH(), 0, 32);
            $user->SetGaUserid($ga_userid);
        }
941 942 943
        
        # But inactive users need special handling.
	if ($user->status() == TBDB_USERSTATUS_INACTIVE) {
944
            if (1) {
945
                TBMAIL($user->email(),
946 947 948 949 950 951
                       "Web Login Inactivity Alert: '$uid'",
                       "Login attempt by $uid ($uid_idx) after extended ".
                       "period of inactivity!\n".
                       "Login was denied, last activity was $lastlogin\n",
                       "From: $TBMAIL_OPS\n".
                       "Bcc: $TBMAIL_AUDIT\n".
952
                       "CC: $TBMAIL_OPS\n".
953 954 955 956
                       "Errors-To: $TBMAIL_WWW");
                
                return DOLOGIN_STATUS_INACTIVE;
            }
957 958 959 960 961 962 963
            # Try to reactivate the user. If we fail for some reason, fall
            # back to just telling them they are inactive. Otherwise we can
            # proceed with login.
            if (ReactivateUser($user)) {
                return DOLOGIN_STATUS_INACTIVE;
            }
	}
964

965
	#
966
	# Set adminmode off on new logins, unless user requested to be
967 968 969 970
	# 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. 
971
	#
972
	$adminon = 0;
973
	if ($adminmode && $isadmin) {
974
	    $adminon = 1;
975
	}
976 977 978 979

        #
        # Insert a record in the login table for this uid.
	#
980
	if (DOLOGIN_MAGIC($uid, $uid_idx, $usr_email, $adminon) < 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
981
	    return DOLOGIN_STATUS_ERROR;
982
	}
983
	$CHECKLOGIN_USER = $user;
984

985 986 987 988
	# 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
989
	return DOLOGIN_STATUS_OKAY;
990 991
      }
    } while (0);
992 993 994
    #
    # No such user
    #
995
    if (!isset($IP)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
996
	return DOLOGIN_STATUS_ERROR;
997
    }
998

999
    $ipfrozen = 0;
1000 1001 1002 1003
    if (isset($iprow)) {
	$ipfailcount = $iprow['failcount'];

        #
1004
        # Bump count.