test-common.py 16.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# Copyright (c) 2008-2013 University of Utah and the Flux Group.
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#

30 31 32 33 34 35 36 37 38 39 40 41 42 43
import six
try:
    from urlparse import urlsplit, urlunsplit
    from urllib import splitport
    import xmlrpclib
    import httplib
except:
    from urllib.parse import urlsplit, urlunsplit
    from urllib.request import splitport
    import xmlrpc.client as xmlrpclib
    import http.client as httplib
import os
import getopt
import sys
44
import time
David Johnson's avatar
David Johnson committed
45 46 47 48 49 50
import traceback
import ssl
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.x509.oid import NameOID
from cryptography.x509.oid import ExtensionOID
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 80 81 82

# Debugging output.
debug           = 0
impotent        = 0

HOME            = os.environ["HOME"]
# Path to my certificate
CERTIFICATE     = HOME + "/.ssl/encrypted.pem"
# Got tired of typing this over and over so I stuck it in a file.
PASSPHRASEFILE  = HOME + "/.ssl/password"
passphrase      = ""

CONFIGFILE      = ".protogeni-config.py"
GLOBALCONF      = HOME + "/" + CONFIGFILE
LOCALCONF       = CONFIGFILE
EXTRACONF       = None
SLICENAME       = "mytestslice"
REQARGS         = None
CMURI           = None
SAURI           = None
DELETE          = 0

selfcredentialfile = None
slicecredentialfile = None
admincredentialfile = None
speaksforcredential = None

if "DEFAULTAUTHENTICATE" not in globals():
    DEFAULTAUTHENTICATE=1

authenticate=DEFAULTAUTHENTICATE

David Johnson's avatar
David Johnson committed
83 84 85
verify = False
cacertificate = None

86 87
myprint = six.print_

88 89
if "Usage" not in dir():
    def Usage():
90 91
        myprint("usage: " + sys.argv[ 0 ] + " [option...]")
        myprint("Options:")
92 93 94 95 96
        BaseOptions()
        pass
    pass

def BaseOptions():
97
    myprint("""
98 99 100 101 102 103 104 105 106 107 108
    -a file, --admincredentials=file    read admin credentials from file
    -A, --authenticated                 authenticate client
    -c file, --credentials=file         read self-credentials from file
                                            [default: query from SA]
    -d, --debug                         be verbose about XML methods invoked
    -f file, --certificate=file         read SSL certificate from file
                                            [default: ~/.ssl/encrypted.pem]
    -h, --help                          show options and usage
    -l uri, --sa=uri                    specify uri of slice authority
                                            [default: local]
    -m uri, --cm=uri                    specify uri of component manager
109
                                            [default: local]""")
110
    if "ACCEPTSLICENAME" in globals():
111 112
        myprint("""    -n name, --slicename=name           specify human-readable name of slice
                                            [default: mytestslice]""")
113
        pass
114
    myprint("""    -p file, --passphrase=file          read passphrase from file
115 116 117 118 119
                                            [default: ~/.ssl/password]
    -r file, --read-commands=file       specify additional configuration file
    -s file, --slicecredentials=file    read slice credentials from file
                                            [default: query from SA]
    -S file, --speaksfor=file           read speaksfor credential from file
David Johnson's avatar
David Johnson committed
120 121
    -U, --unauthenticated               do not authenticate client
        --verify                        enable server verification
122
        --cacertificate=file            read CA certificate from file""")
123 124 125 126 127 128 129 130 131 132
    pass

try:
    opts, REQARGS = getopt.gnu_getopt( sys.argv[ 1: ], "a:Ac:df:hl:m:n:p:r:s:S:U",
                                       [ "admincredentials=", "authenticated",
                                         "credentials=", "debug",
                                         "certificate=", "help", "sa=", "cm=",
                                         "slicename=", "passphrase=",
                                         "read-commands=", "slicecredentials=",
                                         "speaksfor=", "unauthenticated",
David Johnson's avatar
David Johnson committed
133
                                         "delete", "verify", "cacertificate=" ] )
134

135 136
except getopt.GetoptError:
    myprint(str(sys.exc_info()[1]),file=sys.stderr)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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
    Usage()
    sys.exit( 1 )

args = REQARGS

if "PROTOGENI_CERTIFICATE" in os.environ:
    CERTIFICATE = os.environ[ "PROTOGENI_CERTIFICATE" ]
if "PROTOGENI_PASSPHRASE" in os.environ:
    PASSPHRASEFILE = os.environ[ "PROTOGENI_PASSPHRASE" ]

