コード例 #1
0
def get_keypair(config = None):
    if not config:
        config = SfaConfig()
    hierarchy = Hierarchy()
    key_dir= hierarchy.basedir
    data_dir = config.data_path
    keyfile =data_dir + os.sep + "server.key"
    certfile = data_dir + os.sep + "server.cert"

    # check if files already exist
    if os.path.exists(keyfile) and os.path.exists(certfile):
        return (keyfile, certfile)

    # create temp keypair server key and certificate
    (_, tmp_keyfile) = tempfile.mkstemp(suffix='.pkey', prefix='tmpkey', dir='/tmp')
    (_, tmp_certfile) = tempfile.mkstemp(suffix='.cert', prefix='tmpcert', dir='/tmp') 
    tmp_key = Keypair(create=True)
    tmp_key.save_to_file(tmp_keyfile)
    tmp_cert = Certificate(subject='subject')
    tmp_cert.set_issuer(key=tmp_key, subject='subject')
    tmp_cert.set_pubkey(tmp_key)
    tmp_cert.save_to_file(tmp_certfile, save_parents=True)

    # request real pkey from registry
    api = ComponentAPI(key_file=tmp_keyfile, cert_file=tmp_certfile)
    registry = api.get_registry()
    registry.get_key()
    key = Keypair(filename=keyfile)
    cert = Certificate(subject=hrn)
    cert.set_issuer(key=key, subject=hrn)
    cert.set_pubkey(key)
    cert.sign()
    cert.save_to_file(certfile, save_parents=True)
    return (keyfile, certfile)
コード例 #2
0
ファイル: registry_manager.py プロジェクト: aquila/sfa
    def get_key_from_incoming_ip (self, api):
        dbsession=api.dbsession()
        # verify that the callers's ip address exist in the db and is an interface
        # for a node in the db
        (ip, port) = api.remote_addr
        interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
        if not interfaces:
            raise NonExistingRecord("no such ip %(ip)s" % locals())
        nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
        if not nodes:
            raise NonExistingRecord("no such node using ip %(ip)s" % locals())
        node = nodes[0]
       
        # look up the sfa record
        record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
        if not record:
            raise RecordNotFound("node with pointer %s"%node['node_id'])
        
        # generate a new keypair and gid
        uuid = create_uuid()
        pkey = Keypair(create=True)
        urn = hrn_to_urn(record.hrn, record.type)
        gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
        gid = gid_object.save_to_string(save_parents=True)
        record.gid = gid

        # update the record
        dbsession.commit()
  
        # attempt the scp the key
        # and gid onto the node
        # this will only work for planetlab based components
        (kfd, key_filename) = tempfile.mkstemp() 
        (gfd, gid_filename) = tempfile.mkstemp() 
        pkey.save_to_file(key_filename)
        gid_object.save_to_file(gid_filename, save_parents=True)
        host = node['hostname']
        key_dest="/etc/sfa/node.key"
        gid_dest="/etc/sfa/node.gid" 
        scp = "/usr/bin/scp" 
        #identity = "/etc/planetlab/root_ssh_key.rsa"
        identity = "/etc/sfa/root_ssh_key"
        scp_options=" -i %(identity)s " % locals()
        scp_options+="-o StrictHostKeyChecking=no " % locals()
        scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
                         locals()
        scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
                         locals()    

        all_commands = [scp_key_command, scp_gid_command]
        
        for command in all_commands:
            (status, output) = commands.getstatusoutput(command)
            if status:
                raise Exception, output

        for filename in [key_filename, gid_filename]:
            os.unlink(filename)

        return 1 
コード例 #3
0
ファイル: testKeypair.py プロジェクト: gnogueras/sfa
   def testSaveLoadFile(self):
      k = Keypair()
      k.create()

      k.save_to_file("test.key")

      k2 = Keypair()
      k2.load_from_file("test.key")

      self.assertEqual(k.as_pem(), k2.as_pem())
コード例 #4
0
ファイル: testKeypair.py プロジェクト: tubav/sfa
    def testSaveLoadFile(self):
        k = Keypair()
        k.create()

        k.save_to_file("test.key")

        k2 = Keypair()
        k2.load_from_file("test.key")

        self.assertEqual(k.as_pem(), k2.as_pem())
