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 ] ) )
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 hasVOMSExtensions(self): """ Has voms extensions """ if not self.__valid: return S_ERROR( "No certificate loaded" ) extList = self.__certObj.get_extensions() for ext in extList: if ext.get_sn() == "vomsExtensions": return S_OK( True ) return S_OK( False )
def isVOMS(self): """ Check wether this chain is a proxy """ retVal = self.isProxy() if not retVal[ 'OK' ] or not retVal[ 'Value' ]: return retVal for i in range( len( self.__certList ) ): cert = self.getCertInChain( i )[ 'Value' ] if cert.hasVOMSExtensions()[ 'Value' ]: return S_OK( True ) return S_OK( False )
def getNotAfterDate( self ): """ Get the smallest not after date """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) notAfter = self.__certList[0].get_not_after() for iC in range( len( self.__certList )-1, -1, -1 ): stepNotAfter = self.__certList[iC].get_not_after() if self.__certList[iC].has_expired(): return S_OK( stepNotAfter ) if notAfter > stepNotAfter: notAfter = stepNotAfter return S_OK( notAfter )
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 isValidProxy( self ): """ Check wether this chain is a valid proxy checks if its a proxy checks if its expired """ if not self.__loadedChain: return S_ERROR( "No chain loaded" ) retVal = S_OK( False ) if not self.__isProxy: retVal[ 'Message' ] = "Chain is not a proxy" elif self.hasExpired()['Value']: retVal[ 'Message' ] = "Chain has expired" if 'Message' in retVal: return retVal return S_OK( True )
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 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 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 _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 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 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 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 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 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 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 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 setChain( self, certList ): """ Set the chain Return : S_OK / S_ERROR """ self.__certList = certList self.__loadedChain = True return S_OK()
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 setPKey( self, pkeyObj ): """ Set the chain Return : S_OK / S_ERROR """ self.__keyObj = pkeyObj self.__loadedPKey = True return S_OK()
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 __executePythonFunction(self, function, writePipe, *stArgs, **stKeyArgs): try: os.write(writePipe, DEncode.encode(S_OK(function(*stArgs, **stKeyArgs)))) except OSError, v: if str(v) == '[Errno 32] Broken pipe': # the parent has died pass
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 )