Ejemplo n.º 1
0
def store_credential(JObject, usercert, userkey):
    username           = JObject['watts_userid']
    ConfParams         = JObject['conf_params']
    prefix             = ConfParams['prefix']
    username           = prefix + '_' + username
    MYPROXY_SERVER_PWD_KEY_ID = ConfParams['myproxy_server_pwd_key_id']
    MYPROXY_CERT       = ConfParams['myproxy_cert']
    MYPROXY_KEY        = ConfParams['myproxy_key']
    PROXY_LIFETIME     = int(ConfParams['proxy_lifetime'])
    MYPROXY_SERVER     = ConfParams['myproxy_server']
    MYPROXY_SERVER_DN  = ConfParams['myproxy_server_dn']
    if not MYPROXY_SERVER_DN:
        myproxy_clnt       = MyProxyClient(hostname = MYPROXY_SERVER, CACertDir="/etc/grid-security/certificates")
    else:
        myproxy_clnt       = MyProxyClient(hostname = MYPROXY_SERVER, serverDN = MYPROXY_SERVER_DN, CACertDir="/etc/grid-security/certificates")
    MYPROXY_SERVER_PWD = get_secret_from_passwordd(MYPROXY_SERVER_PWD_KEY_ID)
    myproxy_clnt.store(username              = username,
                       passphrase            = MYPROXY_SERVER_PWD,
                       certFile              = usercert,
                       keyFile               = userkey,
                       sslCertFile           = MYPROXY_CERT,
                       sslKeyFile            = MYPROXY_KEY,
                       sslKeyFilePhassphrase = None,
                       lifetime              = PROXY_LIFETIME,
                       force                 = True)
    return 0