コード例 #5
0
ファイル: forms.py プロジェクト: fp7-alien/C-BAS
class UploadCertForm(forms.Form):
    """Form to upload a certificate and its corresponding key."""
    
    key_file = forms.FileField(
        help_text="Select the file that contains the key for the "\
            "certificate to upload.")
    cert_file = forms.FileField(
        help_text="Select the file that contains the "\
            "certificate to upload. The certificate must be signed "\
            "with the uploaded key.")
    
    clean_key_file = _clean_x_file_factory("key")
    clean_cert_file = _clean_x_file_factory("cert")
            
    def clean(self):
        """Check that the cert file is signed by the key file and is trusted."""
        logger.debug("cleaned_data %s" % self.cleaned_data)
        if self.files:
            self.key = Keypair(string=self.files["key_file"].read())
            self.cert = GID(string=self.files["cert_file"].read())
            
            cert_pubkey = self.cert.get_pubkey().get_pubkey_string()
            if cert_pubkey != self.key.get_pubkey_string():
                raise forms.ValidationError(
                    "Error: The certificate was not signed "
                    "by the uploaded key. Please use a key "
                    "that matches the certificate.")
    
            try:
                certs = [GID(filename=f) for f in get_trusted_cert_filenames()]
                self.cert.verify_chain(certs)
            except Exception as e:
                logger.error(traceback.format_exc())
                raise forms.ValidationError(
                    "Could not verify that the uploaded certificate is "
                    "trusted. This could be because none of the certificate's "
                    "ancestors have been installed as trusted. The error was: "
                    "%s" % e
                )

        return self.cleaned_data
    
    def save(self, user):
        """Write the key and cert into files.
        
        @param user: the user to save the cert and key for.
        @type user: C{django.contrib.auth.models.User}
        """
        
        key_fname = get_user_key_fname(user)
        cert_fname = get_user_cert_fname(user)
        
        self.key.save_to_file(key_fname)
        self.cert.save_to_file(cert_fname)
コード例 #6
0
ファイル: sfa_component_setup.py プロジェクト: aquila/sfa
def create_server_keypair(keyfile=None, certfile=None, hrn="component", verbose=False):
    """
    create the server key/cert pair in the right place
    """
    key = Keypair(filename=keyfile)
    key.save_to_file(keyfile)
    cert = Certificate(subject=hrn)
    cert.set_issuer(key=key, subject=hrn)
    cert.set_pubkey(key)
    cert.sign()
    cert.save_to_file(certfile, save_parents=True)       
コード例 #7
0
ファイル: forms.py プロジェクト: cargious/ocf
class UploadCertForm(forms.Form):
    """Form to upload a certificate and its corresponding key."""

    key_file = forms.FileField(
        help_text="Select the file that contains the key for the "\
            "certificate to upload.")
    cert_file = forms.FileField(
        help_text="Select the file that contains the "\
            "certificate to upload. The certificate must be signed "\
            "with the uploaded key.")

    clean_key_file = _clean_x_file_factory("key")
    clean_cert_file = _clean_x_file_factory("cert")

    def clean(self):
        """Check that the cert file is signed by the key file and is trusted."""
        logger.debug("cleaned_data %s" % self.cleaned_data)
        if self.files:
            self.key = Keypair(string=self.files["key_file"].read())
            self.cert = GID(string=self.files["cert_file"].read())

            cert_pubkey = self.cert.get_pubkey().get_pubkey_string()
            if cert_pubkey != self.key.get_pubkey_string():
                raise forms.ValidationError(
                    "Error: The certificate was not signed "
                    "by the uploaded key. Please use a key "
                    "that matches the certificate.")

            try:
                certs = [GID(filename=f) for f in get_trusted_cert_filenames()]
                self.cert.verify_chain(certs)
            except Exception as e:
                logger.error(traceback.format_exc())
                raise forms.ValidationError(
                    "Could not verify that the uploaded certificate is "
                    "trusted. This could be because none of the certificate's "
                    "ancestors have been installed as trusted. The error was: "
                    "%s" % e)

        return self.cleaned_data

    def save(self, user):
        """Write the key and cert into files.
        
        @param user: the user to save the cert and key for.
        @type user: C{django.contrib.auth.models.User}
        """

        key_fname = get_user_key_fname(user)
        cert_fname = get_user_cert_fname(user)

        self.key.save_to_file(key_fname)
        self.cert.save_to_file(cert_fname)