for opt, arg in opts:
    if opt in ( "-a", "--admincredentials" ):
        admincredentialfile = arg
    elif opt in ( "-A", "--authenticated" ):
        authenticate=1
    elif opt in ( "-c", "--credentials" ):
        selfcredentialfile = arg
    elif opt in ( "-d", "--debug" ):
        debug = 1
    elif opt in ( "-f", "--certificate" ):
        CERTIFICATE = arg
    elif opt in ( "-h", "--help" ):
        Usage()
        sys.exit( 0 )
    elif opt in ( "-l", "--sa" ):
        SAURI = arg
        if SAURI[-2:] == "cm":
            SAURI = SAURI[:-3]
    elif opt in ( "-m", "--cm" ):
        CMURI = arg
        if CMURI[-2:] == "cm":
            CMURI = CMURI[:-3]
        elif CMURI[-4:] == "cmv2":
            CMURI = CMURI[:-5]
            pass
        pass
    elif opt in ( "-n", "--slicename" ):
        SLICENAME = arg
    elif opt in ( "-p", "--passphrase" ):
        PASSPHRASEFILE = arg
    elif opt in ( "-r", "--read-commands" ):
        EXTRACONF = arg
    elif opt in ( "-s", "--slicecredentials" ):
        slicecredentialfile = arg
    elif opt in ( "-S", "--speaksfor" ):
        f = open(arg)
        speaksforcredential = f.read()
        f.close()
    elif opt in ( "-U", "--unauthenticated" ):
        authenticate=0
    elif opt in ( "--delete" ):
        DELETE = 1
David Johnson's avatar
David Johnson committed
189 190 191 192
    elif opt in ( "--verify" ):
        verify = True
    elif opt in ("--cacertificate"):
        cacertificate = arg
193 194 195

# try to load a cert even if we're not planning to authenticate, since we
# can use it to construct default authority locations
David Johnson's avatar
David Johnson committed
196 197 198 199 200
certdata = None
try:
    fd = open(CERTIFICATE)
    certdata = fd.read()
    fd.close()
201 202 203
except IOError:
    myprint('Error reading certificate file %s: %s' % (CERTIFICATE,sys.exc_info()[1].strerror))
cert = None
David Johnson's avatar
David Johnson committed
204
try:
205 206 207
    cert = x509.load_pem_x509_certificate(six.b(certdata),default_backend())
except Exception:
    myprint('Error loading certificate: %s' % (str(sys.exc_info()[1])))
David Johnson's avatar
David Johnson committed
208 209 210

if verify and cacertificate is not None:
    if not os.access(cacertificate, os.R_OK):
211
        myprint("CA Certificate cannot be accessed: " + cacertificate)
David Johnson's avatar
David Johnson committed
212
        sys.exit(-1);
213 214 215 216 217 218 219

# XMLRPC server: use www.emulab.net for the clearinghouse.
XMLRPC_SERVER   = { "ch" : "www.emulab.net", "sr" : "www.emulab.net" }
SERVER_PATH = { "ch" : ":12369/protogeni/xmlrpc/",
                "sr" : ":12370/protogeni/pubxmlrpc/" }

try:
David Johnson's avatar
David Johnson committed
220 221 222 223 224 225 226 227 228 229 230 231 232
    descriptors = cert.extensions.get_extension_for_oid(
        ExtensionOID.AUTHORITY_INFORMATION_ACCESS).value
    url = None
    for d in descriptors:
        if d.access_method.dotted_string == '2.25.305821105408246119474742976030998643995':
            url = d.access_location.value
            break
    if url:
        url = url.rstrip()
        # strip trailing sa
        if url.endswith('/sa') > 0:
            url = url[:-2]
        scheme, netloc, path, query, fragment = urlsplit(url)
233
        host,port = splitport(netloc)
David Johnson's avatar
David Johnson committed
234
        XMLRPC_SERVER["default"] = host
235
        if port:
David Johnson's avatar
David Johnson committed
236
            path = ":" + port + path
237
        SERVER_PATH["default"] = path
238
except Exception:
David Johnson's avatar
David Johnson committed
239
    if debug:
240
        myprint("Warning: error getting authInfoAccess extension value:")
David Johnson's avatar
David Johnson committed
241
        traceback.print_exc()
242 243 244
    pass

