geni-login.ajax 13.7 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 23 24 25 26
# 
# {{{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/>.
# 
# }}}
#
chdir("..");
include_once("geni_defs.php");
chdir("apt");
27 28 29 30 31 32 33 34 35
include_once("instance_defs.php");

#
# Return info to allow the client to load and start the auth process.
# This is entirely cause we want to have a login button on each page,
# but not have to load all the signer stuff unless its actually used.
#
function Do_GetSignerInfo()
{
36
    global $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN, $TBDIR;
37 38
    $hash = GENHASH();

39 40 41 42
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
43 44 45 46 47
    # We use a session to hold stuff across the ajax calls
    session_start();
    session_regenerate_id(TRUE);

    $blob = array();
48 49 50
    $blob["HOST"]  = "https://ch.geni.net:8444";
    $blob["PATH"]  = "/xml-signer/index.html";
    $blob["AUTH"]  = "https://ch.geni.net:8444/xml-signer/geni-auth.js";
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    $infname  = "$TBDIR/etc/genisa.pem";
    $outfname = tempnam("/tmp", "certout");
    $retval   = myexec("$TBDIR/sbin/protogeni/parsecert $infname $outfname");
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal certificate parse error");
        unlink($outfname);
	session_destroy();
	return;
    }
    $parse_output = file_get_contents($outfname);
    unlink($outfname);

    #
    # Decode simple XML that is returned. 
    #
    $parsed = simplexml_load_string($parse_output);
    if (!$parsed) {
	TBERROR("Could not parse XML output:\n$parse_output\n", 0);
	SPITAJAX_ERROR(-1, "Internal parsing Error");
	session_destroy();
	return;
    }
    $info = array();
    foreach ($parsed->attribute as $attribute) {
	$info[(string)$attribute['name']] = (string)$attribute;
    }
    $blob["ID"]    = $info["urn"];
    $blob["CERT"]  = $info["certificate"];
80 81 82

    SPITAJAX_RESPONSE($blob);
}
83 84 85 86 87 88 89 90

#
# 
#
function Do_CreateSecret()
{
    global $ajax_args;
    global $TBDIR;
91
    global $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN;
92

93 94 95 96
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    #
    # Destroy any existing session data to prevent replay.
    #
    if (!(session_start() &&
	  session_destroy())) {
	SPITAJAX_ERROR(-1, "Internal session error 1");
	return;
    }
    session_commit();
    if (!session_start()) {
	SPITAJAX_ERROR(-1, "Internal session error 2");
	return;
    }
    
    if (!isset($ajax_args["certificate"])) {
	SPITAJAX_ERROR(1, "Missing user public key");
	return;
    }
    $certificate = $ajax_args["certificate"];

    if (!isset($ajax_args["r1_encrypted"])) {
	SPITAJAX_ERROR(1, "Missing encrypted random string");
	return;
    }
    $r1_encrypted = $ajax_args["r1_encrypted"];
    $r2_decrypted = GENHASH();

    $infname  = tempnam("/tmp", "pkcs7in");
    $outfname = tempnam("/tmp", "pkcs7out");
126
    $userCertName = tempnam("/tmp", "pkcs7cert");
127 128 129 130 131 132 133 134 135

    #
    # Decrypt the random bytes. To do this we have to put the stuff
    # into a file, and it is decrypted into a file which we have to read.
    #
    $fp = fopen($infname, "w");
    fwrite($fp, $r1_encrypted);
    fclose($fp);

136 137 138
    $retval =
	myexec("/usr/bin/openssl smime -decrypt -inform PEM -inkey ".
	       "${TBDIR}/etc/genisa.pem -in $infname -out $outfname");
139

140 141
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal decryption error");
142 143 144 145 146 147 148 149 150 151 152 153
	return;
    }
    $r1_decrypted = file_get_contents($outfname);
    $r1_decrypted = rtrim($r1_decrypted);

    #
    # Now encrypt the random bytes.
    #
    $fp = fopen($infname, "w");
    fwrite($fp, $r2_decrypted);
    fclose($fp);

