示例#1
0
文件: sfi.py 项目: planetlab/sfa
def save_records_to_file(filename, recordList, format="xml"):
    if format == "xml":
        index = 0
        for record in recordList:
            if index > 0:
                save_record_to_file(filename + "." + str(index), record)
            else:
                save_record_to_file(filename, record)
            index = index + 1
    elif format == "xmllist":
        f = open(filename, "w")
        f.write("<recordlist>\n")
        for record in recordList:
            record = SfaRecord(dict=record)
            f.write('<record hrn="' + record.get_name() + '" type="' + record.get_type() + '" />\n')
        f.write("</recordlist>\n")
        f.close()
    elif format == "hrnlist":
        f = open(filename, "w")
        for record in recordList:
            record = SfaRecord(dict=record)
            f.write(record.get_name() + "\n")
        f.close()
    else:
        # this should never happen
        print "unknown output format", format
示例#2
0
    def call(self, cert, xrn, type):
        """
        GetSelfCredential a degenerate version of GetCredential used by a client
        to get his initial credential when de doesnt have one. This is the same as
        GetCredential(..., cred = None, ...)

        The registry ensures that the client is the principal that is named by
        (type, name) by comparing the public key in the record's  GID to the
        private key used to encrypt the client side of the HTTPS connection. Thus
        it is impossible for one principal to retrieve another principal's
        credential without having the appropriate private key.

        @param type type of object (user | slice | sa | ma | node)
        @param hrn human readable name of authority to list
        @return string representation of a credential object
        """
        if type:
            hrn = urn_to_hrn(xrn)[0]
        else:
            hrn, type = urn_to_hrn(xrn) 
        self.api.auth.verify_object_belongs_to_me(hrn)

        origin_hrn = Certificate(string=cert).get_subject()
        self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, hrn, self.name))
        
        manager = self.api.get_interface_manager()
 
        # authenticate the gid
        records = manager.resolve(self.api, xrn, type)
        if not records:
            raise RecordNotFound(hrn)
        record = SfaRecord(dict=records[0])
        gid = record.get_gid_object()
        gid_str = gid.save_to_string(save_parents=True)
        self.api.auth.authenticateGid(gid_str, [cert, type, hrn])
        # authenticate the certificate against the gid in the db
        certificate = Certificate(string=cert)
        if not certificate.is_pubkey(gid.get_pubkey()):
            for (obj,name) in [ (certificate,"CERT"), (gid,"GID"), ]:
                self.api.logger.debug("ConnectionKeyGIDMismatch, %s pubkey: %s"%(name,obj.get_pubkey().get_pubkey_string()))
                self.api.logger.debug("ConnectionKeyGIDMismatch, %s dump: %s"%(name,obj.dump_string()))
                if hasattr (obj,'filename'): 
                    self.api.logger.debug("ConnectionKeyGIDMismatch, %s filename: %s"%(name,obj.filename))
            raise ConnectionKeyGIDMismatch(gid.get_subject())
        
        return manager.get_credential(self.api, xrn, type, is_self=True)
示例#3
0
def register(api, record):

    hrn, type = record['hrn'], record['type']
    urn = hrn_to_urn(hrn,type)
    # validate the type
    if type not in ['authority', 'slice', 'node', 'user']:
        raise UnknownSfaType(type) 
    
    # check if record already exists
    table = SfaTable()
    existing_records = table.find({'type': type, 'hrn': hrn})
    if existing_records:
        raise ExistingRecord(hrn)
       
    record = SfaRecord(dict = record)
    record['authority'] = get_authority(record['hrn'])
    type = record['type']
    hrn = record['hrn']
    auth_info = api.auth.get_auth_info(record['authority'])
    pub_key = None
    # make sure record has a gid
    if 'gid' not in record:
        uuid = create_uuid()
        pkey = Keypair(create=True)
        if 'key' in record and record['key']:
            if isinstance(record['key'], types.ListType):
                pub_key = record['key'][0]
            else:
                pub_key = record['key']
            pkey = convert_public_key(pub_key)

        gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
        gid = gid_object.save_to_string(save_parents=True)
        record['gid'] = gid
        record.set_gid(gid)

    if type in ["authority"]:
        # update the tree
        if not api.auth.hierarchy.auth_exists(hrn):
            api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))

        # get the GID from the newly created authority
        gid = auth_info.get_gid_object()
        record.set_gid(gid.save_to_string(save_parents=True))
        pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
        sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
        if not sites:
            pointer = api.plshell.AddSite(api.plauth, pl_record)
        else:
            pointer = sites[0]['site_id']

        record.set_pointer(pointer)
        record['pointer'] = pointer

    elif (type == "slice"):
        acceptable_fields=['url', 'instantiation', 'name', 'description']
        pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
        for key in pl_record.keys():
            if key not in acceptable_fields:
                pl_record.pop(key)
        slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
        if not slices:
             pointer = api.plshell.AddSlice(api.plauth, pl_record)
        else:
             pointer = slices[0]['slice_id']
        record.set_pointer(pointer)
        record['pointer'] = pointer

    elif  (type == "user"):
        persons = api.plshell.GetPersons(api.plauth, [record['email']])
        if not persons:
            pointer = api.plshell.AddPerson(api.plauth, dict(record))
        else:
            pointer = persons[0]['person_id']

        if 'enabled' in record and record['enabled']:
            api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
        # add this persons to the site only if he is being added for the first
        # time by sfa and doesont already exist in plc
        if not persons or not persons[0]['site_ids']:
            login_base = get_leaf(record['authority'])
            api.plshell.AddPersonToSite(api.plauth, pointer, login_base)

        # What roles should this user have?
        api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
        # Add the user's key
        if pub_key:
            api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})

    elif (type == "node"):
        pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
        login_base = hrn_to_pl_login_base(record['authority'])
        nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
        if not nodes:
            pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
        else:
            pointer = nodes[0]['node_id']

    record['pointer'] = pointer
    record.set_pointer(pointer)
    record_id = table.insert(record)
    record['record_id'] = record_id

    # update membership for researchers, pis, owners, operators
    api.update_membership(None, record)

    return record.get_gid_object().save_to_string(save_parents=True)