nodetipacl.php3 10.4 KB
Newer Older
1
<?php
Leigh Stoller's avatar
Leigh Stoller committed
2
#
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
# 
# {{{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
include("defs.php3");
25
include_once("node_defs.php");
26
include("xmlrpc.php3");
27 28 29 30 31

#
# This script generates an "acl" file.
#
#
32
# Verify form arguments first, since we might be using optional key.
33
#
34 35 36 37
$reqargs = RequiredPageArguments("node",       PAGEARG_NODE);
$optargs = OptionalPageArguments("key",        PAGEARG_STRING,
				 "closekills", PAGEARG_BOOLEAN,
				 "noclose",    PAGEARG_BOOLEAN);
38 39 40

# Need these below
$node_id = $node->node_id();
41

42 43 44 45
if (isset($key)) {
    $safe_key = addslashes($key);
    
    $query_result =
46
	DBQueryFatal("select urlstamp,reuseurl from tiplines ".
47
		     "where node_id='$node_id' and urlhash='$safe_key' and ".
48
		     "      urlstamp!=0");
49 50
    
    if (mysql_num_rows($query_result) == 0) {
51 52 53 54 55
	USERERROR("Invalid node or invalid key", 1);
    } else {
	$row = mysql_fetch_array($query_result);
	$stamp = $row['urlstamp'];
	if ($stamp <= time()) {
56 57
	    DBQueryFatal("update tiplines set urlhash=NULL,urlstamp=0,".
			 "reuseurl=0 ".
58 59 60
	    		 "where node_id='$node_id'");
	    USERERROR("Key is no longer valid", 1);
	}
61
    }
62 63 64 65 66 67 68
    # URLs are use-once, unless marked as reusable (dangerous).
    $reuse = $row['reuseurl'];
    if ($reuse != 1) {
        DBQueryFatal("update tiplines set urlhash=NULL,urlstamp=0,".
                     "reuseurl=0 ".
                     "where node_id='$node_id'");
    }
69
    $uid = "nobody";
70 71 72 73 74 75 76 77 78 79 80
    $isadmin = 0;
}
else {
    #
    # Only known and logged in users can get acls..
    #
    $this_user = CheckLoginOrDie();
    $uid       = $this_user->uid();
    $isadmin   = ISADMIN();
}

81 82 83 84
#
# Admin users can look at any node, but normal users can only control
# nodes in their own experiments.
#
85 86
# Do not allow console access for certain node taint states.
#
87
# XXX is MODIFYINFO the correct one to check? (probably)
88
#
89 90 91 92 93 94 95
if (!$isadmin && !isset($key)) {
    if (!$node->AccessCheck($this_user, $TB_NODEACCESS_READINFO)) {
        USERERROR("You do not have permission to tip to node $node_id!", 1);
    }
    if ($node->IsTainted("useronly") || $node->IsTainted("blackbox")) {
        USERERROR("Node $node_id is in a restricted state - console access denied.", 1);
    }
96 97
}

98 99 100
# Array of arguments
$console = array();