Ejemplo n.º 2
0
class MyProxyClientLiveTestCase(_MyProxyClientTestCase):
    '''Tests require a connection to a real MyProxy service running on a host.

    The server must be set up as a credential repository - i.e. able to receive
    and store credentials
    '''
    CONFIG_FILENAME = "myProxyClientTest.cfg"

    def setUp(self):

        super(MyProxyClientLiveTestCase, self).setUp()

        configParser = CaseSensitiveConfigParser()
        configFilePath = path.join(os.environ['MYPROXYCLIENT_UNITTEST_DIR'],
                                   MyProxyClientLiveTestCase.CONFIG_FILENAME)
        configParser.read(configFilePath)

        self.cfg = {}
        for section in configParser.sections():
            self.cfg[section] = dict(configParser.items(section))

        configFilePath = path.expandvars(self.cfg['setUp']['cfgFilePath'])

        self.clnt = MyProxyClient(cfgFilePath=configFilePath)

        # Get trust roots bootstrapping trust ready for test
        self.trustRoots = self.clnt.getTrustRoots(writeToCACertDir=True,
                                                  bootstrap=True)

        # Keep a copy of files stored ready for tearDown tidy up
        self.trustRootFiles = []

        dirContents = os.listdir(self.clnt.caCertDir)
        for fileName in self.trustRoots:
            self.assertTrue(fileName in dirContents)
            file_path = os.path.join(self.clnt.caCertDir, fileName)
            self.trustRootFiles.append(file_path)

    def tearDown(self):
        """Clear up CA certs retrieved in test01GetTrustRoots call ready for
        next run of these unit tests
        """
        self.trustRoots = None
        self._deleteTrustRootFiles()

    def _deleteTrustRootFiles(self):
        """Helper method clears up CA certs in trust roots directory set from
        previous call to test01GetTrustRoots()
        """
        for fileName in self.trustRootFiles:
            os.remove(fileName)

    def test01GetTrustRoots(self):
        # Test output from getTrustRoots call made in setUp
        self.assertTrue(self.trustRoots)
        self.assertTrue(isinstance(self.trustRoots, dict))
        self.assertTrue(len(self.trustRoots) > 0)
        for fileName, fileContents in list(self.trustRoots.items()):
            if fileName.endswith('.0'):
                # test parsing certificate
                cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                               fileContents)
                self.assertTrue(cert)
                self.assertTrue(isinstance(cert, crypto.X509))
                subj = cert.get_subject()
                self.assertTrue(subj)
                print(("Trust root certificate retrieved with DN=%s" % subj))

    def test02Store(self):
        # Test get trust root to bootstrap trust
        self.test01GetTrustRoots()

        # upload X509 cert and private key to repository
        thisSection = self.cfg['test02Store']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("\ntest02Store credential pass-phrase: ")

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest02Store credential owner "
                                           "pass-phrase: ")

        certFile = path.expandvars(thisSection['ownerCertFile'])
        keyFile = path.expandvars(thisSection['ownerKeyFile'])
        sslCertFile = path.expandvars(thisSection['sslCertFile'])
        sslKeyFile = path.expandvars(thisSection['sslKeyFile'])

        self.clnt.store(thisSection['username'],
                        passphrase,
                        certFile,
                        keyFile,
                        sslCertFile=sslCertFile,
                        sslKeyFile=sslKeyFile,
                        sslKeyFilePassphrase=sslKeyFilePassphrase,
                        force=False)
        print(("Store creds for user %s" % thisSection['username']))

    def test03GetDelegation(self):
        # retrieve proxy cert./private key
        thisSection = self.cfg['test03GetDelegation']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("\ntest03GetDelegation passphrase: ")

        proxyCertFile = path.expandvars(thisSection['proxyCertFileOut'])
        proxyKeyFile = path.expandvars(thisSection['proxyKeyFileOut'])

        creds = self.clnt.getDelegation(thisSection['username'], passphrase)
        print("proxy credentials:")
        print(b''.join(creds))
        with open(proxyCertFile, 'wb') as proxy_cert_file:
            proxy_cert_file.write(creds[0] + b''.join(creds[2:]))

        with open(proxyKeyFile, 'wb') as proxy_key_file:
            proxy_key_file.write(creds[1])

    def test04Info(self):
        # Retrieve information about a given credential
        thisSection = self.cfg['test04Info']

        # sslKeyFilePassphrase can be omitted from the congif file in which case
        # the get call below would return None
        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest04Info owner credentials "
                                           "passphrase: ")

        credExists, errorTxt, fields = self.clnt.info(
            thisSection['username'],
            path.expandvars(thisSection['sslCertFile']),
            path.expandvars(thisSection['sslKeyFile']),
            sslKeyFilePassphrase=sslKeyFilePassphrase)
        print("test04Info... ")
        print("credExists: %s" % credExists)
        print("errorTxt: " + errorTxt)
        print("fields: %s" % fields)

    def test06ChangePassphrase(self):
        # change pass-phrase protecting a given credential
        thisSection = self.cfg['test06ChangePassphrase']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("test06ChangePassphrase - passphrase: ")

        newPassphrase = thisSection.get('newPassphrase')
        if newPassphrase is None:
            newPassphrase = getpass(
                "test06ChangePassphrase - new passphrase: ")

            confirmNewPassphrase = getpass("test06ChangePassphrase - confirm "
                                           "new passphrase: ")

            if newPassphrase != confirmNewPassphrase:
                self.fail("New and confirmed new password don't match")

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase') or \
                            passphrase

        self.clnt.changePassphrase(thisSection['username'],
                                   passphrase,
                                   newPassphrase,
                                   path.expandvars(thisSection['sslCertFile']),
                                   path.expandvars(thisSection['sslKeyFile']),
                                   sslKeyFilePassphrase=sslKeyFilePassphrase)
        print("Changed pass-phrase")

    def test05GetDelegationWithBootstrappedTrustRoots(self):
        # Get delegation call whilst simulataneously bootstrapping trust roots
        thisSection = self.cfg['test05GetDelegationWithBootstrappedTrustRoots']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass(
                "\n"
                "test05GetDelegationWithBootstrappedTrustRoots"
                "passphrase: ")

        # Ensure any previously set trust root files are removed
        self._deleteTrustRootFiles()

        creds = self.clnt.getDelegation(thisSection['username'],
                                        passphrase,
                                        bootstrap=True)
        print("proxy credentials:")
        print(b''.join(creds))

    def test07Destroy(self):
        # destroy credentials for a given user
        thisSection = self.cfg['test07Destroy']

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest07Destroy credential owner "
                                           "passphrase: ")

        self.clnt.destroy(
            thisSection['username'],
            sslCertFile=path.expandvars(thisSection['sslCertFile']),
            sslKeyFile=path.expandvars(thisSection['sslKeyFile']),
            sslKeyFilePassphrase=sslKeyFilePassphrase)
        print(("Destroy creds for user %s" % thisSection['username']))