コード例 #8
0
def create_server_keypair(keyfile=None,
                          certfile=None,
                          hrn="component",
                          verbose=False):
    """
    create the server key/cert pair in the right place
    """
    key = Keypair(filename=keyfile)
    key.save_to_file(keyfile)
    cert = Certificate(subject=hrn)
    cert.set_issuer(key=key, subject=hrn)
    cert.set_pubkey(key)
    cert.sign()
    cert.save_to_file(certfile, save_parents=True)
コード例 #9
0
ファイル: sfa_component_setup.py プロジェクト: aquila/sfa
def get_node_key(registry=None, verbose=False):
    # this call requires no authentication, 
    # so we can generate a random keypair here
    subject="component"
    (kfd, keyfile) = tempfile.mkstemp()
    (cfd, certfile) = tempfile.mkstemp()
    key = Keypair(create=True)
    key.save_to_file(keyfile)
    cert = Certificate(subject=subject)
    cert.set_issuer(key=key, subject=subject)
    cert.set_pubkey(key)
    cert.sign()
    cert.save_to_file(certfile)
    
    registry = server_proxy(url = registry, keyfile=keyfile, certfile=certfile)    
    registry.get_key_from_incoming_ip()
コード例 #10
0
def get_node_key(registry=None, verbose=False):
    # this call requires no authentication,
    # so we can generate a random keypair here
    subject = "component"
    (kfd, keyfile) = tempfile.mkstemp()
    (cfd, certfile) = tempfile.mkstemp()
    key = Keypair(create=True)
    key.save_to_file(keyfile)
    cert = Certificate(subject=subject)
    cert.set_issuer(key=key, subject=subject)
    cert.set_pubkey(key)
    cert.sign()
    cert.save_to_file(certfile)

    registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile)
    registry.get_key_from_incoming_ip()
コード例 #11
0
ファイル: plcomponentdriver.py プロジェクト: aquila/sfa
 def get_node_key(self):
     # this call requires no authentication,
     # so we can generate a random keypair here
     subject="component"
     (kfd, keyfile) = tempfile.mkstemp()
     (cfd, certfile) = tempfile.mkstemp()
     key = Keypair(create=True)
     key.save_to_file(keyfile)
     cert = Certificate(subject=subject)
     cert.set_issuer(key=key, subject=subject)
     cert.set_pubkey(key)
     cert.sign()
     cert.save_to_file(certfile)
     registry = self.get_registry()
     # the registry will scp the key onto the node
     registry.get_key_from_incoming_ip()        
コード例 #12
0
ファイル: plcomponentdriver.py プロジェクト: gnogueras/sfa
 def get_node_key(self):
     # this call requires no authentication,
     # so we can generate a random keypair here
     subject = "component"
     (kfd, keyfile) = tempfile.mkstemp()
     (cfd, certfile) = tempfile.mkstemp()
     key = Keypair(create=True)
     key.save_to_file(keyfile)
     cert = Certificate(subject=subject)
     cert.set_issuer(key=key, subject=subject)
     cert.set_pubkey(key)
     cert.sign()
     cert.save_to_file(certfile)
     registry = self.get_registry()
     # the registry will scp the key onto the node
     registry.get_key_from_incoming_ip()
コード例 #13
0
def GetCredential(registry=None, force=False, verbose=False):
    config = Config()
    hierarchy = Hierarchy()
    key_dir = hierarchy.basedir
    data_dir = config.data_path
    config_dir = config.config_path
    credfile = data_dir + os.sep + 'node.cred'
    # check for existing credential
    if not force and os.path.exists(credfile):
        if verbose:
            print "Loading Credential from %(credfile)s " % locals()
        cred = Credential(filename=credfile).save_to_string(save_parents=True)
    else:
        if verbose:
            print "Getting credential from registry"
        # make sure node private key exists
        node_pkey_file = config_dir + os.sep + "node.key"
        node_gid_file = config_dir + os.sep + "node.gid"
        if not os.path.exists(node_pkey_file) or \
           not os.path.exists(node_gid_file):
            get_node_key(registry=registry, verbose=verbose)

        gid = GID(filename=node_gid_file)
        hrn = gid.get_hrn()
        # create server key and certificate
        keyfile = data_dir + os.sep + "server.key"
        certfile = data_dir + os.sep + "server.cert"
        key = Keypair(filename=node_pkey_file)
        key.save_to_file(keyfile)
        create_server_keypair(keyfile, certfile, hrn, verbose)

        # get credential from registry
        registry = server_proxy(url=registry,
                                keyfile=keyfile,
                                certfile=certfile)
        cert = Certificate(filename=certfile)
        cert_str = cert.save_to_string(save_parents=True)
        cred = registry.GetSelfCredential(cert_str, 'node', hrn)
        Credential(string=cred).save_to_file(credfile, save_parents=True)

    return cred
