tbauth.php3 44.3 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2018 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 Stoller's avatar
Leigh 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
define("CHECKLOGIN_NOPROJECTS",		0x4000000);
74
define("CHECKLOGIN_PROJDISABLED",	0x8000000);  # Member of disabled proj
75

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

Leigh Stoller's avatar
Leigh Stoller committed
82 83 84 85 86 87
# 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);
88
define("DOLOGIN_STATUS_INACTIVE",	-4);
89
define("DOLOGIN_STATUS_FROZEN", 	-5);
90
define("DOLOGIN_STATUS_PROJDISABLED", 	-6);
Leigh Stoller's avatar
Leigh Stoller committed
91

92 93 94
# So we can redefine this in the APT pages.
$CHANGEPSWD_PAGE = "moduserinfo.php3";

95 96 97 98 99 100 101 102 103
#
# 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 Stoller's avatar
Leigh Stoller committed
104
    $random_bytes = fread($fp, 128);
105 106
    fclose($fp);

107
    $hash  = mhash (MHASH_MD5, bin2hex($random_bytes) . " " . microtime());
108 109 110
    return bin2hex($hash);
}

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

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

    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 Stoller's avatar
Leigh Stoller committed
149
    global $TBNAMECOOKIE;
150
    $status_archived = TBDB_USERSTATUS_ARCHIVED;
151
    $status_nonlocal = TBDB_USERSTATUS_NONLOCAL;
152

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

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

	return $idx;
Chad Barb's avatar
Chad Barb committed
190
    }
191
    return FALSE;
192 193
}

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

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

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

    #
    # 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;
    }
253 254 255 256 257 258 259

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

283
    # No such user.
284 285 286 287 288 289 290
    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
291
    # values and the pid. pid is a hack.
292
    #
293 294 295
    $trusted   = 0;
    $opsguy    = 0;
    $workbench = 0;
Leigh Stoller's avatar
Leigh Stoller committed
296
    $frozen    = 0;
297
    $nonlocal  = 0;
298
    $pcount    = 0;
299
    $pdisabled = 0;
300
    
301 302 303 304 305 306 307
    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];
308 309 310 311 312 313 314 315 316 317 318
        $trust   = $row[6];

        #
        # Count up number of projects where user has local_root or better.
        # These are projects where user has viable permission to do things,
        # like create experiments.
        #
        if ($trust != "none" && $trust != "user") {
            $pcount++;
        }
	if ($trust == "project_root" || $trust == "group_root") {
319 320
	    $trusted = 1;
	}
321
	$adminon  = $row[7];
322
	$webonly  = $row[8];
323
	$interface= $row[9];
324 325

	$type     = $row[10];
326
	$stud     = $row[11];
327
	$wikiname = $row[12];
328
	$wikionly = $row[13];
329

330 331 332 333 334
	# Check for an ops guy.
	$pid = $row[14];
	if ($pid == $TBOPSPID) {
	    $opsguy = 1;
	}
335 336 337

	# Set foreign_admin=1 for admins of another Emulab.
	$foreign_admin   = $row[15];
338
	$uid_idx         = $row[16];
339
	$workbench      += $row[17];
Leigh Stoller's avatar
Leigh Stoller committed
340
	$frozen          = $row[18];
341
	$nonlocal        = $row[19] ? 1 : 0;
342 343 344 345
        $disable         = $row[20];
        if ($disable) {
            $pdisabled++;
        }
346

347
	$CHECKLOGIN_NODETYPES[$type] = 1;
348
    }
349 350 351 352

    #
    # If user exists, but login has no entry, quit now.
    #
353 354 355 356
    if (!$hashkey) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
357

358
    #
359
    # Check for frozen account. Might do something interesting later.
360
    #
361
    if ($pdisabled || $frozen ||
Leigh Stoller's avatar
Leigh Stoller committed
362
	$status == TBDB_USERSTATUS_FROZEN) {
363
	DBQueryFatal("DELETE FROM login WHERE uid_idx='$uid_idx'");
364 365
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
366
    }