101
#
102
# Ask outer emulab for the stuff we need. It does it own perm checks
103
#
104 105 106
if ($ELABINELAB) {
    $arghash = array();
    $arghash["node"] = $node_id;
107

108 109 110 111 112 113 114 115 116 117 118 119 120
    $results = XMLRPC($uid, "nobody", "elabinelab.console", $arghash);

    if (!$results ||
	! (isset($results{'server'})  && isset($results{'portnum'}) &&
	   isset($results{'keydata'}) && isset($results{'certsha'}))) {
	TBERROR("Did not get everything we needed from RPC call", 1);
    }

    $server  = $results['server'];
    $portnum = $results['portnum'];
    $keydata = $results['keydata'];
    $keylen  = strlen($keydata);
    $certhash= strtolower($results{'certsha'});
121
}
122
else {
123

124 125 126
    $query_result =
	DBQueryFatal("SELECT server, portnum, keylen, keydata, disabled " . 
		     "FROM tiplines WHERE node_id='$node_id'" );
127 128 129 130 131 132

    if (mysql_num_rows($query_result) == 0) {
	USERERROR("The node $node_id does not exist, ".
		  "or does not have a tipline!", 1);
    }
    $row = mysql_fetch_array($query_result);
133 134 135 136
    $server  = $row["server"];
    $portnum = $row["portnum"];
    $keylen  = $row["keylen"];
    $keydata = $row["keydata"];
137 138 139 140 141
    $disabled= $row["disabled"];

    if ($disabled) {
	USERERROR("The tipline for $node_id is currently disabled", 1);
    }
142 143 144 145 146

    #
    # Read in the fingerprint of the capture certificate
    #
    $capfile = "$TBETC_DIR/capture.fingerprint";
Leigh Stoller's avatar
Leigh Stoller committed
147
    $lines = file($capfile);
148 149 150 151 152 153 154 155 156 157
    if (!$lines) {
	TBERROR("Unable to open $capfile!",1);
    }

    $fingerline = rtrim($lines[0]);
    if (!preg_match("/Fingerprint=([\w:]+)$/",$fingerline,$matches)) {
	TBERROR("Unable to find fingerprint in string $fingerline!",1);
    }
    $certhash = str_replace(":","",strtolower($matches[1]));
}
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
if (! $BROWSER_CONSOLE_ENABLE) {
    $filename = $node_id . ".tbacl"; 

    header("Content-Type: text/x-testbed-acl");
    header("Content-Disposition: inline; filename=$filename;");
    header("Content-Description: ACL key file for a testbed node serial port");

    # XXX, should handle multiple tip lines gracefully somehow, 
    # but not important for now.

    echo "host:   $server\n";	
    echo "port:   $portnum\n";
    echo "keylen: $keylen\n";
    echo "key:    $keydata\n";
    echo "ssl-server-cert: $certhash\n";
    return;
}

#
# ShellInABox
#
$console["server"]   = $server;
$console["portnum"]  = $portnum;
$console["keylen"]   = $keylen;
$console["keydata"]  = $keydata;
$console["certhash"] = $certhash;

#
# Generate an authentication object to pass to the browser that
# is passed to the web server on ops. This is used to grant
# permission to the user to invoke tip to the console. 
#
function ConsoleAuthObject($uid, $nodeid, $console)
{
    global $USERNODE;
	
    $file = "/usr/testbed/etc/sshauth.key";
    
    #
    # We need the secret that is shared with ops.
    #
    $fp = fopen($file, "r");
    if (! $fp) {
Leigh Stoller's avatar
Leigh Stoller committed
202
	TBERROR("Error opening $file", 1);
203 204 205 206 207
	return null;
    }
    $key = fread($fp, 128);
    fclose($fp);
    if (!$key) {
Leigh Stoller's avatar
Leigh Stoller committed
208
	TBERROR("Could not get key from $file", 1);
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	return null;
    }
    $key   = chop($key);
    $stuff = GENHASH();
    $now   = time();

    $authobj = array('uid'       => $uid,
		     'console'   => $console,
		     'stuff'     => $stuff,
		     'nodeid'    => $nodeid,
		     'timestamp' => $now,
		     'baseurl'   => "https://${USERNODE}",
		     'signature_method' => 'HMAC-SHA1',
		     'api_version' => '1.0',
		     'signature' => hash_hmac('sha1',
					      $uid . $stuff . $nodeid . $now .
					      " " . implode(",", $console),
					      $key),
    );
    return json_encode($authobj);
}
$console_auth = ConsoleAuthObject($uid, $node_id, $console);

232 233 234
if (!isset($key)) {
    PAGEHEADER("$node_id Console");
}
235
$referrer = $_SERVER['HTTP_REFERER'];
236 237 238 239 240 241
if (!isset($closekills)) {
    $closekills = 0;
}
if (!isset($noclose)) {
    $noclose = 0;
}
242 243