コード例 #14
0
ファイル: sfa-server.py プロジェクト: planetlab/sfa
def init_server_key(server_key_file, server_cert_file, config, hierarchy):

    hrn = config.SFA_INTERFACE_HRN.lower()
    # check if the server's private key exists. If it doesnt,
    # get the right one from the authorities directory. If it cant be
    # found in the authorities directory, generate a random one
    if not os.path.exists(server_key_file):
        hrn = config.SFA_INTERFACE_HRN.lower()
        hrn_parts = hrn.split(".")
        rel_key_path = hrn
        pkey_filename = hrn + ".pkey"

        # sub authority's have "." in their hrn. This must
        # be converted to os.path separator
        if len(hrn_parts) > 0:
            rel_key_path = hrn.replace(".", os.sep)
            pkey_filename = hrn_parts[-1] + ".pkey"

        key_file = os.sep.join([hierarchy.basedir, rel_key_path, pkey_filename])
        if not os.path.exists(key_file):
            # if it doesnt exist then this is probably a fresh interface
            # with no records. Generate a random keypair for now
            logger.debug("server's public key not found in %s" % key_file)

            logger.debug("generating a random server key pair")
            key = Keypair(create=True)
            key.save_to_file(server_key_file)
            init_server_cert(hrn, key, server_cert_file, self_signed=True)

        else:
            # the pkey was found in the authorites directory. lets
            # copy it to where the server key should be and generate
            # the cert
            key = Keypair(filename=key_file)
            key.save_to_file(server_key_file)
            init_server_cert(hrn, key, server_cert_file)

    # If private key exists and cert doesnt, recreate cert
    if (os.path.exists(server_key_file)) and (not os.path.exists(server_cert_file)):
        key = Keypair(filename=server_key_file)
        init_server_cert(hrn, key, server_cert_file)
コード例 #15
0
ファイル: sfa_component_setup.py プロジェクト: aquila/sfa
def GetCredential(registry=None, force=False, verbose=False):
    config = Config()
    hierarchy = Hierarchy()
    key_dir= hierarchy.basedir
    data_dir = config.data_path
    config_dir = config.config_path
    credfile = data_dir + os.sep + 'node.cred'
    # check for existing credential
    if not force and os.path.exists(credfile):
        if verbose:
            print "Loading Credential from %(credfile)s " % locals()  
        cred = Credential(filename=credfile).save_to_string(save_parents=True)
    else:
        if verbose:
            print "Getting credential from registry" 
        # make sure node private key exists
        node_pkey_file = config_dir + os.sep + "node.key"
        node_gid_file = config_dir + os.sep + "node.gid"
        if not os.path.exists(node_pkey_file) or \
           not os.path.exists(node_gid_file):
            get_node_key(registry=registry, verbose=verbose)
        
        gid = GID(filename=node_gid_file)
        hrn = gid.get_hrn()
        # create server key and certificate
        keyfile =data_dir + os.sep + "server.key"
        certfile = data_dir + os.sep + "server.cert"
        key = Keypair(filename=node_pkey_file)
        key.save_to_file(keyfile)
        create_server_keypair(keyfile, certfile, hrn, verbose)

        # get credential from registry 
        registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile)
        cert = Certificate(filename=certfile)
        cert_str = cert.save_to_string(save_parents=True)
        cred = registry.GetSelfCredential(cert_str, 'node', hrn)
        Credential(string=cred).save_to_file(credfile, save_parents=True)
    
    return cred