367 368 369 370 371
    if ($status == TBDB_USERSTATUS_INACTIVE) {
	DBQueryFatal("DELETE FROM login WHERE uid_idx='$uid_idx'");
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
372

373
    #
374 375
    # Check for expired login. Remove this entry from the logins table to
    # keep it from getting cluttered.
376
    #
377
    if (time() > $timeout) {
378 379
	DBQueryFatal("delete from login where ".
		     "uid_idx='$uid_idx' and hashkey='$hashkey'");
380 381 382 383 384
	$CHECKLOGIN_STATUS = CHECKLOGIN_TIMEDOUT;
	return $CHECKLOGIN_STATUS;
    }

    #
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    # 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).
400
	#
401 402 403 404 405 406 407 408 409
	if ($curhash != $hashkey) {
	    #
	    # User is not logged in from this browser. Must be stale.
	    # 
	    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	    return $CHECKLOGIN_STATUS;
	}
	else {
            #
410 411
	    # User is logged in.
	    #
412 413
	    $CHECKLOGIN_STATUS = CHECKLOGIN_LOGGEDIN;
	}
414 415
    }
    else {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
	#
	# 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;
	}
436
	return $CHECKLOGIN_STATUS;
437 438
    }

439 440 441 442 443 444
    # Cache this now; someone will eventually want it.
    $CHECKLOGIN_USER = User::Lookup($uid_idx);
    if (! $CHECKLOGIN_USER) {
	$CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;
	return $CHECKLOGIN_STATUS;
    }
445 446 447 448 449 450
    $ga_userid = $CHECKLOGIN_USER->ga_userid();
    if (!$ga_userid) {
        $ga_userid = substr(GENHASH(), 0, 32);
        $CHECKLOGIN_USER->SetGaUserid($ga_userid);
    }
    
451
    #
452
    # Now add in the modifiers.
453
    #
454
    # Do not expire passwords for admin users.
455
    if (!is_null($expired) && $expired && !$admin)
456 457 458
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PSWDEXPIRED;
    if ($admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISADMIN;
459 460
    if ($adminon)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ADMINON;
461 462
    if ($webonly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WEBONLY;
463 464
    if ($wikionly)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_WIKIONLY;
465 466
    if ($trusted)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_TRUSTED;
467 468
    if ($stud)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_STUDLY;
469 470
    if ($cvsweb)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_CVSWEB;
471
    if ($interface == TBDB_USER_INTERFACE_PLAB)
472
	$CHECKLOGIN_STATUS |= CHECKLOGIN_PLABUSER;
473 474 475 476 477 478 479 480
    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;
481 482
    if (strcmp($status, TBDB_USERSTATUS_INACTIVE) == 0)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_INACTIVE;
483 484
    if (isset($wikiname) && $wikiname != "")
	$CHECKLOGIN_WIKINAME = $wikiname;
485 486
    if ($opsguy)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_OPSGUY;
487 488
    if ($foreign_admin)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_ISFOREIGN_ADMIN;
489 490
    if ($nonlocal)
	$CHECKLOGIN_STATUS |= CHECKLOGIN_NONLOCAL;
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    #
    # A local user that has no privs in at least one project, or a nonlocal
    # user where webonly=1 (which means they have project membership at
    # their home portal). 
    #
    if ($nonlocal) {
        if ($webonly) {
            $CHECKLOGIN_STATUS |= CHECKLOGIN_NOPROJECTS;
        }
    }
    else {
        if (!$pcount) {
            $CHECKLOGIN_STATUS |= CHECKLOGIN_NOPROJECTS;
        }
    }
506

507 508 509
    #
    # Set the magic enviroment variable, if appropriate, for the sake of
    # any processes we might spawn. We prepend an HTTP_ on the front of
510
    # the variable name, so that it will get through suexec.
511
    #
512
    if ($admin && $adminon) {
513 514
    	putenv("HTTP_WITH_TB_ADMIN_PRIVS=1");
    }
515 516 517 518 519 520 521 522 523
    #
    # 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());
    
524 525 526
    # XXX Temporary.
    if ($stud) {
	$EXPOSEARCHIVE = 1;
527 528 529
    }
    if ($workbench) {
	$EXPOSETEMPLATES = $EXPOSEARCHIVE = 1;
530
    }
531
    return $CHECKLOGIN_STATUS;
532 533 534 535
}

#
# This one checks for login, but then dies with an appropriate error
536 537
# message. The modifier allows you to turn off checks for specified
# conditions. 
538
#
539
function LOGGEDINORDIE($uid, $modifier = 0, $login_url = NULL) {
540
    global $TBBASE, $BASEPATH;
541
    global $TBAUTHTIMEOUT, $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
542 543 544 545 546 547 548 549 550 551 552
    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);
    }
553

554
    #
555 556 557 558 559
    # 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
560
    #
561
    $redirect_url = null;
