def remove_credential(JObject): # username = JObject['watts_userid'] username = JObject['cred_state'] ConfParams = JObject['conf_params'] # MYPROXY_SERVER_PWD = ConfParams['myproxy_server_pwd'] MYPROXY_CERT = ConfParams['myproxy_cert'] MYPROXY_KEY = ConfParams['myproxy_key'] MYPROXY_SERVER = ConfParams['myproxy_server'] MYPROXY_SERVER_DN = ConfParams['myproxy_server_dn'] REMOVE_CERTIFICATE = bool(ConfParams['remove_certificate']) 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") # check if credential exists if REMOVE_CERTIFICATE: info = myproxy_clnt.info(username, sslCertFile = MYPROXY_CERT, sslKeyFile = MYPROXY_KEY) # time.sleep(3) if info[0]: myproxy_clnt.destroy(username, sslCertFile=MYPROXY_CERT, sslKeyFile=MYPROXY_KEY) return json.dumps({'result': 'ok'})
def get_slcs_token(context, request): originURL = request.POST['url'] proxy_username = request.POST['myproxy_username'] proxy_password = request.POST['myproxy_password'] c = MyProxyClient(hostname='myproxy2.arcs.org.au', port= 7512, serverDN='/C=AU/O=APACGrid/OU=VPAC/CN=myproxy2.arcs.org.au') success, err, field = c.info(proxy_username, userCertFile=CERTIFICATE, userKeyFile=KEY, userPassphrase=lambda *a: '') '''
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']))
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'])
def get_credential(JObject): username = JObject['watts_userid'] AddLogins = JObject['additional_logins'] 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'] Provider = ConfParams['rcauth_op_entry'] if not MYPROXY_SERVER_DN: logging.info('this is the constructor:') logging.info('hostname: %s' % MYPROXY_SERVER) 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") # check if credential exists logging.info('this is the info call:') logging.info('username: %s' % username) logging.info('sslCertFile: %s' % MYPROXY_CERT) logging.info('sslKeyFile: %s' % MYPROXY_KEY) info = myproxy_clnt.info(username, sslCertFile = MYPROXY_CERT, sslKeyFile = MYPROXY_KEY) logging.info('Just got this info from myproxy: "%s"' % str(info)) if info[0] == True and (info[2]['CRED_END_TIME'] <= int(time.time() + 12*60*60)): result = myproxy_clnt.destroy(username, sslCertFile = MYPROXY_CERT, sslKeyFile = MYPROXY_KEY) Msg ='Your certificate has expired, therefore it was removed. '+\ 'You will be redirected to login and verify your '+\ 'identity with RCauth to obtain a new one.' return json.dumps({'result':'oidc_login', 'provider': Provider, 'msg':Msg}) if info[0] == False and len(AddLogins) == 0: Msg ='Currently, we do not have a valid certificate for you. '+\ 'To obtain it, you will be redirected to login and verify your identity with RCauth.' return json.dumps({'result':'oidc_login', 'provider': Provider, 'msg':Msg}) if info[0] == False and len(AddLogins) != 0: try: req_and_store_cert(JObject) except Exception as E: UserMsg = 'Please logout and login again to request a new certificate from RCauth' logging.info = 'Request and store certificate failed with "%s"'%str(E) LogMsg = 'Request and store certificate failed with "%s"'%str(E) raise return json.dumps({'result':'error', 'user_msg':UserMsg, 'log_msg':LogMsg}) MYPROXY_SERVER_PWD = get_secret_from_passwordd(MYPROXY_SERVER_PWD_KEY_ID) logging.info ("calling 'myproxy.get'") result = myproxy_clnt.get(username=username, passphrase=MYPROXY_SERVER_PWD, lifetime = PROXY_LIFETIME, sslCertFile = MYPROXY_CERT, sslKeyFile = MYPROXY_KEY) # join all creds in a single file full_credential = ''.join([s for s in result]) Credential = [{'name':'Proxy certificate', 'type':'textfile', 'value':full_credential, 'rows':30, 'cols':64 , 'save_as': 'x509up_u1000'}] return json.dumps({'result':'ok', 'credential': Credential, 'state': username})
from arcs.gsi.certificate import Certificate certFile = open('cert.pem', 'r') keyFile = open('cert.key', 'r') certString = certFile.read() keyString = keyFile.read() print certString print keyString certificate = Certificate(str(certString), str(keyString)) #certificate.add_extension({'name' : 'Proxy Cert Info', 'critical' : 1, 'value' : 'Path Length Constraint: infinite, Policy Language: Inherit all'}) #print certificate c = MyProxyClient(hostname='myproxy2.arcs.org.au', port= 7512, serverDN='/C=AU/O=APACGrid/OU=VPAC/CN=myproxy2.arcs.org.au') #c = MyProxyClient(hostname='myproxydev.arcs.org.au', serverDN='/C=AU/O=APACGrid/OU=VPAC/CN=myproxydev.arcs.org.au') #c.put('testProxy', 'pa55w0rd', certificate, certificate.get_key()._key, \ #lambda *a: '', ownerCertFile=certificate, ownerKeyFile=certificate.get_key()._key, ownerPassphraseCallback=lambda *a: '', \ #retrievers='*') #print "Trying to put:" #print certificate.get_key() #c.put('testuser50', 'askldasdhqwod', certificate, certificate.get_key()._key, \ # lambda *a: '', retrievers='*') #print "Got here" success, err, field = c.info('asdasdas') if success: print "IT WORKED" else: print ":("