Exemplo n.º 1
0
class CredentialVerifier(object):
    """Utilities to verify signed credentials from a given set of 
    root certificates. Will compare target and source URNs, and privileges.
    See verify and verify_from_strings methods in particular."""

    CATEDCERTSFNAME = 'CATedCACerts.pem'

    # root_cert_fileordir is a trusted root cert file or directory of
    # trusted roots for verifying credentials
    def __init__(self, root_cert_fileordir):
        if root_cert_fileordir is None:
            raise Exception("Missing Root certs argument")
        elif os.path.isdir(root_cert_fileordir):
            files = os.listdir(root_cert_fileordir)
            self.root_cert_files = []
            for file in files:
                # FIXME: exclude files that aren't cert files?
                #print file == CredentialVerifier.CATEDCERTSFNAME
                if file == CredentialVerifier.CATEDCERTSFNAME:
                    continue
                self.root_cert_files.append(os.path.expanduser(os.path.join(root_cert_fileordir, file)))
         
            #self.root_cert_files = [root_cert_fileordir]
        else:
            raise Exception("Couldn't find Root certs in %s" % root_cert_fileordir)


    @classmethod
    def getCAsFileFromDir(cls, caCerts):
        '''Take a directory of CA certificates and concatenate them into a single
        file suitable for use by the Python SSL library to validate client 
        credentials. Existing file is replaced.'''
        if caCerts is None:
            raise Exception ('Missing caCerts argument')
        if os.path.isfile(os.path.expanduser(caCerts)):
            return caCerts
        if not os.path.isdir(os.path.expanduser(caCerts)):
            raise Exception ('caCerts arg Not a file or a dir: %s' % caCerts)

      

        # Now we have a dir of caCerts files
        # For each file in the dir (isfile), concatenate them into a new file
        comboFullPath = os.path.join(caCerts, CredentialVerifier.CATEDCERTSFNAME)

        caFiles = os.listdir(caCerts)
        #logger.debug('Got %d potential caCert files in the dir', len(caFiles))

        outfile = open(comboFullPath, "w")
        okFileCount = 0
        for filename in caFiles:
            filepath = os.path.join(caCerts, filename)
            # Confirm it's a CA file?
            #        if not file.endswith('.pem'):
            #            continue
            if not os.path.isfile(os.path.expanduser(filepath)):

                continue
            if filename == CredentialVerifier.CATEDCERTSFNAME:
                # logger.debug('Skipping previous cated certs file')
                continue
            okFileCount += 1

            certfile = open(filepath)
            for line in certfile:
                outfile.write(line)
            certfile.close()
        outfile.close()
        if okFileCount == 0:
            sys.exit('Found NO trusted certs in %s!' %  caCerts)

        return comboFullPath

    def verify_from_strings(self, gid_string, cred_strings, target_urn,
                            privileges, options=None):

        '''Create Credential and GID objects from the given strings,
        and then verify the GID has the right privileges according 
        to the given credentials on the given target.'''
        def make_cred(cred_string):
            credO = None
            try:
                credO = CredentialFactory.createCred(credString=cred_string)
            except Exception, e:
                print e
            return credO

        root_certs = \
            [Certificate(filename=root_cert_file) \
                 for root_cert_file in self.root_cert_files]

        caller_gid = gid.GID(string=gid_string)

        # Potentially, change gid_string to be the cert of the actual user 
        # if this is a 'speaks-for' invocation
        speaksfor_gid = \
            determine_speaks_for(None, \
            cred_strings, # May include ABAC speaks_for credential
            caller_gid, # Caller cert (may be the tool 'speaking for' user)
            options, # May include 'geni_speaking_for' option with user URN
            root_certs
            )
        if caller_gid.get_subject() != speaksfor_gid.get_subject():
            speaksfor_urn = speaksfor_gid.get_urn()
            caller_gid = speaksfor_gid


        # Remove the abac credentials
        cred_strings = [cred_string for cred_string in cred_strings \
                            if CredentialFactory.getType(cred_string) == cred.Credential.SFA_CREDENTIAL_TYPE]

        return self.verify(caller_gid,
                           map(make_cred, cred_strings),
                           target_urn,
                           privileges)
Exemplo n.º 2
0
        else:
            print "Usage: --create cred_file " + \
                "--user_cert_file user_cert_file" + \
                " --user_key_file user_key_file --ma_cert_file ma_cert_file"
        sys.exit()

    user_urn = options.user_urn

    # Get list of trusted rootcerts
    if options.cred_file and not options.trusted_roots_directory:
        sys.exit(
            "Must supply --trusted_roots_directory to validate a credential")

    trusted_roots_directory = options.trusted_roots_directory
    trusted_roots = \
        [Certificate(filename=os.path.join(trusted_roots_directory, file)) \
             for file in os.listdir(trusted_roots_directory) \
             if file.endswith('.pem') and file != 'CATedCACerts.pem']

    cred = open(options.cred_file).read()

    creds = [{
        'geni_type': ABACCredential.ABAC_CREDENTIAL_TYPE,
        'geni_value': cred,
        'geni_version': '1'
    }]
    gid = determine_speaks_for(None, creds, tool_gid, \
                                   {'geni_speaking_for' : user_urn}, \
                                   trusted_roots)

    print 'SPEAKS_FOR = %s' % (gid != tool_gid)