562 563
    if (!$login_url) {
	$login_url = "$TBBASE/login.php3?refer=1";
564 565 566 567 568 569
        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']);
	}
570 571 572
    }

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

575
    $status = LoginStatus();
576 577 578

    switch ($status & CHECKLOGIN_STATUSMASK) {
    case CHECKLOGIN_NOTLOGGEDIN:
579 580 581 582 583 584 585
	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);
        }
586
        break;
587
    case CHECKLOGIN_TIMEDOUT:
588 589 590 591 592 593 594
	if ($redirect_url) {
	    header("Location: $redirect_url&error=timedout");
	    exit;
        } else {
            USERERROR("Your login has timed out! $link",
		      1, HTTP_403_FORBIDDEN);
        }
595
        break;
596
    case CHECKLOGIN_MAYBEVALID:
597 598 599 600
	# 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? ".
601
		  "Are you using https? Are you logged in using another ".
602
		  "browser or another machine? $link", 1, HTTP_403_FORBIDDEN);
603
        break;
604
    case CHECKLOGIN_LOGGEDIN:
605
	BumpLogoutTime();
606 607 608
	break;
    default:
	TBERROR("LOGGEDINORDIE failed mysteriously", 1);
609
    }
610

611
    CheckLoginConditions($status & ~$modifier);
612

613 614 615 616 617 618 619 620 621
    # No one should ever look at the return value of this function.
    return null;
}

#
# Check other conditions.
#
function CheckLoginConditions($status)
{
622
    global $CHANGEPSWD_PAGE, $TBMAILADDR;
623
    
624
    if ($status & CHECKLOGIN_PSWDEXPIRED)
625
        USERERROR("Your password has expired. ".
626
		  "<a href='$CHANGEPSWD_PAGE'>Please change it now.</a>",
627
		  1, HTTP_403_FORBIDDEN);
628
    if ($status & CHECKLOGIN_FROZEN)
629 630
        USERERROR("Your account has been frozen!",
		  1, HTTP_403_FORBIDDEN);
631
    if ($status & CHECKLOGIN_INACTIVE)
632 633
        USERERROR("Your account has gone inactive since your last login was ".
                  "so long ago. Please contact $TBMAILADDR to restore it.",
634
		  1, HTTP_403_FORBIDDEN);
635
    if ($status & (CHECKLOGIN_UNVERIFIED|CHECKLOGIN_NEWUSER))
636 637
        USERERROR("You have not verified your account yet!",
		  1, HTTP_403_FORBIDDEN);
638
    if ($status & CHECKLOGIN_UNAPPROVED)
639 640 641 642
        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.",
643
		  1, HTTP_403_FORBIDDEN);
644
    if (($status & CHECKLOGIN_WEBONLY) && ! ISADMIN())
645 646
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
647 648 649
    if ($status & CHECKLOGIN_NONLOCAL)
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
650
    if (($status & CHECKLOGIN_WIKIONLY) && ! ISADMIN())
651 652
        USERERROR("Your account does not permit you to access this page!",
		  1, HTTP_403_FORBIDDEN);
653 654 655 656 657

    #
    # Lastly, check for nologins here. This heads off a bunch of other
    # problems and checks we would need.
    #
658
    if (NOLOGINS() && !ISADMIN())
659
        USERERROR("Sorry. The Web Interface is ".
660
		  "temporarily unavailable. Please check back later.", 1);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
}

#
# 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)
{
684
    global $CHECKLOGIN_USER, $CHECKLOGIN_STATUS;
685 686 687 688

    $status = LoginStatus();

    # If login looks valid, return the user. 
689 690 691 692 693 694 695 696 697 698 699
    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;
	}
700 701 702 703 704
	if ($status & CHECKLOGIN_LOGGEDIN) {
	    BumpLogoutTime();
	}
	return $CHECKLOGIN_USER;
    }
705
    return null;
706 707 708
}

#
709 710 711 712
# 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.
713
#
714
function ISADMIN() {
715 716
    global $CHECKLOGIN_STATUS;
    
717
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
718
	return 0;
719
    }
720

721
    return (($CHECKLOGIN_STATUS &
722 723
	     (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON)) ==
	    (CHECKLOGIN_LOGGEDIN|CHECKLOGIN_ISADMIN|CHECKLOGIN_ADMINON));
724 725
}

726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

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

741 742 743 744
function STUDLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
745
	TBERROR("STUDLY: user is not logged in!", 1);
746 747 748 749 750 751 752
    }

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