echo "\n";
244
echo "<script src='$TBBASE/emulab_sup.js'></script>\n";
245 246
echo "<script src='https://code.jquery.com/jquery.js'></script>\n";
echo "<script>\n";
247 248 249
echo "var tbbaseurl  = '$referrer';\n";
echo "var closekills = $closekills;\n";
echo "var noclose    = $noclose;\n";
250 251 252 253 254 255 256 257 258 259 260 261 262 263
?>
function StartConsole(id, authobject)
{
    var jsonauth = $.parseJSON(authobject);
	
    var callback = function(stuff) {
        var split   = stuff.split(':');
        var session = split[0];
    	var port    = split[1];

        var url   = jsonauth.baseurl + ':' + port + '/' + '#' +
            encodeURIComponent(document.location.href) + ',' + session;
        console.log(url);
        var iwidth  = $('#' + id).width();
264 265 266 267 268 269 270 271 272 273 274 275
	var iheight = $(window).height();
	var Iframe  = getObjbyName(id);
	// Now get the Y offset of the outputframe.
	var yoff    = Iframe.offsetTop;

	if (iheight != 0 && yoff != 0) {
	    iheight = iheight - yoff;
	}
	else {
	    iheight = 200;
	}
        iheight = iheight - 25;
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	/*
	 * Oh, this is a pain.
	 *
	 * Firefox views the same server certificate on different
	 * ports, as needing to be confirmed. Since the server side of
	 * the console picks a new port each time, firefox wants to
	 * confirm the security exception each time.
	 *
	 * Firefox will not allow you to confirm aforementioned
	 * security exception when it is inside an iframe. It just
	 * tells you it is insecure, and thats it. The only way around
	 * it is to right-click and say open in new tab, and then you
	 * get the option to confirm.
	 *
	 * So put the damn in the current tab and be done with it. DUMB!
	 */
	if (is_firefox) {
	    PageReplace(url);
	}
	else {
	    $('#' + id).html('<iframe id="' + id + '_iframe" ' +
			     'width=' + iwidth + ' ' +
			     'height=' + iheight + ' ' +
			     'src=\'' + url + '\'>');

	    //
	    // Setup a custom event handler so we can kill the connection.
	    //
	    $('#' + id).on("killconsole",
		{ "url": jsonauth.baseurl + ':' + port + '/quit' +
			'?session=' + session },
		function(e) {
		    console.log("killconsole: " + e.data.url);
		    $.ajax({
			url: e.data.url,
				type: 'GET',
		    });
		});
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

	    addEventListener("message",
			     function(event) {
				 console.info(event);
				 // Trigger the custom event.
				 $("#" + id).trigger("killconsole");
			     },
			     false);

	    if (!noclose) {
		// Install a click handler for the X button.
		$("#" + id + "_kill").click(function(e) {
			e.preventDefault();
			// Trigger the custom event.
			$("#" + id).trigger("killconsole");
                    
			if (closekills) {
			    window.close();
			}
			else {
			    PageReplace(tbbaseurl);
			}
		    });
	    }
339 340 341
	}
    }
    var callback_failed = function(jqXHR, textStatus) {
342
	var acceptURL = jsonauth.baseurl + '/accept_cert.html';
343 344 345 346 347 348 349
	
	console.log("Request failed: " + textStatus);
	
	$('#' + id).html("An SSL certificate must be accepted by your " +
			 "browser to continue.  Please click " +
			 "<a href='" + acceptURL + "'>here</a> " +
			 "to be redirected.");
350
    }
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    var xmlthing = $.ajax({
	// the URL for the request
     	url: jsonauth.baseurl + '/d77e8041d1ad',
 
     	// the data to send (will be converted to a query string)
	data: {
	    auth: authobject,
	},
 
 	// Needs to be a POST to send the auth object.
	type: 'POST',
 
    	// Ask for plain text for easier parsing. 
	dataType : 'text',
    });
    xmlthing.done(callback);
368
    xmlthing.fail(callback_failed);
369 370 371 372
}
</script>

<?php
Leigh Stoller's avatar
Leigh Stoller committed
373
echo "<div id='${node_id}_console' style='width: 100%;'></div>";
374 375 376 377 378
if (!$noclose) {
    echo "<center><button type=button
                          id='${node_id}_console_kill'>Close</button>" .
	 "</center>\n";
}
379
echo "<script language=JavaScript>
380 381 382
        window.onload = function() {
            StartConsole('${node_id}_console', '$console_auth');
        }
383
      </script>\n";
384

385 386 387
if (!isset($key)) {
    PAGEFOOTER();
}
Chad Barb's avatar
Chad Barb committed
388
?>