geni-login.ajax 12.7 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2015 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
include_once("instance_defs.php");

#
# So we can capture stderr. Sheesh.
# 
function myexec($cmd)
{
    ignore_user_abort(1);

    $myexec_output_array = array();
    $myexec_output       = "";
    $myexec_retval       = 0;
    
    exec("$cmd 2>&1", $myexec_output_array, $myexec_retval);
    if ($myexec_retval) {
	for ($i = 0; $i < count($myexec_output_array); $i++) {
	    $myexec_output .= "$myexec_output_array[$i]\n";
	}
	$foo  = "Shell Program Error. Exit status: $myexec_retval\n";
	$foo .= "  '$cmd'\n";
	$foo .= "\n";
	$foo .= $myexec_output;
	TBERROR($foo, 0);
	return 1;
    }
    return 0;
}

#
# 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()
{
62
    global $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN, $TBDIR;
63 64
    $hash = GENHASH();

65 66 67 68
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
69 70 71 72 73
    # We use a session to hold stuff across the ajax calls
    session_start();
    session_regenerate_id(TRUE);

    $blob = array();
74 75 76
    $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";
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

    $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"];
106 107 108

    SPITAJAX_RESPONSE($blob);
}
109 110 111 112 113 114 115 116

#
# 
#
function Do_CreateSecret()
{
    global $ajax_args;
    global $TBDIR;
117
    global $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN;
118

119 120 121 122
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    #
    # 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");
152
    $userCertName = tempnam("/tmp", "pkcs7cert");
153 154 155 156 157 158 159 160 161

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

162 163 164
    $retval =
	myexec("/usr/bin/openssl smime -decrypt -inform PEM -inkey ".
	       "${TBDIR}/etc/genisa.pem -in $infname -out $outfname");
165

166 167
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal decryption error");
168 169 170 171 172 173 174 175 176 177 178 179
	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);

180 181 182 183
    $fp = fopen($userCertName, "w");
    fwrite($fp, $certificate);
    fclose($fp);

184 185 186
    $retval =
	myexec("/usr/bin/openssl smime -encrypt -outform PEM ".
	       "-in $infname -out $outfname -aes256 $userCertName");
187

188 189
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal encryption error");
190 191 192
	return;
    }
    $r2_encrypted = file_get_contents($outfname);
193
    $secret = $r1_decrypted . $r2_decrypted;
194 195 196 197 198 199 200 201 202 203 204

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

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

    unlink($infname);
    unlink($outfname);
205
    unlink($userCertName);
206 207 208 209 210 211 212 213 214
    SPITAJAX_RESPONSE($blob);
}

#
# 
#
function Do_VerifySpeaksfor()
{
    global $ajax_args;
215
    global $TBDIR, $COOKDIEDOMAIN, $TBMAINSITE, $PROTOGENI_GENIWEBLOGIN;
216
    global $TBAUTHCOOKIE, $TBLOGINCOOKIE, $TBAUTHTIMEOUT, $TBNAMECOOKIE;
217
    global $OURDOMAIN;
218
    $embedded = 0;
219

220 221 222 223
    if (! ($TBMAINSITE || $PROTOGENI_GENIWEBLOGIN)) {
        SPITAJAX_ERROR(1, "Geni Users are not allowed to login to this site");
	return;
    }
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    # 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;
    }
249
    if (isset($ajax_args["embedded"])) {
Leigh Stoller's avatar
Leigh Stoller committed
250
        $embedded = $ajax_args["embedded"];
251
    }
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

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

276 277
    $retval = 
	myexec("$TBDIR/sbin/protogeni/parsecert $infname $outfname");
278

279 280 281
    if ($retval) {
	SPITAJAX_ERROR(-1, "Internal certificate parse error");
	session_destroy();
282
        unlink($infname);
283 284 285 286 287 288 289 290 291 292 293 294 295
	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");
296
	session_destroy();
297 298 299 300 301 302 303 304 305
	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.
306 307
    # 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.
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 341 342 343 344 345 346 347 348 349 350 351 352
    if (!preg_match("/^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/",
                    $info["urn"], $matches)) {
        SPITAJAX_ERROR(1, "Bad URN");
	session_destroy();
	return;
    }
    if ($matches[1] == $OURDOMAIN) {
        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;
            }
353
        }
354
    }
355 356 357 358 359 360 361
    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;
    }
362 363
    if ($this_user->IsNonLocal() &&
        UpdateCredentials($this_user, $_SESSION["certificate"], $speaksfor)) {
364 365 366 367
	SPITAJAX_ERROR(-1, "Internal error updating user credentials");
	session_destroy();
	return;
    }
368
    $blob = array();
369
    $blob["domain"]    = $COOKDIEDOMAIN;
370 371
    $blob["hashname"]  = $TBAUTHCOOKIE;
    $blob["hash"]      = $loginhash;
372 373 374 375 376
    $blob["crcname"]   = $TBLOGINCOOKIE;
    $blob["crc"]       = $logincrc;
    $blob["username"]  = $TBNAMECOOKIE;
    $blob["user"]      = $this_user->uid_idx();
    $blob["timeout"]   = time() + $TBAUTHTIMEOUT;
377 378 379 380 381 382 383
    if ($embedded) {
        $blob["url"]   = "showuser.php3";
    }
    else {
        $blob["url"]   = (Instance::UserHasInstances($this_user)
                          ? "myexperiments.php" : "instantiate.php");
    }
384 385 386 387 388 389 390
    session_destroy();
    SPITAJAX_RESPONSE($blob);
}

#
# Create a new user. All we have is the email, urn, and uuid.
#
391
function CreateNonLocalUser($urn, $email)
392
{
393 394 395 396 397
    global $TBOPSPID;
    $safe_urn = escapeshellarg($urn);
    $safe_email = escapeshellarg($email);
    
    $retval = SUEXEC("elabman", $TBOPSPID,
398
		     "webcreategeniuser -p CloudLab $safe_urn $safe_email",
399 400 401 402 403 404 405 406 407 408 409 410
		     SUEXEC_ACTION_CONTINUE);
    if ($retval)
	return -1;

    return 0;
}

#
# Update the certificate/credential for the user.
# 
function UpdateCredentials($user, $cert, $cred)
{
411 412
    global $TBMAINSITE;

413
    $uid = $user->uid();
414 415 416 417
    $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" : "");
418 419 420 421 422 423 424 425 426 427 428 429 430
    
    $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);
    
431 432
    $retval = SUEXEC($uid, $pid,
		     "webupdategeniuser -c $credfile -e $certfile $arg $uid",
433 434
		     SUEXEC_ACTION_CONTINUE);

Leigh Stoller's avatar
Leigh Stoller committed
435 436 437 438 439 440 441
    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);
    }
442 443 444 445 446 447 448
    unlink($credfile);
    unlink($certfile);
    
    if ($retval)
	return -1;

    return 0;
449 450
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
#
# 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;
}

472 473 474 475
# Local Variables:
# mode:php
# End:
?>