753 754 755 756
function OPSGUY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
757
	TBERROR("OPSGUY: user is not logged in!", 1);
758 759 760 761 762 763 764
    }

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

765 766 767 768
function WIKIONLY() {
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
769
	TBERROR("WIKIONLY: user is not logged in!", 1);
770 771 772 773 774 775 776
    }

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

777 778 779 780 781 782 783 784
function NOPROJECTMEMBERSHIP() {
    global $CHECKLOGIN_STATUS;

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

785
# Is this user a real administrator (ignore onoff bit).
786
function ISADMINISTRATOR() {
787 788 789
    global $CHECKLOGIN_STATUS;
    
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS)
Leigh Stoller's avatar
Leigh Stoller committed
790
	TBERROR("ISADMINISTRATOR: $uid is not logged in!", 1);
791 792 793 794 795 796

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

797 798 799
#
# Toggle current login admin bit. Must be an administrator of course!
#
800 801
function SETADMINMODE($onoff) {
    global $CHECKLOGIN_HASHKEY, $CHECKLOGIN_IDX;
802 803 804 805 806
    
    # This makes sure the user is actually logged in secure (https).
    if (! ISADMINISTRATOR())
	return;

807 808
    # Be pedantic.
    if (! ($CHECKLOGIN_HASHKEY && $CHECKLOGIN_IDX))
809
	return;
810

811
    $onoff   = addslashes($onoff);
812 813
    $curhash = addslashes($CHECKLOGIN_HASHKEY);
    $uid_idx = $CHECKLOGIN_IDX;
814 815
    
    DBQueryFatal("update login set adminon='$onoff' ".
816
		 "where uid_idx='$uid_idx' and hashkey='$curhash'");
817 818
}

819
# Is this user a planetlab user? Returns 1 if they are, 0 if not.
820 821 822
function ISPLABUSER() {
    global $CHECKLOGIN_STATUS;

823 824 825 826 827 828 829 830
    if ($CHECKLOGIN_STATUS == CHECKLOGIN_NOSTATUS) {
	#
	# For users who are not logged in, we need to check the database
	#
	$uid = GETUID();
	if (!$uid) {
	    return 0;
	}
831 832
	# Lookup sanitizes argument.
	if (! ($user = User::Lookup($uid)))
833
	    return 0;
834

835 836 837 838
	if ($user->user_interface()) {
	    return ($user->user_interface() == TBDB_USER_INTERFACE_PLAB);
	}
	else {
839 840
	    return 0;
	}
841
    } else {
842
	#
843
	# For logged-in users, we recorded it in the the login status
844 845
	#
	return (($CHECKLOGIN_STATUS &
846 847
		 (CHECKLOGIN_PLABUSER)) ==
		(CHECKLOGIN_PLABUSER));
848 849 850
    }
}

851 852 853 854 855 856 857 858 859 860 861 862
#
# 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;
863 864

    if (! GETUID())
865
	return 0;
866

Leigh Stoller's avatar
Leigh Stoller committed
867
    if (isset($CHECKLOGIN_NODETYPES[$type])) {
868 869 870 871 872 873
	return 1;
    } else {
	return 0;
    }
}

874 875 876
#
# Attempt a login.
# 
877
function DOLOGIN($token, $password, $adminmode = 0, $nopassword = 0) {
878 879
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES;
880
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
881
    global $WIKISUPPORT, $WIKICOOKIENAME;
882
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME, $CHECKLOGIN_USER;
883
    global $TB_PROJECT_READINFO;
Leigh Stoller's avatar
Leigh Stoller committed
884 885
    
    # Caller makes these checks too.
886
    if ((!TBvalid_uid($token) && !TBvalid_email($token)) ||
887
	((!isset($password) || $password == "") && !$nopassword)) {
Leigh Stoller's avatar
Leigh Stoller committed
888
	return DOLOGIN_STATUS_ERROR;
889
    }
890
    $now = time();
891

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
    #
    # 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 Stoller's avatar
Leigh Stoller committed
912
		return DOLOGIN_STATUS_IPFREEZE;
913 914 915 916
	    }
	}
    }

917 918 919 920 921 922 923
    if (TBvalid_email($token)) {
	$user = User::LookupByEmail($token);
    }
    else {
	$user = User::Lookup($token);
    }
	    
924 925 926
    #
    # Check password in the database against provided. 
    #