154 155 156 157
    $fp = fopen($userCertName, "w");
    fwrite($fp, $certificate);
    fclose($fp);

158 159 160
    $retval =
	myexec("/usr/bin/openssl smime -encrypt -outform PEM ".
	       "-in $infname -out $outfname -aes256 $userCertName");
161

162 163
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal encryption error");
164 165 166
	return;
    }
    $r2_encrypted = file_get_contents($outfname);
167
    $secret = $r1_decrypted . $r2_decrypted;
168 169 170 171 172 173 174 175 176 177 178

    $blob = array();
    $blob["r2_encrypted"] = $r2_encrypted;

    # Store in the session.
    $_SESSION["secret"] = $secret;
    $_SESSION["certificate"]  = $certificate;
    session_commit();

    unlink($infname);
    unlink($outfname);
179
    unlink($userCertName);
180 181 182 183 184 185 186 187 188
    SPITAJAX_RESPONSE($blob);
}

#
# 
#
function Do_VerifySpeaksfor()
{
    global $ajax_args;
189
    global $TBDIR, $COOKDIEDOMAIN, $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN;
190
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHTIMEOUT, $TBNAMECOOKIE;
191
    global $OURDOMAIN, $TBMAILADDR;
192
    $embedded = 0;
193

194 195 196 197
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    # Restore the session.
    if (!session_start()) {
	SPITAJAX_ERROR(-1, "Internal session error 3");
	return;
    }

    if (!isset($ajax_args["speaksfor"]) || $ajax_args["speaksfor"] == "") {
	SPITAJAX_ERROR(1, "Missing speaksfor credential");
	session_destroy();
	return;
    }
    $speaksfor = $ajax_args["speaksfor"];

    if (!isset($ajax_args["signature"]) || $ajax_args["signature"] == "") {
	SPITAJAX_ERROR(1, "Missing signature for the credential");
	session_destroy();
	return;
    }
    $signature = $ajax_args["signature"];

    if (!isset($_SESSION["secret"]) || $_SESSION["secret"] == "") {
	SPITAJAX_ERROR(1, "What is your secret?");
	session_destroy();
	return;
    }
223
    if (isset($ajax_args["embedded"])) {
Leigh Stoller's avatar
Leigh Stoller committed
224
        $embedded = $ajax_args["embedded"];
225
    }
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

    #
    # Really the SHA256(speaksfor + secret). We need to verify that.
    #
    $secret = $_SESSION["secret"];
    $hash   = hash("sha256", $speaksfor . $secret);
    if ($hash != $signature) {
	SPITAJAX_ERROR(1, "Bad signature on credential");
	session_destroy();
	return;
    }

    $infname  = tempnam("/tmp", "certin");
    $outfname = tempnam("/tmp", "certout");

    #
    # The certificate belongs to the user and tells us who it is via
    # the URN. Use external script to parse the certificate and tell
    # us whats in it. We get back some simple XML.
    #
    $fp = fopen($infname, "w");
    fwrite($fp, $_SESSION["certificate"]);
    fclose($fp);

250 251
    $retval = 
	myexec("$TBDIR/sbin/protogeni/parsecert $infname $outfname");
252

253 254 255
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal certificate parse error");
	session_destroy();
256
        unlink($infname);
257 258 259 260 261 262 263 264 265 266 267 268 269
	return;
    }
    $parse_output = file_get_contents($outfname);
    unlink($infname);
    unlink($outfname);

    #
    # Decode simple XML that is returned. 
    #
    $parsed = simplexml_load_string($parse_output);
    if (!$parsed) {
	TBERROR("Could not parse XML output:\n$parse_output\n", 0);
	SPITAJAX_ERROR(-1, "Internal Error");
270
	session_destroy();
271 272 273 274 275 276 277 278 279
	return;
    }
    $info = array();
    foreach ($parsed->attribute as $attribute) {
	$info[(string)$attribute['name']] = (string)$attribute;
    }

    #
    # Find the user and log them in, returning the cookies to the caller.