Ejemplo n.º 3
0
class MyProxyClientLiveTestCase(_MyProxyClientTestCase):
    '''Tests require a connection to a real MyProxy service running on a host.

    The server must be set up as a credential repository - i.e. able to receive
    and store credentials
    '''
    CONFIG_FILENAME = "myProxyClientTest.cfg"


    def setUp(self):

        super(MyProxyClientLiveTestCase, self).setUp()

        configParser = CaseSensitiveConfigParser()
        configFilePath = path.join(os.environ['MYPROXYCLIENT_UNITTEST_DIR'],
                                   MyProxyClientLiveTestCase.CONFIG_FILENAME)
        configParser.read(configFilePath)

        self.cfg = {}
        for section in configParser.sections():
            self.cfg[section] = dict(configParser.items(section))

        configFilePath = path.expandvars(self.cfg['setUp']['cfgFilePath'])
        self.clnt = MyProxyClient(cfgFilePath=configFilePath)

        # Get trust roots bootstrapping trust ready for test
        self.trustRoots = self.clnt.getTrustRoots(writeToCACertDir=True,
                                                  bootstrap=True)

        # Keep a copy of files stored ready for tearDown tidy up
        self.trustRootFiles = []

        dirContents = os.listdir(self.clnt.caCertDir)
        for fileName in self.trustRoots:
            self.assert_(fileName in dirContents)
            file_path = os.path.join(self.clnt.caCertDir, fileName)
            self.trustRootFiles.append(file_path)

    def tearDown(self):
        """Clear up CA certs retrieved in test01GetTrustRoots call ready for
        next run of these unit tests
        """
        self.trustRoots = None
        self._deleteTrustRootFiles()

    def _deleteTrustRootFiles(self):
        """Helper method clears up CA certs in trust roots directory set from
        previous call to test01GetTrustRoots()
        """
        for fileName in self.trustRootFiles:
            os.remove(fileName)

    def test01GetTrustRoots(self):
        # Test output from getTrustRoots call made in setUp
        self.assert_(self.trustRoots)
        self.assert_(isinstance(self.trustRoots, dict))
        self.assert_(len(self.trustRoots) > 0)
        for fileName, fileContents in self.trustRoots.items():
            if fileName.endswith('.0'):
                # test parsing certificate
                cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                               fileContents)
                self.assert_(cert)
                self.assert_(isinstance(cert, crypto.X509))
                subj = cert.get_subject()
                self.assert_(subj)
                print("Trust root certificate retrieved with DN=%s" % subj)

    def test02Store(self):
        # Test get trust root to bootstrap trust
        self.test01GetTrustRoots()

        # upload X509 cert and private key to repository
        thisSection = self.cfg['test02Store']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("\ntest02Store credential pass-phrase: ")

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest02Store credential owner "
                                           "pass-phrase: ")

        certFile = path.expandvars(thisSection['ownerCertFile'])
        keyFile = path.expandvars(thisSection['ownerKeyFile'])
        sslCertFile = path.expandvars(thisSection['sslCertFile'])
        sslKeyFile = path.expandvars(thisSection['sslKeyFile'])

        self.clnt.store(thisSection['username'],
                        passphrase,
                        certFile,
                        keyFile,
                        sslCertFile=sslCertFile,
                        sslKeyFile=sslKeyFile,
                        sslKeyFilePassphrase=sslKeyFilePassphrase,
                        force=False)
        print("Store creds for user %s" % thisSection['username'])

    def test03GetDelegation(self):
        # retrieve proxy cert./private key
        thisSection = self.cfg['test03GetDelegation']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("\ntest03GetDelegation passphrase: ")

        proxyCertFile = path.expandvars(thisSection['proxyCertFileOut'])
        proxyKeyFile = path.expandvars(thisSection['proxyKeyFileOut'])

        creds = self.clnt.getDelegation(thisSection['username'], passphrase)
        print "proxy credentials:"
        print ''.join(creds)
        open(proxyCertFile, 'w').write(creds[0]+''.join(creds[2:]))
        open(proxyKeyFile, 'w').write(creds[1])

    def test04Info(self):
        # Retrieve information about a given credential
        thisSection = self.cfg['test04Info']

        # sslKeyFilePassphrase can be omitted from the congif file in which case
        # the get call below would return None
        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest04Info owner credentials "
                                           "passphrase: ")

        credExists, errorTxt, fields = self.clnt.info(
                                 thisSection['username'],
                                 path.expandvars(thisSection['sslCertFile']),
                                 path.expandvars(thisSection['sslKeyFile']),
                                 sslKeyFilePassphrase=sslKeyFilePassphrase)
        print "test04Info... "
        print "credExists: %s" % credExists
        print "errorTxt: " + errorTxt
        print "fields: %s" % fields

    def test06ChangePassphrase(self):
        # change pass-phrase protecting a given credential
        thisSection = self.cfg['test06ChangePassphrase']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("test06ChangePassphrase - passphrase: ")

        newPassphrase = thisSection.get('newPassphrase')
        if newPassphrase is None:
            newPassphrase = getpass("test06ChangePassphrase - new passphrase: ")

            confirmNewPassphrase = getpass("test06ChangePassphrase - confirm "
                                           "new passphrase: ")

            if newPassphrase != confirmNewPassphrase:
                self.fail("New and confirmed new password don't match")

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase') or \
                            passphrase

        self.clnt.changePassphrase(thisSection['username'],
                               passphrase,
                               newPassphrase,
                               path.expandvars(thisSection['sslCertFile']),
                               path.expandvars(thisSection['sslKeyFile']),
                               sslKeyFilePassphrase=sslKeyFilePassphrase)
        print("Changed pass-phrase")

    def test05GetDelegationWithBootstrappedTrustRoots(self):
        # Get delegation call whilst simulataneously bootstrapping trust roots
        thisSection = self.cfg['test05GetDelegationWithBootstrappedTrustRoots']

        passphrase = thisSection.get('passphrase')
        if passphrase is None:
            passphrase = getpass("\n"
                                 "test05GetDelegationWithBootstrappedTrustRoots"
                                 "passphrase: ")

        # Ensure any previously set trust root files are removed
        self._deleteTrustRootFiles()

        creds = self.clnt.getDelegation(thisSection['username'], passphrase,
                                        bootstrap=True)
        print "proxy credentials:"
        print ''.join(creds)

    def test07Destroy(self):
        # destroy credentials for a given user
        thisSection = self.cfg['test07Destroy']

        sslKeyFilePassphrase = thisSection.get('sslKeyFilePassphrase')
        if sslKeyFilePassphrase is None:
            sslKeyFilePassphrase = getpass("\ntest07Destroy credential owner "
                                           "passphrase: ")

        self.clnt.destroy(thisSection['username'],
                      sslCertFile=path.expandvars(thisSection['sslCertFile']),
                      sslKeyFile=path.expandvars(thisSection['sslKeyFile']),
                      sslKeyFilePassphrase=sslKeyFilePassphrase)
        print("Destroy creds for user %s" % thisSection['username'])