927
    do {
928 929 930 931 932 933 934 935 936
      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();
937
	$uid_idx     = $user->uid_idx();
938
	$usr_email   = $user->email();
939
        $ga_userid   = $user->ga_userid();
940
        $lastlogin   = $user->weblogin_last();
941

942 943
	# Check for frozen accounts. We do not update the IP record when
	# an account is frozen.
944
	if ($frozen) {
945
	    $user->UpdateWebLoginFail();
Leigh Stoller's avatar
Leigh Stoller committed
946
	    return DOLOGIN_STATUS_WEBFREEZE;
947
	}
948 949 950 951 952
        # Check for membership in disabled project.
        $plist = $user->DisabledProjects();
        if (count($plist)) {
            return DOLOGIN_STATUS_PROJDISABLED;
        }
953 954 955 956 957 958 959 960 961
	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);
962
		
963 964 965 966
		    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".
967 968 969 970 971
			   "Testbed Operations has been notified.\n".
                           (isset($PORTAL_GENESIS) ?
                            "Portal: $PORTAL_GENESIS" :
                            "Classic Interface") . "\n",
                           
972 973 974 975 976 977 978
			   "From: $TBMAIL_OPS\n".
			   "Cc: $TBMAIL_OPS\n".
			   "Bcc: $TBMAIL_AUDIT\n".
			   "Errors-To: $TBMAIL_WWW");
		}
		$user->UpdateWebLoginFail();
		break;
979
	    }
980
	}
981
	#
982
	# Pass!
983
	#
984 985 986 987
        if (!$ga_userid) {
            $ga_userid = substr(GENHASH(), 0, 32);
            $user->SetGaUserid($ga_userid);
        }
988
        
989 990 991 992 993
        # But inactive/frozen users need special handling.
	if ($user->status() == TBDB_USERSTATUS_FROZEN) {
          return DOLOGIN_STATUS_FROZEN;
        }
	elseif ($user->status() == TBDB_USERSTATUS_INACTIVE) {
994
            if (1) {
995
                TBMAIL($user->email(),
996 997 998 999 1000 1001
                       "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".
1002
                       "CC: $TBMAIL_OPS\n".
1003 1004 1005 1006
                       "Errors-To: $TBMAIL_WWW");
                
                return DOLOGIN_STATUS_INACTIVE;
            }
1007 1008 1009 1010 1011 1012 1013
            # 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;
            }
	}
1014

1015
	#
1016
	# Set adminmode off on new logins, unless user requested to be
1017 1018 1019 1020
	# 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. 
1021
	#
1022
	$adminon = 0;
1023
	if ($adminmode && $isadmin) {
1024
	    $adminon = 1;
1025
	}
1026 1027 1028 1029

        #
        # Insert a record in the login table for this uid.
	#
1030
	if (DOLOGIN_MAGIC($uid, $uid_idx, $usr_email, $adminon) < 0) {
Leigh Stoller's avatar
Leigh Stoller committed
1031
	    return DOLOGIN_STATUS_ERROR;
1032
	}
1033
	$CHECKLOGIN_USER = $user;
1034

1035 1036 1037 1038
	# Clear IP record since we have a sucessful login from the IP.
	if (isset($IP)) {
	    DBQueryFatal("delete from login_failures where IP='$IP'");
	}
Leigh Stoller's avatar
Leigh Stoller committed
1039
	return DOLOGIN_STATUS_OKAY;
1040 1041
      }
    } while (0);
1042 1043 1044
    #
    # No such user
    #
1045
    if (!isset($IP)) {
Leigh Stoller's avatar
Leigh Stoller committed
1046
	return DOLOGIN_STATUS_ERROR;
1047
    }
1048

1049
    $ipfrozen = 0;
1050 1051 1052 1053
    if (isset($iprow)) {
	$ipfailcount = $iprow['failcount'];

        #
1054
        # Bump count.
1055 1056 1057 1058
        #
	$ipfailcount++;
    }
    else {
1059 1060 1061
	#
	# First failure.
	# 
1062 1063
	$ipfailcount = 1;
    }
1064 1065 1066 1067

    #
    # Check for too many consecutive failures.
    #