if "default" not in XMLRPC_SERVER:
David Johnson's avatar
David Johnson committed
245 246
    XMLRPC_SERVER["default"] = cert.issuer.get_attributes_for_oid(
        NameOID.COMMON_NAME)[0].value
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    SERVER_PATH ["default"] = ":443/protogeni/xmlrpc/"
pass

if os.path.exists( GLOBALCONF ):
    execfile( GLOBALCONF )
if os.path.exists( LOCALCONF ):
    execfile( LOCALCONF )
if EXTRACONF and os.path.exists( EXTRACONF ):
    execfile( EXTRACONF )

if "sa" in XMLRPC_SERVER:
    HOSTNAME = XMLRPC_SERVER[ "sa" ]
else:
    HOSTNAME = XMLRPC_SERVER[ "default" ]
DOMAIN   = HOSTNAME[HOSTNAME.find('.')+1:]
SLICEURN = "urn:publicid:IDN+" + DOMAIN + "+slice+" + SLICENAME

David Johnson's avatar
David Johnson committed
264 265 266 267 268 269 270
# If the passphrase file exists, read it:
passphrase = None
if os.path.exists(PASSPHRASEFILE):
    try:
        passphrase = open(PASSPHRASEFILE).readline()
        passphrase = passphrase.strip()
        if passphrase == '':
271
            myprint('Passphrase file empty; you may be prompted')
David Johnson's avatar
David Johnson committed
272
            passphrase = None
273 274 275
    except IOError:
        myprint('Error reading passphrase file %s: %s' % (
            PASSPHRASEFILE,sys.exc_info()[1].strerror))
David Johnson's avatar
David Johnson committed
276 277
else:
    if debug:
278
        myprint('Passphrase file %s does not exist' % (PASSPHRASEFILE))
David Johnson's avatar
David Johnson committed
279

280
def Fatal(message):
281
    myprint(message,file=sys.stderr)
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 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
    sys.exit(1)

def geni_am_response_handler(method, method_args):
    """Handles the GENI AM responses, which are different from the
    ProtoGENI responses. ProtoGENI always returns a dict with three
    keys (code, value, and output. GENI AM operations return the
    value, or an XML RPC Fault if there was a problem.
    """
    return apply(method, method_args)

def geni_sr_response_handler(method, method_args):
    """Handles the GENI SR responses, which are different from the
    ProtoGENI responses. ProtoGENI always returns a dict with three
    keys (code, value, and output). GENI SR operations return the
    value, or an XML RPC Fault if there was a problem.
    """
    return apply(method, method_args)

#
# Call the rpc server.
#
def do_method(module, method, params, URI=None, quiet=False, version=None,
              response_handler=None):
    #
    # Add speaksforcredential for credentials list.
    #
    if "credentials" in params and speaksforcredential:
        if 1 or type(params["credentials"]) is tuple:
            params["credentials"] = list(params["credentials"])
            pass
        params["credentials"].append(speaksforcredential);
        pass
    
    if URI == None and CMURI and (module == "cm" or module == "cmv2"):
        URI = CMURI
    elif URI == None and SAURI and module == "sa":
        URI = SAURI

    if URI == None:
        if module in XMLRPC_SERVER:
            addr = XMLRPC_SERVER[ module ]
        else:
            addr = XMLRPC_SERVER[ "default" ]

        if module in SERVER_PATH:
            path = SERVER_PATH[ module ]
        else:
            path = SERVER_PATH[ "default" ]

        URI = "https://" + addr + path + module
    elif module:
        URI = URI + "/" + module
        pass

    if version:
        URI = URI + "/" + version
        pass

    url = urlsplit(URI, "https")

    if debug:
343
        myprint(str( url ) + " " + method)
344 345

    if url.scheme == "https":
David Johnson's avatar
David Johnson committed
346
        if authenticate and not cert:
347
            if not quiet:
348
                myprint("error: missing emulab certificate: " + CERTIFICATE,file=sys.stderr)
349 350 351 352
            return (-1, None)

        port = url.port if url.port else 443

David Johnson's avatar
David Johnson committed
353
        ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
354
        if authenticate:
