Esempio n. 1
0
  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 )
Esempio n. 2
0
    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)
Esempio n. 3
0
 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 )
Esempio n. 4
0
 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) )
Esempio n. 5
0
 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 )
Esempio n. 6
0
 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)
Esempio n. 7
0
 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 )
Esempio n. 8
0
 def getNumCertsInChain( self ):
   """
   Numbers of certificates in chain
   """
   if not self.__loadedChain:
     return S_ERROR( "No chain loaded" )
   return S_OK( len( self.__certList ) )
Esempio n. 9
0
 def getCertList( self ):
   """
   Get the cert list
   """
   if not self.__loadedChain:
     return S_ERROR( "No chain loaded" )
   return S_OK( self.__certList )
Esempio n. 10
0
 def getPKeyObj( self ):
   """
   Get the pkey obj
   """
   if not self.__loadedPKey:
     return S_ERROR( "No pkey loaded" )
   return S_OK( self.__keyObj )
Esempio n. 11
0
 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() )
Esempio n. 12
0
 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)
Esempio n. 13
0
 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))
Esempio n. 14
0
 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 ) )
Esempio n. 15
0
 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 ] ) )
Esempio n. 16
0
 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() )
Esempio n. 17
0
 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() )
Esempio n. 18
0
 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() )
Esempio n. 19
0
 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() )
Esempio n. 20
0
 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() )
Esempio n. 21
0
 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() )
Esempio n. 22
0
 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() )
Esempio n. 23
0
 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() )
Esempio n. 24
0
 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 ) )
Esempio n. 25
0
 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) )
Esempio n. 26
0
 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 )
Esempio n. 27
0
 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) )
Esempio n. 28
0
 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 )
Esempio n. 29
0
 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) )
Esempio n. 30
0
 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 ] ) )