def getVOMSProxyInfo( self, proxy, option = False ): """ Returns information about a proxy certificate (both grid and voms). Available information is: 1. Full (grid)voms-proxy-info output 2. Proxy Certificate Timeleft in seconds (the output is an int) 3. DN 4. voms group (if any) @type proxy_file: a string @param proxy_file: the proxy certificate location. @type option: a string @param option: None is the default value. Other option available are: - timeleft - actimeleft - identity - fqan - all @rtype: tuple @return: status, output, error, pyerror. """ validOptions = ['actimeleft', 'timeleft', 'identity', 'fqan', 'all'] if option: if option not in validOptions: S_ERROR( 'Non valid option %s' % option ) retVal = FileSec.multiProxyArgument( proxy ) if not retVal[ 'OK' ]: return retVal proxyDict = retVal[ 'Value' ] chain = proxyDict[ 'chain' ] proxyLocation = proxyDict[ 'file' ] cmd = 'voms-proxy-info -dont-verify-ac -file %s' % proxyLocation if option: cmd += ' -%s' % option result = shellCall( self._secCmdTimeout, cmd ) if proxyDict[ 'tempFile' ]: self._unlinkFiles( proxyLocation ) if not result['OK']: return S_ERROR( 'Failed to call voms-proxy-info' ) status, output, error = result['Value'] # FIXME: if the local copy of the voms server certificate is not up to date the command returns 0. # the stdout needs to be parsed. if status: if error.find( 'VOMS extension not found' ) == -1 and \ not error.find( 'WARNING: Unable to verify signature! Server certificate possibly not installed.' ) == 0: return S_ERROR( 'Failed to get proxy info. Command: %s; StdOut: %s; StdErr: %s' % ( cmd, output, error ) ) if option == 'fqan': if output: output = output.split( '/Role' )[0] else: output = '/lhcb' return S_OK( output )
def uploadProxy(self, proxy=False, useDNAsUserName=False): """ Upload a proxy to myproxy service. proxy param can be: : Default -> use current proxy : string -> upload file specified as proxy : X509Chain -> use chain """ retVal = FileSec.multiProxyArgument(proxy) if not retVal['OK']: return retVal proxyDict = retVal['Value'] chain = proxyDict['chain'] proxyLocation = proxyDict['file'] #timeLeft = int( chain.getRemainingSecs()[ 'Value' ] / 3600 ) cmdArgs = ['-n'] cmdArgs.append('-s "%s"' % self._secServer) #cmdArgs.append( '-c "%s"' % ( timeLeft - 1 ) ) #cmdArgs.append( '-t "%s"' % self._secMaxProxyHours ) cmdArgs.append('-C "%s"' % proxyLocation) cmdArgs.append('-y "%s"' % proxyLocation) cmdArgs.append(' -n -R wms-enmr.cerm.unifi.it ') #cmdArgs.append( ' -n -R prod-wms-01.pd.infn.it ') if useDNAsUserName: cmdArgs.append('-d') else: retVal = self._getUsername(chain) if not retVal['OK']: FileSec.deleteMultiProxy(proxyDict) return retVal mpUsername = retVal['Value'] cmdArgs.append('-l "%s"' % mpUsername) mpEnv = self._getExternalCmdEnvironment() #Hack to upload properly mpEnv['GT_PROXY_MODE'] = 'old' os.environ['PATH'] = '/opt/globus/bin/' cmd = "/opt/globus/bin/myproxy-init %s" % " ".join(cmdArgs) result = shellCall(self._secCmdTimeout, cmd, env=mpEnv) FileSec.deleteMultiProxy(proxyDict) if not result['OK']: errMsg = "Call to myproxy-init failed: %s" % retVal['Message'] return S_ERROR(errMsg) status, output, error = result['Value'] # Clean-up files if status: errMsg = "Call to myproxy-init failed" extErrMsg = 'Command: %s; StdOut: %s; StdErr: %s' % (cmd, result, error) return S_ERROR("%s %s" % (errMsg, extErrMsg)) return S_OK(output)
def generateProxyRequest( self, bitStrength = 1024, limited = False ): """ Generate a proxy request Return S_OK( X509Request ) / S_ERROR """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) if not bitStrength: return S_ERROR( "bitStrength has to be greater than 1024 (%s)" % bitStrength ) x509 = self.getCertInChain(0)[ 'Value' ] return x509.generateProxyRequest( bitStrength, limited )
def generateChainFromRequestString( self, pemData, lifetime = 86400, requireLimited = False, diracGroup = False ): """ Generate a x509 chain from a request return S_OK( string ) / S_ERROR """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) if not self.__loadedPKey: return S_ERROR( "No pkey loaded" ) try: req = crypto.load_certificate_request( crypto.FILETYPE_PEM, pemData ) except Exception, e: return S_ERROR( "Can't load request data: %s" % str(e) )
def getDIRACGroup( self, ignoreDefault = False ): """ Get the dirac group if present """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) if not self.__isProxy: return S_ERROR( "Chain does not contain a valid proxy" ) #ADRI: Below will find first match of dirac group #for i in range( len( self.__certList ) -1, -1, -1 ): # retVal = self.getCertInChain( i )[ 'Value' ].getDIRACGroup() # if retVal[ 'OK' ] and 'Value' in retVal and retVal[ 'Value' ]: # return retVal return self.getCertInChain( self.__firstProxyStep )[ 'Value' ].getDIRACGroup( ignoreDefault = ignoreDefault )
def _getUsername(self, proxyChain): retVal = proxyChain.getCredentials() if not retVal['OK']: return retVal credDict = retVal['Value'] if not credDict['isProxy']: return S_ERROR("chain does not contain a proxy") if not credDict['validDN']: return S_ERROR("DN %s is not known in dirac" % credDict['subject']) if not credDict['validGroup']: return S_ERROR("Group %s is invalid for DN %s" % (credDict['group'], credDict['subject'])) mpUsername = "******" % (credDict['group'], credDict['username']) return S_OK(mpUsername)
def isLimitedProxy(self): """ Check wether this chain is a proxy """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) return S_OK( self.__isProxy and self.__isLimitedProxy )
def getNumCertsInChain( self ): """ Numbers of certificates in chain """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) return S_OK( len( self.__certList ) )
def getCertList( self ): """ Get the cert list """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) return S_OK( self.__certList )
def getPKeyObj( self ): """ Get the pkey obj """ if not self.__loadedPKey: return S_ERROR( "No pkey loaded" ) return S_OK( self.__keyObj )
def getPublicKey(self): """ Get the public key of the certificate """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_pubkey() )
def _generateTemporalFile(self): try: fd, filename = tempfile.mkstemp() os.close(fd) except IOError: return S_ERROR('Failed to create temporary file') return S_OK(filename)
def project_self_creation(self, tipology): '''Create a project and a calculation without user intervention project name: new_project_[seconds since 1/1/1970] ''' owner = Session.query(Users).get(session['REMOTE_USER']) project = u'new_project_%s' % str(time.time()).split('.')[0] # Create the directory structure on the filesystem pdir = os.path.join(config['app_conf']['working_dir'], owner.home) if os.path.isdir(pdir): pdir = os.path.join(pdir, project, tipology) try: os.makedirs(pdir) # Project creation p = Projects() p.name = project p.creation_date = datetime.now() p.owner = owner Session.add(p) Session.commit() return S_OK(p.id) except IOError, (errno, strerror): return S_ERROR( "I/O Error: %s %s" % (pname, strerror))
def dumpPKeyToString( self ): """ Dump key to string """ if not self.__loadedPKey: return S_ERROR( "No chain loaded" ) return S_OK( crypto.dump_privatekey( crypto.FILETYPE_PEM, self.__keyObj ) )
def getCertInChain( self, certPos = 0 ): """ Get a certificate in the chain """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) return S_OK( X509Certificate( self.__certList[ certPos ] ) )
def getSerialNumber(self): """ Get certificate serial number Return: S_OK( serial )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_serial_number() )
def getIssuerNameObject(self): """ Get issuer name object Return: S_OK( X509Name )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_issuer() )
def getNotAfterDate( self ): """ Get not after date of a certificate Return: S_OK( datetime )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_not_after() )
def getIssuerDN( self ): """ Get issuer DN Return: S_OK( string )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_issuer().one_line() )
def getSubjectNameObject(self): """ Get subject name object Return: S_OK( X509Name )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_subject() )
def getSubjectDN( self ): """ Get subject DN Return: S_OK( string )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_subject().one_line() )
def getNotBeforeDate( self ): """ Get not before date of a certificate Return: S_OK( datetime )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.get_not_before() )
def hasExpired( self ): """ Check if a certificate file/proxy is still valid Return: S_OK( True/False )/S_ERROR """ if not self.__valid: return S_ERROR( "No certificate loaded" ) return S_OK( self.__certObj.has_expired() )
def getRemainingSecs( self ): """ Get remaining lifetime in secs """ if not self.__valid: return S_ERROR( "No certificate loaded" ) notAfter = self.__certObj.get_not_after() remaining = notAfter - Time.dateTime() return S_OK( max( 0, remaining.days * 86400 + remaining.seconds ) )
def loadFromString( self, pemData ): """ Load a x509 cert from a string containing the pem data Return : S_OK / S_ERROR """ try: self.__certObj = GSI.crypto.load_certificate( GSI.crypto.FILETYPE_PEM, pemData ) except Exception, e: return S_ERROR( "Can't load pem data: %s" % str(e) )
def dumpChainToString( self ): """ Dump only cert chain to string """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) buffer = '' for i in range( len( self.__certList ) ): buffer += crypto.dump_certificate( crypto.FILETYPE_PEM, self.__certList[1] ) return S_OK( buffer )
def loadKeyFromString( self, pemData, password = False ): """ Load a xPKey from a string containing the pem data Return : S_OK / S_ERROR """ self.__loadedPKey = False try: self.__keyObj = crypto.load_privatekey( crypto.FILETYPE_PEM, pemData, password ) except Exception, e: return S_ERROR( "Can't load key file: %s (Probably bad pass phrase?)" % str(e) )
def hasExpired( self ): """ Is any of the elements in the chain expired? """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) for iC in range( len( self.__certList )-1, -1, -1 ): if self.__certList[iC].has_expired(): return S_OK( True ) return S_OK( False )
def loadChainFromString( self, pemData ): """ Load a x509 cert from a string containing the pem data Return : S_OK / S_ERROR """ self.__loadedChain = False try: self.__certList = crypto.load_certificate_chain( crypto.FILETYPE_PEM, pemData ) except Exception, e: return S_ERROR( "Can't load pem data: %s" % str(e) )
def getIssuerCert( self ): """ Get a issuer cert in the chain """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) if self.__isProxy: return S_OK( X509Certificate( self.__certList[ self.__firstProxyStep + 1 ] ) ) else: return S_OK( X509Certificate( self.__certList[ -1 ] ) )