280 281
    # If the user is actually a user with a real local account, we use
    # that account, we do not want to create a new user.
282
    #
283 284 285 286 287 288
    if (!preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/",
                    $info["urn"], $matches)) {
        SPITAJAX_ERROR(1, "Bad URN");
	session_destroy();
	return;
    }
289 290 291
    $domain = $matches[1];

    if ($domain == $OURDOMAIN) {
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        if (!TBvalid_uid($matches[3])) {
            SPITAJAX_ERROR(1, "Illegal characters in urn id");
            session_destroy();
            return;
        }
        $this_user = User::LookupByUid($matches[3]);
        if (!$this_user) {
            SPITAJAX_ERROR(1, "No local account for URN");
            session_destroy();
            return;
        }
        if (VerifyLocalUser($this_user, $_SESSION["certificate"])) {
            SPITAJAX_ERROR(1, "Cannot verify we signed your certificate");
            session_destroy();
            return;
        }
    }
    else {
        $this_user = User::LookupNonLocal($info["urn"]);

        if (!$this_user) {
            if (!$TBMAINSITE) {
                SPITAJAX_ERROR(1, "You do not have an account at this site");
                session_destroy();
                return;
            }
            if (CreateNonLocalUser($info["urn"], $info["email"])) {
                SPITAJAX_ERROR(-1, "Internal error creating new user");
                session_destroy();
                return;
            }
            $this_user = User::LookupNonLocal($info["urn"]);
            if (!$this_user) {
                SPITAJAX_ERROR(-1, "Internal error looking up new user");
                session_destroy();
                return;
            }
329
        }
330 331 332 333 334 335 336 337 338 339 340 341 342
        else {
            #
            # Ug, if this geni user came in on the regular geni api first,
            # we have a user record but they might not be a member of the
            # Cloudlab holding project. 
            #
            if ($TBMAINSITE) {
                $project = Project::Lookup("CloudLab");
                if (! $project->IsMember($this_user, $ignored)) {
                    $project->AddNewMember($this_user,
                                           TBDB_TRUSTSTRING_LOCALROOT);
                }
            }
343 344 345 346 347 348 349
            if ($this_user->status() == TBDB_USERSTATUS_INACTIVE) {
                SPITAJAX_ERROR(1, "Your account has gone inactive. Please ".
                               "contact $TBMAILADDR to have your ".
                               "account restored.");
                session_destroy();
                return;
            }
350
        }
351
    }
352 353 354 355 356 357 358 359 360 361 362
    #
    # Check for a frozen login. 
    #
    if ($this_user->weblogin_frozen()) {
        SPITAJAX_ERROR(1, "Your account has been frozen. Please ".
                       "contact $TBMAILADDR to have your ".
                       "account restored.");
        session_destroy();
        return;
    }
    
363 364 365 366 367 368 369
    list ($loginhash, $logincrc) =
	DOLOGIN_MAGIC($this_user->uid(), $this_user->uid_idx(), null, 0, 1);
    if (! ($loginhash && $logincrc)) {
	SPITAJAX_ERROR(1, "Could not log you in. Sorry!");
	session_destroy();
	return;
    }
370
    if ($this_user->IsNonLocal() &&
371 372 373
        UpdateCredentials($this_user, $_SESSION["certificate"],
                          $speaksfor, $error)) {
	SPITAJAX_ERROR(-1, "Error updating user credentials: $error");
374 375 376
	session_destroy();
	return;
    }
377 378
    $this_user->Refresh();
    
379
    $blob = array();
380
    $blob["domain"]    = $COOKDIEDOMAIN;
381 382
    $blob["hashname"]  = $TBAUTHCOOKIE;
    $blob["hash"]      = $loginhash;
