예제 #1
0
class MyProxyUtils(object):
    def __init__(self):
        self.config = config.read_config()
        self.cacertdir = os.path.expanduser("~/.esg/certificates")
        self.credsfile = os.path.expanduser("~/.esg/credentials.pem")
        self.myproxy = MyProxyClient(hostname=self.config['nodes']['idp_node'])
        self.myproxy._setCACertDir(self.cacertdir)

    def get_trustroots(self):
        # Get trust roots
        self.trustRoots = self.myproxy.getTrustRoots(
            self.config['account']['username'],
            self.config['account']['password'],
            writeToCACertDir=True,
            bootstrap=True)

    def get_credentials(self):
        # Get credentials (and trustroots)
        self.credentials = self.myproxy.logon(
            self.config['account']['username'],
            self.config['account']['password'])
        # Write Credentials
        with open(self.credsfile, 'w') as f:
            f.write(self.credentials[0] + self.credentials[1])
        os.chmod(self.credsfile, self.myproxy.PROXY_FILE_PERMISSIONS)

    def delete_credentials(self):
        # Delete credentials file
        if os.path.exists(self.credsfile):
            os.remove(self.credsfile)

    def delete_trustroots(self):
        # Delete trustroots and cacert directory
        if os.path.exists(self.cacertdir):
            shutil.rmtree(self.cacertdir)
예제 #2
0
class MyProxyUtils(object):
	def __init__(self):
		self.config = config.read_config()
		self.cacertdir = os.path.expanduser("~/.esg/certificates")
		self.credsfile = os.path.expanduser("~/.esg/credentials.pem")
		self.myproxy = MyProxyClient(hostname=self.config['nodes']['idp_node'])
		self.myproxy._setCACertDir(self.cacertdir)


	def get_trustroots(self):
		# Get trust roots
		self.trustRoots = self.myproxy.getTrustRoots(self.config['account']['username'],
							     	     self.config['account']['password'],
	         					     	     writeToCACertDir=True,
	  				       	             	     bootstrap=True)

	def get_credentials(self):
		# Get credentials (and trustroots)
                self.credentials = self.myproxy.logon(self.config['account']['username'],
                                                      	      self.config['account']['password'])
		# Write Credentials
		with open(self.credsfile, 'w') as f:
			f.write(self.credentials[0]+self.credentials[1])
            	os.chmod(self.credsfile, self.myproxy.PROXY_FILE_PERMISSIONS)
	

	def delete_credentials(self):
		# Delete credentials file
		if os.path.exists(self.credsfile):
			os.remove(self.credsfile)


	def delete_trustroots(self):
		# Delete trustroots and cacert directory
		if os.path.exists(self.cacertdir):
                        shutil.rmtree(self.cacertdir)
예제 #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.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']))
예제 #4
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'])