geni-login.ajax 14.2 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 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
    #
    # 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"];

117 118 119 120
    #
    # Watch for an expired or invalid certificate. 
    #
    if (VerifyLocalUser(null, $certificate)) {
121
        SPITAJAX_ERROR(1, "Cannot verify your certificate, please regenerate ".
122 123 124 125
                       "your certificate at your home portal (typically ".
                       "this would be https://portal.geni.net/). You must ".
                       "also flush your old certificate from ".
                       "from the Geni Authorization Tool.");
126 127 128
        return;
    }

129 130 131 132 133 134 135 136 137
    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");
138
    $userCertName = tempnam("/tmp", "pkcs7cert");
139 140 141 142 143 144 145 146 147

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

148 149 150
    $retval =
	myexec("/usr/bin/openssl smime -decrypt -inform PEM -inkey ".
	       "${TBDIR}/etc/genisa.pem -in $infname -out $outfname");
151

152 153
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal decryption error");
154 155 156 157 158 159 160 161 162 163 164 165
	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);

166 167 168 169
    $fp = fopen($userCertName, "w");
    fwrite($fp, $certificate);
    fclose($fp);

170 171 172
    $retval =
	myexec("/usr/bin/openssl smime -encrypt -outform PEM ".
	       "-in $infname -out $outfname -aes256 $userCertName");
173

174 175
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal encryption error");
176 177 178
	return;
    }
    $r2_encrypted = file_get_contents($outfname);
179
    $secret = $r1_decrypted . $r2_decrypted;
180 181 182 183 184 185 186 187 188 189 190

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

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

    unlink($infname);
    unlink($outfname);
191
    unlink($userCertName);
192 193 194 195 196 197 198 199 200
    SPITAJAX_RESPONSE($blob);
}

#
# 
#
function Do_VerifySpeaksfor()
{
    global $ajax_args;
201
    global $TBDIR, $COOKDIEDOMAIN, $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN;
202
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHTIMEOUT, $TBNAMECOOKIE;
203
    global $OURDOMAIN, $TBMAILADDR;
204
    $embedded = 0;
205

206 207 208 209
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    # 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;
    }
235
    if (isset($ajax_args["embedded"])) {
Leigh Stoller's avatar
Leigh Stoller committed
236
        $embedded = $ajax_args["embedded"];
237
    }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

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

262 263
    $retval = 
	myexec("$TBDIR/sbin/protogeni/parsecert $infname $outfname");
264

265 266 267
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal certificate parse error");
	session_destroy();
268
        unlink($infname);
269 270 271 272 273 274 275 276 277 278 279 280 281
	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");
282
	session_destroy();
283 284 285 286 287 288 289 290 291
	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.
292 293
    # 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.
294
    #
295 296 297 298 299 300
    if (!preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/",
                    $info["urn"], $matches)) {
        SPITAJAX_ERROR(1, "Bad URN");
	session_destroy();
	return;
    }
301 302 303
    $domain = $matches[1];

    if ($domain == $OURDOMAIN) {
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 329 330 331 332 333 334 335 336 337 338 339 340
        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;
            }
341
        }
342 343 344 345 346 347 348 349 350 351 352 353 354
        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);
                }
            }
355 356 357 358 359 360 361
            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;
            }
362
        }
363
    }
364 365 366 367 368 369 370 371 372 373 374
    #
    # 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;
    }
    
375 376 377 378 379 380 381
    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;
    }
382
    if ($this_user->IsNonLocal() &&
383 384 385
        UpdateCredentials($this_user, $_SESSION["certificate"],
                          $speaksfor, $error)) {
	SPITAJAX_ERROR(-1, "Error updating user credentials: $error");
386 387 388
	session_destroy();
	return;
    }
389 390
    $this_user->Refresh();
    
391
    $blob = array();
392
    $blob["domain"]    = $COOKDIEDOMAIN;
393 394
    $blob["hashname"]  = $TBAUTHCOOKIE;
    $blob["hash"]      = $loginhash;
395 396 397 398 399
    $blob["crcname"]   = $TBLOGINCOOKIE;
    $blob["crc"]       = $logincrc;
    $blob["username"]  = $TBNAMECOOKIE;
    $blob["user"]      = $this_user->uid_idx();
    $blob["timeout"]   = time() + $TBAUTHTIMEOUT;
400 401 402
    $blob["webonly"]   = $this_user->webonly();
    $blob["portal"]    = ($this_user->webonly() && $domain == "ch.geni.net" ?
                          "https://portal.geni.net/" : "");
403 404 405 406
    if ($embedded) {
        $blob["url"]   = "showuser.php3";
    }
    else {
407
        $blob["url"]   = "landing.php";
408
    }
409 410 411 412 413 414 415
    session_destroy();
    SPITAJAX_RESPONSE($blob);
}

#
# Create a new user. All we have is the email, urn, and uuid.
#
416
function CreateNonLocalUser($urn, $email)
417
{
418 419 420 421
    global $TBOPSPID;
    $safe_urn = escapeshellarg($urn);
    $safe_email = escapeshellarg($email);
    
422 423 424 425
    #
    # The script is going to lock for concurrent creation, and return
    # non-negative value if the user already exists.
    #
426
    $retval = SUEXEC("elabman", $TBOPSPID,
Leigh Stoller's avatar
Leigh Stoller committed
427
		     "webcreategeniuser -p CloudLab $safe_urn $safe_email",
428
		     SUEXEC_ACTION_CONTINUE);
429
    if ($retval < 0)
430 431 432 433 434 435 436 437
	return -1;

    return 0;
}

#
# Update the certificate/credential for the user.
# 
438
function UpdateCredentials($user, $cert, $cred, &$error)
439
{
440
    global $TBMAINSITE, $suexec_output;
441

442
    $uid = $user->uid();
443 444 445 446
    $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" : "");
447 448 449 450 451 452 453 454 455 456 457 458 459
    
    $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);
    
460
    $retval = SUEXEC($uid, $pid,
461 462
		     "webupdategeniuser -p -u ".
                     "  -c $credfile -e $certfile $arg $uid",
463 464
		     SUEXEC_ACTION_CONTINUE);

Leigh Stoller's avatar
Leigh Stoller committed
465 466 467 468 469 470
    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);
471
        $error = $suexec_output;
Leigh Stoller's avatar
Leigh Stoller committed
472
    }
473 474 475 476 477 478 479
    unlink($credfile);
    unlink($certfile);
    
    if ($retval)
	return -1;

    return 0;
480 481
}

482 483 484 485 486 487
#
# Verify the certificate was signed by us, for a local user.
# 
function VerifyLocalUser($user, $cert)
{
    $certfile = tempnam("/tmp", "cert");
488
    $args = ($user ? "" : "-e");
489 490 491 492 493 494

    $fp = fopen($certfile, "w");
    fwrite($fp, $cert);
    fclose($fp);
    chmod($certfile, 0666);
    
495
    $retval = SUEXEC("nobody", "nobody", "webverifycert $args $certfile",
496
		     SUEXEC_ACTION_IGNORE);
497 498 499 500 501 502 503
    unlink($certfile);
    if ($retval)
	return -1;

    return 0;
}

504 505 506 507
# Local Variables:
# mode:php
# End:
?>