1068 1069 1070 1071 1072 1073
    if ($ipfailcount > DOLOGIN_MAXIPATTEMPTS) {
	$ipfrozen = 1;
	    
	TBMAIL($TBMAIL_OPS,
	       "Web Login Freeze: '$IP'",
	       "Logins has been frozen because there were too many login\n".
1074 1075 1076
	       "failures from $IP. Last attempted uid was '$token'.\n".
               (isset($PORTAL_GENESIS) ?
                "Portal: $PORTAL_GENESIS" : "Classic Interface") . "\n\n",
1077 1078 1079 1080 1081 1082 1083 1084
	       "From: $TBMAIL_OPS\n".
	       "Bcc: $TBMAIL_AUDIT\n".
	       "Errors-To: $TBMAIL_WWW");
    }
    DBQueryFatal("replace into login_failures set ".
		 "       IP='$IP', ".
		 "       frozen='$ipfrozen', ".
		 "       failcount='$ipfailcount', ".
1085
		 "       failstamp='$now'");
Leigh Stoller's avatar
Leigh Stoller committed
1086
    return DOLOGIN_STATUS_ERROR;
1087 1088
}

1089 1090
function DOLOGIN_MAGIC($uid, $uid_idx, $email = null,
		       $adminon = 0, $nosetcookies = 0)
1091
{
1092
    global $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT, $WWWHOST;
1093
    global $TBNAMECOOKIE, $TBLOGINCOOKIE, $TBSECURECOOKIES, $TBEMAILCOOKIE;
1094 1095
    global $TBMAIL_OPS, $TBMAIL_AUDIT, $TBMAIL_WWW;
    global $WIKISUPPORT, $WIKICOOKIENAME;
1096
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME, $TRACSUPPORT, $TRACCOOKIENAME;
1097
    global $TBLIBEXEC_DIR, $EXP_VIS, $TBMAINSITE;
1098
    global $WITHZFS, $ZFS_NOEXPORT;
1099
    global $PORTAL_GENESIS;
1100

1101
    $flushtime = time() - 1000000;
1102 1103 1104 1105 1106
    
    # Caller makes these checks too.
    if (!TBvalid_uid($uid)) {
	return -1;
    }
1107 1108 1109
    if (!TBvalid_uididx($uid_idx)) {
	return -1;
    }
1110 1111
    $now = time();

Leigh Stoller's avatar
Leigh Stoller committed
1112 1113 1114 1115
    if (isset($_SERVER['REMOTE_ADDR'])) {
	$IP = $_SERVER['REMOTE_ADDR'];
    }
        
1116 1117 1118 1119 1120
    #
    # 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. 
    #
1121 1122
    # One hour initially, it will get bumped as soon as they hit another page.
    $timeout = $now + 3600;
1123
    $hashkey = GENHASH();
1124
    # See note in CrossLogin() in db/User.pm.in. Do not change this.
1125
    $crc     = bin2hex(mhash(MHASH_CRC32, $hashkey));
1126
    $opskey  = GENHASH();
1127

1128 1129 1130 1131
    #
    # Ug. When using ZFS in NOEXPORT mode, we have to call exports_setup
    # to get the mounts exported to back to boss. We do not want to do this
    # every time the user logs in of course, and since exports_setup is 
1132
    # using one week as its threshold, we can use that as the limit.
1133
    #
1134
    $exports_active = TBGetSiteVar("general/export_active");
1135 1136 1137 1138 1139 1140 1141 1142

    # We get the email at the same time for inactivity warning.
    $query_result =
        DBQueryFatal("select UNIX_TIMESTAMP(last_activity),last_activity, ".
                     "       UNIX_TIMESTAMP(weblogin_last),weblogin_last, ".
                     "       usr_email ".
                     "  from users as u ".
                     "left join user_stats as s on s.uid_idx=u.uid_idx ".
1143
                     "where u.uid_idx='$uid_idx'");
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    
    if (!mysql_num_rows($query_result)) {
        return -1;
    }
    $lastrow       = mysql_fetch_row($query_result);
    $lastactive    = $lastrow[0];
    $lastactivestr = $lastrow[1];
    $lastlogin     = $lastrow[2];
    $lastloginstr  = $lastrow[3];
    $usr_email     = $lastrow[4];
1154 1155 1156 1157 1158 1159 1160 1161
    
    if ($WITHZFS && $ZFS_NOEXPORT && $exports_active) {
        $limit = (($exports_active * 24) - 12) * 3600;
        
        # Update last_activity first so exports_setup will do something
        # and to mark activity to keep the mount active.
        DBQueryFatal("update user_stats set last_activity=now() ".
                     "where uid_idx='$uid_idx'");
Leigh Stoller's avatar
Leigh Stoller committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

        $history = "insert into login_history set ".
            "   idx=null,uid='$uid',uid_idx='$uid_idx',tstamp=now()";
        
        if (isset($IP)) {
            $history .= ",IP='$IP'";
        }
        if (isset($PORTAL_GENESIS)) {
            $history .= ",portal='$PORTAL_GENESIS'";
        }
        DBQueryFatal($history);
1173
        
1174 1175 1176 1177 1178 1179
        if (time() - $lastactive > $limit) {
            $rv = SUEXEC("nobody", "nobody", "webexports_setup",
                         SUEXEC_ACTION_IGNORE);
            
            # failed, reset the timestamp
            if ($rv) {
1180 1181 1182 1183 1184
                if ($lastactivestr != '') {                
                    DBQueryFatal("update user_stats set ".
                                 " last_activity='$lastactivestr' ".
                                 "where uid_idx='$uid_idx'");
                }
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
                SUEXECERROR(SUEXEC_ACTION_DIE);
                return;
            }
        }
    }
    if ($lastlogin && 
        time() - $lastlogin > (3600 * 24 * 365)) {
        TBMAIL($usr_email,
               "Web Login Inactivity Alert: '$uid'",
               "Login by $uid ($uid_idx) after extended period ".
               "of inactivity!\n".
               "Last activity was $lastloginstr\n",
               "From: $TBMAIL_OPS\n".
               "Bcc: $TBMAIL_AUDIT\n".
               "CC: $TBMAIL_OPS\n".
               "Errors-To: $TBMAIL_WWW");
1201
    }
1202
    DBQueryFatal("replace into login ".
1203 1204 1205 1206
		 "  (uid,uid_idx,hashkey,hashhash,timeout,adminon,opskey) ".
                 " values ".
		 "  ('$uid', $uid_idx, '$hashkey', '$crc', '$timeout', ".
                 "    $adminon, '$opskey')");
1207 1208 1209 1210
    if (isset($PORTAL_GENESIS)) {
        DBQueryFatal("update login set portal='$PORTAL_GENESIS' ".
                     "where uid_idx='$uid_idx' and hashkey='$hashkey'");
    }
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

    DBQueryFatal("update users set ".
		 "       weblogin_failcount=0,weblogin_failstamp=0 ".
		 "where uid_idx='$uid_idx'");
    
    #
    # Usage stats. 
    #
    DBQueryFatal("update user_stats set ".
		 " weblogin_count=weblogin_count+1, ".
		 " weblogin_last=now() ".
		 "where uid_idx='$uid_idx'");
1223

1224 1225 1226 1227 1228
    # Does the caller just want the cookies for itself.
    if ($nosetcookies) {
	return array($hashkey, $crc);
    }

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

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
    #
    # Since we changed the domain of the cookies make sure that the cookies 
    # from the old domain no longer exist.
    #
    setcookie($TBAUTHCOOKIE, '', 1, "/", $TBAUTHDOMAIN, $TBSECURECOOKIES);
    setcookie($TBLOGINCOOKIE, '', 1, "/", $TBAUTHDOMAIN, 0);
    setcookie($TBNAMECOOKIE, '', 1, "/", $TBAUTHDOMAIN, 0);
    if ($email)
      setcookie($TBEMAILCOOKIE, '', 1, "/", $TBAUTHDOMAIN, 0);

1243 1244 1245 1246 1247 1248 1249 1250
    #
    # 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, "/",
1251
	      $WWWHOST, $TBSECURECOOKIES);