383 384 385 386 387
    $blob["crcname"]   = $TBLOGINCOOKIE;
    $blob["crc"]       = $logincrc;
    $blob["username"]  = $TBNAMECOOKIE;
    $blob["user"]      = $this_user->uid_idx();
    $blob["timeout"]   = time() + $TBAUTHTIMEOUT;
388 389 390
    $blob["webonly"]   = $this_user->webonly();
    $blob["portal"]    = ($this_user->webonly() && $domain == "ch.geni.net" ?
                          "https://portal.geni.net/" : "");
391 392 393 394
    if ($embedded) {
        $blob["url"]   = "showuser.php3";
    }
    else {
395 396 397
        $blob["url"]   = ($this_user->webonly() ||
                          !Instance::UserHasInstances($this_user)
                          ? "instantiate.php" : "myexperiments.php");
398
    }
399 400 401 402 403 404 405
    session_destroy();
    SPITAJAX_RESPONSE($blob);
}

#
# Create a new user. All we have is the email, urn, and uuid.
#
406
function CreateNonLocalUser($urn, $email)
407
{
408 409 410 411 412
    global $TBOPSPID;
    $safe_urn = escapeshellarg($urn);
    $safe_email = escapeshellarg($email);
    
    $retval = SUEXEC("elabman", $TBOPSPID,
Leigh Stoller's avatar
Leigh Stoller committed
413
		     "webcreategeniuser -p CloudLab $safe_urn $safe_email",
414 415 416 417 418 419 420 421 422 423
		     SUEXEC_ACTION_CONTINUE);
    if ($retval)
	return -1;

    return 0;
}

#
# Update the certificate/credential for the user.
# 
424
function UpdateCredentials($user, $cert, $cred, &$error)
425
{
426
    global $TBMAINSITE, $suexec_output;
427

428
    $uid = $user->uid();
429 430 431 432
    $project = $user->FirstApprovedProject();
    $pid = (isset($project) ? $project->pid() : "nobody");
    # Update keys on main site, no need to do this on backend clusters.
    $arg = ($TBMAINSITE ? "-s" : "");
433 434 435 436 437 438 439 440 441 442 443 444 445
    
    $credfile = tempnam("/tmp", "cert");
    $certfile = tempnam("/tmp", "cred");

    $fp = fopen($credfile, "w");
    fwrite($fp, $cred);
    fclose($fp);
    $fp = fopen($certfile, "w");
    fwrite($fp, $cert);
    fclose($fp);
    chmod($certfile, 0666);
    chmod($credfile, 0666);
    
446
    $retval = SUEXEC($uid, $pid,
447 448
		     "webupdategeniuser -p -u ".
                     "  -c $credfile -e $certfile $arg $uid",
449 450
		     SUEXEC_ACTION_CONTINUE);

Leigh Stoller's avatar
Leigh Stoller committed
451 452 453 454 455 456
    if ($retval) {
        $cred = file_get_contents($credfile);
        $cert = file_get_contents($certfile);
        TBERROR("webupdategeniuser failed.\n ".
                "Cert:\n${cert}\n\n".
                "Cred:\n${$cred}\n", 0);
457
        $error = $suexec_output;
Leigh Stoller's avatar
Leigh Stoller committed
458
    }
459 460 461 462 463 464 465
    unlink($credfile);
    unlink($certfile);
    
    if ($retval)
	return -1;

    return 0;
466 467
}

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
#
# Verify the certificate was signed by us, for a local user.
# 
function VerifyLocalUser($user, $cert)
{
    $certfile = tempnam("/tmp", "cert");

    $fp = fopen($certfile, "w");
    fwrite($fp, $cert);
    fclose($fp);
    chmod($certfile, 0666);
    
    $retval = SUEXEC("nobody", "nobody", "webverifycert $certfile",
		     SUEXEC_ACTION_CONTINUE);
    unlink($certfile);
    if ($retval)
	return -1;

    return 0;
}

489 490 491 492
# Local Variables:
# mode:php
# End:
?>