David Johnson's avatar
David Johnson committed
355 356 357 358 359 360 361 362 363 364
            ctx.load_cert_chain(CERTIFICATE,password=passphrase)
        if not verify:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        else:
            if cacertificate:
                ctx.load_verify_locations(cafile=cacertificate)
            ctx.verify_mode = ssl.CERT_REQUIRED

        server = httplib.HTTPSConnection( url.hostname, port, context = ctx )
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    elif url.scheme == "http":
        port = url.port if url.port else 80
        server = httplib.HTTPConnection( url.hostname, port )
        
    if response_handler:
        # If a response handler was passed, use it and return the result.
        # This is the case when running the GENI AM.
        def am_helper( server, path, body ):
            server.request( "POST", path, body )
            return xmlrpclib.loads( server.getresponse().read() )[ 0 ][ 0 ]
            
        return response_handler( ( lambda *x: am_helper( server, url.path, xmlrpclib.dumps( x, method ) ) ), params )

    #
    # Make the call. 
    #
    while True:
        try:
            server.request( "POST", url.path, xmlrpclib.dumps( (params,), method ) )
            response = server.getresponse()
            if response.status == 503:
                if not quiet:
387
                    myprint("Will try again in a moment. Be patient!",file=sys.stderr)
388 389 390 391
                time.sleep(5.0)
                continue
            elif response.status != 200:
                if not quiet:
392
                    myprint(str(response.status) + " " + response.reason,file=sys.stderr)
393 394 395
                return (-1,None)
            response = xmlrpclib.loads( response.read() )[ 0 ][ 0 ]
            break
396 397
        except httplib.HTTPException:
            if not quiet: myprint(sys.exc_info()[1],file=sys.stderr)
398
            return (-1, None)
399 400
        except xmlrpclib.Fault:
            e = sys.exc_info()[1]
401
            if e.faultCode == 503:
402
                myprint(e.faultString + " Retrying\n",file=sys.stderr)
403 404
                time.sleep(5.0)
                continue;
405
            if not quiet: myprint(e.faultString,file=sys.stderr)
406
            return (-1, None)
407 408
        except ssl.CertificateError:
            e = sys.exc_info()[1]
409
            if not quiet:
410 411 412 413 414
                myprint("Warning: possible certificate host name mismatch.",file=sys.stderr)
                myprint("Please consult:",file=sys.stderr)
                myprint("    http://www.protogeni.net/trac/protogeni/wiki/HostNameMismatch",file=sys.stderr)
                myprint("for recommended solutions.",file=sys.stderr)
                myprint(e,file=sys.stderr)
415 416 417 418 419 420 421 422 423
                pass
            return (-1, None)

    #
    # Parse the Response, which is a Dictionary. See EmulabResponse in the
    # emulabclient.py module. The XML standard converts classes to a plain
    # Dictionary, hence the code below. 
    # 
    if response[ "code" ] and len(response["output"]):
424
        if not quiet: myprint(response["output"] + ":",file=sys.stderr)
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
        pass

    rval = response["code"]

    #
    # If the code indicates failure, look for a "value". Use that as the
    # return value instead of the code. 
    # 
    if rval:
        if response["value"]:
            rval = response["value"]
            pass
        pass
    return (rval, response)

def get_self_credential():
    if selfcredentialfile:
        f = open( selfcredentialfile )
        c = f.read()
        f.close()
        return c
    params = {}
    rval,response = do_method_retry("sa", "GetCredential", params)
    if rval:
        Fatal("Could not get my credential")
        pass
    return response["value"]

def do_method_retry(suffix, method, params):
  count = 200;
  rval, response = do_method(suffix, method, params)
  while count > 0 and response and response["code"] == 14:
      count = count - 1
458
      myprint(" Will try again in a few seconds\n")
459 460 461 462 463 464 465
      time.sleep(5.0)
      rval, response = do_method(suffix, method, params)
  return (rval, response)

def resolve_slice( name, selfcredential ):
    if slicecredentialfile:
        myslice = {}
466
        myslice["urn"] = SLICEURN
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        return myslice
    params = {}
    params["credential"] = mycredential
    params["type"]       = "Slice"
    if name.startswith("urn:"):
        params["urn"]       = name
    else:
        params["hrn"]       = name
        pass
    
    while True:
        rval,response = do_method_retry("sa", "Resolve", params)
        if rval:
            Fatal("Slice does not exist");
            pass
        else:
            break
        pass
    return response["value"]

def get_slice_credential( slice, selfcredential ):
    if slicecredentialfile:
        f = open( slicecredentialfile )
        c = f.read()
        f.close()
        return c

    params = {}
    params["credential"] = selfcredential
    params["type"]       = "Slice"
    if "urn" in slice:
        params["urn"]       = slice["urn"]
    else:
        params["uuid"]      = slice["uuid"]
        pass

    while True:
        rval,response = do_method_retry("sa", "GetCredential", params)
        if rval:
            Fatal("Could not get Slice credential")
            pass
        else:
            break
        pass
    return response["value"]