1252 1253 1254 1255 1256 1257 1258 1259

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

    #
1263 1264 1265 1266
    # We want to remember who the user was each time they load a page
    # NOTE: This cookie is integral to authorization, since we do not pass
    # around the UID anymore, but look for it in the cookie.
    #
1267
    setcookie($TBNAMECOOKIE, $uid_idx, 0, "/", $WWWHOST, 0);
1268 1269 1270 1271 1272 1273 1274

    #
    # This is a long term cookie so we can remember who the user was, and
    # and stick that in the login box.
    #
    if ($email) {
	$timeout = $now + (60 * 60 * 24 * 365);
1275
	setcookie($TBEMAILCOOKIE, $email, $timeout, "/", $WWWHOST, 0);
1276
    }
1277 1278 1279 1280 1281

    #
    # Clear the existing Wiki cookie so that there is not an old one
    # for a different user, sitting in the brower. 
    # 
1282
    if ($WIKISUPPORT || $TBMAINSITE) {
1283 1284 1285
	setcookie($WIKICOOKIENAME, "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
    }
1286 1287 1288 1289 1290 1291 1292 1293
    if (0) {
	#
	# Some incomplete code for auto login to new (plone based) wiki.
	#
	setcookie("emulab_wiki",
		  "user=$uid&hash=Fooey", time() + 5000, "/", $TBAUTHDOMAIN, 0);
    }
    
1294 1295 1296 1297 1298 1299 1300
    #
    # Ditto for bugdb
    # 
    if ($BUGDBSUPPORT) {
	setcookie($BUGDBCOOKIENAME, "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
    }
1301 1302 1303 1304
    # These cookie names are still in flux. 
    if ($TRACSUPPORT) {
	setcookie("trac_auth_emulab", "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
1305 1306
	setcookie("trac_auth_emulab_priv", "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
1307 1308
	setcookie("trac_auth_protogeni", "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
1309 1310
	setcookie("trac_auth_protogeni_priv", "", $flushtime, "/",
		  $TBAUTHDOMAIN, $TBSECURECOOKIES);
1311
    }
1312 1313 1314
    # Clear the PHP session cookie, in case someone is using sessions.
    setcookie(session_name(), "", $flushtime, "/",
	      $TBAUTHDOMAIN, $TBSECURECOOKIES);
1315
	
1316
    # Proj-vis cookies
1317 1318
    if ($EXP_VIS) {
	setcookie("exp_vis_session", $opskey, 0, "/", $TBAUTHDOMAIN, 0);
1319
        SUEXEC($uid,"nobody", "write-vis-auth &", SUEXEC_ACTION_CONTINUE);
1320
    }
1321

1322 1323
    return 0;
}
1324 1325 1326 1327 1328

#
# Verify a password
# 
function VERIFYPASSWD($uid, $password) {
1329
    if (! isset($password) || $password == "") {
1330 1331 1332
	return -1;
    }

1333 1334
    if (! ($user = User::Lookup($uid)))
	return -1;
1335 1336 1337 1338

    #
    # Check password in the database against provided. 
    #
1339
    $encoding = crypt("$password", $user->pswd());
1340
	
1341
    if ($encoding == $user->pswd()) {
1342 1343 1344 1345 1346
	return 0;
    }
    return -1;
}

1347
#
1348
# Log out a UID.
1349
#
1350 1351
function DOLOGOUT($user) {
    global $CHECKLOGIN_STATUS, $CHECKLOGIN_USER;
1352
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHDOMAIN, $WWWHOST;
1353
    global $WIKISUPPORT, $WIKICOOKIENAME, $TBMAINSITE;
1354
    global $BUGDBSUPPORT, $BUGDBCOOKIENAME, $TRACSUPPORT, $TRACCOOKIENAME;
1355
    global $TBLIBEXEC_DIR, $EXP_VIS;
1356

1357
    if (! $CHECKLOGIN_USER)
1358
	return 1;
1359 1360

    $uid_idx = $user->uid_idx();
1361
    $uid = $user->uid();
1362 1363 1364 1365 1366 1367 1368

    #
    # An admin logging out another user. Nothing else to do.
    #
    if (! $user->SameUser($CHECKLOGIN_USER)) {
	DBQueryFatal("delete from login where uid_idx='$uid_idx'");
	return 0;
1369
    }
1370

1371 1372
    $CHECKLOGIN_STATUS = CHECKLOGIN_NOTLOGGEDIN;

Leigh Stoller's avatar
Leigh Stoller committed
1373 1374 1375
    $curhash  = "";
    $hashhash = "";

1376 1377
    if (isset($_COOKIE[$TBAUTHCOOKIE])) {
	$curhash = $_COOKIE[$TBAUTHCOOKIE];
Leigh Stoller's avatar
Leigh Stoller committed
1378
    }
1379 1380
    if (isset($_COOKIE[$TBLOGINCOOKIE])) {
	$hashhash = $_COOKIE[$TBLOGINCOOKIE];
Leigh Stoller's avatar
Leigh Stoller committed
1381
    }
1382 1383 1384 1385
    
    #
    # We have to get at least one of the hashes. 
    #
Leigh Stoller's avatar
Leigh Stoller committed
1386
    if ($curhash == "" && $hashhash == "") {
1387
	return 1;
1388
    }
Leigh Stoller's avatar
Leigh Stoller committed
1389
    if ($curhash != "" &&
1390 1391 1392
	! preg_match("/^[\w]+$/", $curhash)) {
	return 1;
    }
Leigh Stoller's avatar
Leigh Stoller committed
1393
    if ($hashhash != "" &&