コード例 #16
0
ファイル: get_key.py プロジェクト: planetlab/sfa
    def call(self):
        # verify that the callers's ip address exist in the db and is an inteface
        # for a node in the db
        (ip, port) = self.api.remote_addr
        interfaces = self.api.plshell.GetInterfaces(self.api.plauth, {'ip': ip}, ['node_id'])
        if not interfaces:
            raise NonExistingRecord("no such ip %(ip)s" % locals())
        nodes = self.api.plshell.GetNodes(self.api.plauth, [interfaces[0]['node_id']], ['node_id', 'hostname'])
        if not nodes:
            raise NonExistingRecord("no such node using ip %(ip)s" % locals())
        node = nodes[0]
       
        # look up the sfa record
        table = SfaTable()
        records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
        if not records:
            raise RecordNotFound("pointer:" + str(node['node_id']))  
        record = records[0]
        
        # generate a new keypair and gid
        uuid = create_uuid()
        pkey = Keypair(create=True)
        urn = hrn_to_urn(record['hrn'], record['type'])
        gid_object = self.api.auth.hierarchy.create_gid(urn, uuid, pkey)
        gid = gid_object.save_to_string(save_parents=True)
        record['gid'] = gid
        record.set_gid(gid)

        # update the record
        table.update(record)
  
        # attempt the scp the key
        # and gid onto the node
        # this will only work for planetlab based components
        (kfd, key_filename) = tempfile.mkstemp() 
        (gfd, gid_filename) = tempfile.mkstemp() 
        pkey.save_to_file(key_filename)
        gid_object.save_to_file(gid_filename, save_parents=True)
        host = node['hostname']
        key_dest="/etc/sfa/node.key"
        gid_dest="/etc/sfa/node.gid" 
        scp = "/usr/bin/scp" 
        #identity = "/etc/planetlab/root_ssh_key.rsa"
        identity = "/etc/sfa/root_ssh_key"
        scp_options=" -i %(identity)s " % locals()
        scp_options+="-o StrictHostKeyChecking=no " % locals()
        scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
                         locals()
        scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
                         locals()    

        all_commands = [scp_key_command, scp_gid_command]
        
        for command in all_commands:
            (status, output) = commands.getstatusoutput(command)
            if status:
                raise Exception, output

        for filename in [key_filename, gid_filename]:
            os.unlink(filename)

        return 1 
コード例 #17
0
ファイル: registry_manager.py プロジェクト: gnogueras/sfa
    def get_key_from_incoming_ip(self, api):
        dbsession = api.dbsession()
        # verify that the callers's ip address exist in the db and is an interface
        # for a node in the db
        (ip, port) = api.remote_addr
        interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
        if not interfaces:
            raise NonExistingRecord("no such ip %(ip)s" % locals())
        nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']],
                                          ['node_id', 'hostname'])
        if not nodes:
            raise NonExistingRecord("no such node using ip %(ip)s" % locals())
        node = nodes[0]

        # look up the sfa record
        record = dbsession.query(RegRecord).filter_by(
            type='node', pointer=node['node_id']).first()
        if not record:
            raise RecordNotFound("node with pointer %s" % node['node_id'])

        # generate a new keypair and gid
        uuid = create_uuid()
        pkey = Keypair(create=True)
        urn = hrn_to_urn(record.hrn, record.type)
        gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
        gid = gid_object.save_to_string(save_parents=True)
        record.gid = gid

        # update the record
        dbsession.commit()

        # attempt the scp the key
        # and gid onto the node
        # this will only work for planetlab based components
        (kfd, key_filename) = tempfile.mkstemp()
        (gfd, gid_filename) = tempfile.mkstemp()
        pkey.save_to_file(key_filename)
        gid_object.save_to_file(gid_filename, save_parents=True)
        host = node['hostname']
        key_dest = "/etc/sfa/node.key"
        gid_dest = "/etc/sfa/node.gid"
        scp = "/usr/bin/scp"
        #identity = "/etc/planetlab/root_ssh_key.rsa"
        identity = "/etc/sfa/root_ssh_key"
        scp_options = " -i %(identity)s " % locals()
        scp_options += "-o StrictHostKeyChecking=no " % locals()
        scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
                         locals()
        scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
                         locals()

        all_commands = [scp_key_command, scp_gid_command]

        for command in all_commands:
            (status, output) = commands.getstatusoutput(command)
            if status:
                raise Exception, output

        for filename in [key_filename, gid_filename]:
            os.unlink(filename)

        return 1