Ejemplo n.º 1
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 = File.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)
        if useDNAsUserName:
            cmdArgs.append('-d')
        else:
            retVal = self._getUsername(chain)
            if not retVal['OK']:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal['Value']
            cmdArgs.append('-l "%s"' % mpUsername)

        mpEnv = self._getExternalCmdEnvironment()
        #Hack to upload properly
        mpEnv['GT_PROXY_MODE'] = 'old'

        cmd = "myproxy-init %s" % " ".join(cmdArgs)
        result = shellCall(self._secCmdTimeout, cmd, env=mpEnv)

        File.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()
Ejemplo 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 = File.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)
        if useDNAsUserName:
            cmdArgs.append("-d")
        else:
            retVal = self._getUsername(chain)
            if not retVal["OK"]:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal["Value"]
            cmdArgs.append('-l "%s"' % mpUsername)

        mpEnv = self._getExternalCmdEnvironment()
        # Hack to upload properly
        mpEnv["GT_PROXY_MODE"] = "old"

        cmd = "myproxy-init %s" % " ".join(cmdArgs)
        result = shellCall(self._secCmdTimeout, cmd, env=mpEnv)

        File.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()
Ejemplo n.º 3
0
    def renewProxy(self,
                   proxyToBeRenewed=False,
                   minLifeTime=3600,
                   newProxyLifeTime=43200,
                   proxyToConnect=False):
        """
    Renew a proxy using the ProxyManager
    Arguments:
      proxyToBeRenewed : proxy to renew
      minLifeTime : if proxy life time is less than this, renew. Skip otherwise
      newProxyLifeTime : life time of new proxy
      proxyToConnect : proxy to use for connecting to the service
    """
        retVal = File.multiProxyArgument(proxyToBeRenewed)
        if not retVal['Value']:
            return retVal
        proxyToRenewDict = retVal['Value']

        secs = proxyToRenewDict['chain'].getRemainingSecs()['Value']
        if secs > minLifeTime:
            File.deleteMultiProxy(proxyToRenewDict)
            return S_OK()

        if not proxyToConnect:
            proxyToConnectDict = {'chain': False, 'tempFile': False}
        else:
            retVal = File.multiProxyArgument(proxyToConnect)
            if not retVal['Value']:
                File.deleteMultiProxy(proxyToRenewDict)
                return retVal
            proxyToConnectDict = retVal['Value']

        userDN = proxyToRenewDict['chain'].getIssuerCert(
        )['Value'].getSubjectDN()['Value']
        retVal = proxyToRenewDict['chain'].getDIRACGroup()
        if not retVal['OK']:
            File.deleteMultiProxy(proxyToRenewDict)
            File.deleteMultiProxy(proxyToConnectDict)
            return retVal
        userGroup = retVal['Value']
        limited = proxyToRenewDict['chain'].isLimitedProxy()['Value']

        voms = VOMS()
        retVal = voms.getVOMSAttributes(proxyToRenewDict['chain'])
        if not retVal['OK']:
            File.deleteMultiProxy(proxyToRenewDict)
            File.deleteMultiProxy(proxyToConnectDict)
            return retVal
        vomsAttrs = retVal['Value']
        if vomsAttrs:
            retVal = self.downloadVOMSProxy(
                userDN,
                userGroup,
                limited=limited,
                requiredTimeLeft=newProxyLifeTime,
                requiredVOMSAttribute=vomsAttrs[0],
                proxyToConnect=proxyToConnectDict['chain'])
        else:
            retVal = self.downloadProxy(
                userDN,
                userGroup,
                limited=limited,
                requiredTimeLeft=newProxyLifeTime,
                proxyToConnect=proxyToConnectDict['chain'])

        File.deleteMultiProxy(proxyToRenewDict)
        File.deleteMultiProxy(proxyToConnectDict)

        if not retVal['OK']:
            return retVal

        chain = retVal['Value']

        if not proxyToRenewDict['tempFile']:
            return chain.dumpAllToFile(proxyToRenewDict['file'])

        return S_OK(chain)
Ejemplo n.º 4
0
    def getDelegatedProxy(self,
                          proxyChain,
                          lifeTime=604800,
                          useDNAsUserName=False):
        """
      Get delegated proxy from MyProxy server
      return S_OK( X509Chain ) / S_ERROR
    """
        #TODO: Set the proxy coming in proxyString to be the proxy to use

        #Get myproxy username diracgroup:diracuser
        retVal = File.multiProxyArgument(proxyChain)
        if not retVal['OK']:
            return retVal
        proxyDict = retVal['Value']
        chain = proxyDict['chain']
        proxyLocation = proxyDict['file']

        retVal = self._generateTemporalFile()
        if not retVal['OK']:
            File.deleteMultiProxy(proxyDict)
            return retVal
        newProxyLocation = retVal['Value']

        # myproxy-get-delegation works only with environment variables
        cmdEnv = self._getExternalCmdEnvironment()
        if self._secRunningFromTrustedHost:
            cmdEnv['X509_USER_CERT'] = self._secCertLoc
            cmdEnv['X509_USER_KEY'] = self._secKeyLoc
            if 'X509_USER_PROXY' in cmdEnv:
                del cmdEnv['X509_USER_PROXY']
        else:
            cmdEnv['X509_USER_PROXY'] = proxyLocation

        cmdArgs = []
        cmdArgs.append("-s '%s'" % self._secServer)
        cmdArgs.append("-t '%s'" % (int(lifeTime / 3600)))
        cmdArgs.append("-a '%s'" % proxyLocation)
        cmdArgs.append("-o '%s'" % newProxyLocation)
        if useDNAsUserName:
            cmdArgs.append('-d')
        else:
            retVal = self._getUsername(chain)
            if not retVal['OK']:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal['Value']
            cmdArgs.append('-l "%s"' % mpUsername)

        cmd = "myproxy-logon %s" % " ".join(cmdArgs)
        gLogger.verbose("myproxy-logon command:\n%s" % cmd)

        result = shellCall(self._secCmdTimeout, cmd, env=cmdEnv)

        File.deleteMultiProxy(proxyDict)

        if not result['OK']:
            errMsg = "Call to myproxy-logon failed: %s" % result['Message']
            File.deleteMultiProxy(proxyDict)
            return S_ERROR(errMsg)

        status, output, error = result['Value']

        # Clean-up files
        if status:
            errMsg = "Call to myproxy-logon failed"
            extErrMsg = 'Command: %s; StdOut: %s; StdErr: %s' % (cmd, result,
                                                                 error)
            File.deleteMultiProxy(proxyDict)
            return S_ERROR("%s %s" % (errMsg, extErrMsg))

        chain = X509Chain()
        retVal = chain.loadProxyFromFile(newProxyLocation)
        if not retVal['OK']:
            File.deleteMultiProxy(proxyDict)
            return S_ERROR(
                "myproxy-logon failed when reading delegated file: %s" %
                retVal['Message'])

        File.deleteMultiProxy(proxyDict)
        return S_OK(chain)
Ejemplo n.º 5
0
    def getInfo(self, proxyChain, useDNAsUserName=False):
        """
      Get info from myproxy server
      return S_OK( { 'username' : myproxyusername,
                     'owner' : owner DN,
                     'timeLeft' : secs left } ) / S_ERROR
    """
        #TODO: Set the proxy coming in proxyString to be the proxy to use

        #Get myproxy username diracgroup:diracuser
        retVal = File.multiProxyArgument(proxyChain)
        if not retVal['OK']:
            return retVal
        proxyDict = retVal['Value']
        chain = proxyDict['chain']
        proxyLocation = proxyDict['file']

        # myproxy-get-delegation works only with environment variables
        cmdEnv = self._getExternalCmdEnvironment()
        if self._secRunningFromTrustedHost:
            cmdEnv['X509_USER_CERT'] = self._secCertLoc
            cmdEnv['X509_USER_KEY'] = self._secKeyLoc
            if 'X509_USER_PROXY' in cmdEnv:
                del cmdEnv['X509_USER_PROXY']
        else:
            cmdEnv['X509_USER_PROXY'] = proxyLocation

        cmdArgs = []
        cmdArgs.append("-s '%s'" % self._secServer)
        if useDNAsUserName:
            cmdArgs.append('-d')
        else:
            retVal = self._getUsername(chain)
            if not retVal['OK']:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal['Value']
            cmdArgs.append('-l "%s"' % mpUsername)

        cmd = "myproxy-info %s" % " ".join(cmdArgs)
        gLogger.verbose("myproxy-info command:\n%s" % cmd)

        result = shellCall(self._secCmdTimeout, cmd, env=cmdEnv)

        File.deleteMultiProxy(proxyDict)

        if not result['OK']:
            errMsg = "Call to myproxy-info failed: %s" % result['Message']
            File.deleteMultiProxy(proxyDict)
            return S_ERROR(errMsg)

        status, output, error = result['Value']

        # Clean-up files
        if status:
            errMsg = "Call to myproxy-info failed"
            extErrMsg = 'Command: %s; StdOut: %s; StdErr: %s' % (cmd, result,
                                                                 error)
            return S_ERROR("%s %s" % (errMsg, extErrMsg))

        infoDict = {}
        usernameRE = re.compile("username\s*:\s*(\S*)")
        ownerRE = re.compile("owner\s*:\s*(\S*)")
        timeLeftRE = re.compile("timeleft\s*:\s*(\S*)")
        for line in List.fromChar(output, "\n"):
            match = usernameRE.search(line)
            if match:
                infoDict['username'] = match.group(1)
            match = ownerRE.search(line)
            if match:
                infoDict['owner'] = match.group(1)
            match = timeLeftRE.search(line)
            if match:
                try:
                    fields = List.fromChar(match.group(1), ":")
                    fields.reverse()
                    secsLeft = 0
                    for iP in range(len(fields)):
                        if iP == 0:
                            secsLeft += int(fields[iP])
                        elif iP == 1:
                            secsLeft += int(fields[iP]) * 60
                        elif iP == 2:
                            secsLeft += int(fields[iP]) * 3600
                    infoDict['timeLeft'] = secsLeft
                except Exception, x:
                    print x
Ejemplo n.º 6
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: a string
        @param proxy: 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 = File.multiProxyArgument( proxy )
    if not retVal[ 'OK' ]:
      return retVal
    proxyDict = retVal[ 'Value' ]

    try:
      res = proxyDict[ 'chain' ].getVOMSData()
      if not res[ 'OK' ]:
        return res

      data = res[ 'Value' ]

      if option == 'actimeleft':
        now = Time.dateTime()
        left = data[ 'notAfter' ] - now
        return S_OK( "%d\n" % left.total_seconds() )
      if option == "timeleft":
        now = Time.dateTime()
        left = proxyDict[ 'chain' ].getNotAfterDate()[ 'Value' ] - now
        return S_OK( "%d\n" % left.total_seconds() )
      if option == "identity":
        return S_OK( "%s\n" % data[ 'subject' ] )
      if option == "fqan":
        return S_OK( "\n".join( [ f.replace( "/Role=NULL", "" ).replace( "/Capability=NULL", "" ) for f in data[ 'fqan' ] ] ) )
      if option == "all":
        lines = []
        creds = proxyDict[ 'chain' ].getCredentials()[ 'Value' ]
        lines.append( "subject : %s" % creds[ 'subject' ] )
        lines.append( "issuer : %s" % creds[ 'issuer' ] )
        lines.append( "identity : %s" % creds[ 'identity' ] )
        if proxyDict[ 'chain' ].isRFC():
          lines.append( "type : RFC compliant proxy" )
        else:
          lines.append( "type : proxy" )
        left = creds[ 'secondsLeft' ]
        h = int( left / 3600 )
        m = int( left / 60 ) - h * 60
        s = int( left ) - m * 60 - h * 3600
        lines.append( "timeleft  : %s:%s:%s\nkey usage : Digital Signature, Key Encipherment, Data Encipherment" % (  h, m, s ) )
        lines.append( "== VO %s extension information ==" % data[ 'vo' ] )
        lines.append( "VO: %s" % data[ 'vo' ] )
        lines.append( "subject : %s" % data[ 'subject' ] )
        lines.append( "issuer : %s" % data[ 'issuer' ] )
        for fqan in data[ 'fqan' ]:
          lines.append( "attribute : %s" % fqan )
        if 'attribute' in data:
          lines.append( "attribute : %s" % data[ 'attribute' ] )
        now = Time.dateTime()
        left = ( data[ 'notAfter' ] - now ).total_seconds()
        h = int( left / 3600 )
        m = int( left / 60 ) - h * 60
        s = int( left ) - m * 60 - h * 3600
        lines.append( "timeleft : %s:%s:%s" % ( h, m , s ) )

        return S_OK( "\n".join( lines ) )
      else:
        return S_ERROR( "NOT IMP" )

    finally:
      if proxyDict[ 'tempFile' ]:
        self._unlinkFiles( proxyDict[ 'tempFile' ] )
Ejemplo n.º 7
0
  def setVOMSAttributes( self, proxy, attribute = None, vo = None ):
    """ Sets voms attributes to a proxy
    """
    if not vo:
      return S_ERROR( "No vo specified, and can't get default in the configuration" )

    retVal = File.multiProxyArgument( proxy )
    if not retVal[ 'OK' ]:
      return retVal
    proxyDict = retVal[ 'Value' ]
    chain = proxyDict[ 'chain' ]
    proxyLocation = proxyDict[ 'file' ]

    secs = chain.getRemainingSecs()[ 'Value' ] - 300
    if secs < 0:
      return S_ERROR( "Proxy length is less that 300 secs" )
    hours = int( secs / 3600 )
    mins = int( ( secs - hours * 3600 ) / 60 )

    retVal = self._generateTemporalFile()
    if not retVal[ 'OK' ]:
      File.deleteMultiProxy( proxyDict )
      return retVal
    newProxyLocation = retVal[ 'Value' ]

    cmdArgs = []
    if chain.isLimitedProxy()[ 'Value' ]:
      cmdArgs.append( '-limited' )
    cmdArgs.append( '-cert "%s"' % proxyLocation )
    cmdArgs.append( '-key "%s"' % proxyLocation )
    cmdArgs.append( '-out "%s"' % newProxyLocation )
    if attribute and attribute != 'NoRole':
      cmdArgs.append( '-voms "%s:%s"' % ( vo, attribute ) )
    else:
      cmdArgs.append( '-voms "%s"' % vo )
    cmdArgs.append( '-valid "%s:%s"' % ( hours, mins ) )
    tmpDir = False
    vomsesPath = self.getVOMSESLocation()
    if vomsesPath:
      cmdArgs.append( '-vomses "%s"' % vomsesPath )

    if not Os.which('voms-proxy-init'):
      return S_ERROR("Missing voms-proxy-init")

    cmd = 'voms-proxy-init %s' % " ".join( cmdArgs )
    result = shellCall( self._secCmdTimeout, cmd )
    if tmpDir:
      shutil.rmtree( tmpDir )

    File.deleteMultiProxy( proxyDict )

    if not result['OK']:
      self._unlinkFiles( newProxyLocation )
      return S_ERROR( 'Failed to call voms-proxy-init: %s' % result['Message'] )

    status, output, error = result['Value']

    if status:
      self._unlinkFiles( newProxyLocation )
      return S_ERROR( 'Failed to set VOMS attributes. Command: %s; StdOut: %s; StdErr: %s' % ( cmd, output, error ) )

    newChain = X509Chain()
    retVal = newChain.loadProxyFromFile( newProxyLocation )
    self._unlinkFiles( newProxyLocation )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Can't load new proxy: %s" % retVal[ 'Message' ] )

    return S_OK( newChain )
Ejemplo n.º 8
0
    def getDelegatedProxy(self, proxyChain, lifeTime=604800, useDNAsUserName=False):
        """
      Get delegated proxy from MyProxy server
      return S_OK( X509Chain ) / S_ERROR
    """
        # TODO: Set the proxy coming in proxyString to be the proxy to use

        # Get myproxy username diracgroup:diracuser
        retVal = File.multiProxyArgument(proxyChain)
        if not retVal["OK"]:
            return retVal
        proxyDict = retVal["Value"]
        chain = proxyDict["chain"]
        proxyLocation = proxyDict["file"]

        retVal = self._generateTemporalFile()
        if not retVal["OK"]:
            File.deleteMultiProxy(proxyDict)
            return retVal
        newProxyLocation = retVal["Value"]

        # myproxy-get-delegation works only with environment variables
        cmdEnv = self._getExternalCmdEnvironment()
        if self._secRunningFromTrustedHost:
            cmdEnv["X509_USER_CERT"] = self._secCertLoc
            cmdEnv["X509_USER_KEY"] = self._secKeyLoc
            if "X509_USER_PROXY" in cmdEnv:
                del cmdEnv["X509_USER_PROXY"]
        else:
            cmdEnv["X509_USER_PROXY"] = proxyLocation

        cmdArgs = []
        cmdArgs.append("-s '%s'" % self._secServer)
        cmdArgs.append("-t '%s'" % (int(lifeTime / 3600)))
        cmdArgs.append("-a '%s'" % proxyLocation)
        cmdArgs.append("-o '%s'" % newProxyLocation)
        if useDNAsUserName:
            cmdArgs.append("-d")
        else:
            retVal = self._getUsername(chain)
            if not retVal["OK"]:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal["Value"]
            cmdArgs.append('-l "%s"' % mpUsername)

        cmd = "myproxy-logon %s" % " ".join(cmdArgs)
        gLogger.verbose("myproxy-logon command:\n%s" % cmd)

        result = shellCall(self._secCmdTimeout, cmd, env=cmdEnv)

        File.deleteMultiProxy(proxyDict)

        if not result["OK"]:
            errMsg = "Call to myproxy-logon failed: %s" % result["Message"]
            File.deleteMultiProxy(proxyDict)
            return S_ERROR(errMsg)

        status, output, error = result["Value"]

        # Clean-up files
        if status:
            errMsg = "Call to myproxy-logon failed"
            extErrMsg = "Command: %s; StdOut: %s; StdErr: %s" % (cmd, result, error)
            File.deleteMultiProxy(proxyDict)
            return S_ERROR("%s %s" % (errMsg, extErrMsg))

        chain = X509Chain()
        retVal = chain.loadProxyFromFile(newProxyLocation)
        if not retVal["OK"]:
            File.deleteMultiProxy(proxyDict)
            return S_ERROR("myproxy-logon failed when reading delegated file: %s" % retVal["Message"])

        File.deleteMultiProxy(proxyDict)
        return S_OK(chain)
Ejemplo n.º 9
0
    def getInfo(self, proxyChain, useDNAsUserName=False):
        """
      Get info from myproxy server
      return S_OK( { 'username' : myproxyusername,
                     'owner' : owner DN,
                     'timeLeft' : secs left } ) / S_ERROR
    """
        # TODO: Set the proxy coming in proxyString to be the proxy to use

        # Get myproxy username diracgroup:diracuser
        retVal = File.multiProxyArgument(proxyChain)
        if not retVal["OK"]:
            return retVal
        proxyDict = retVal["Value"]
        chain = proxyDict["chain"]
        proxyLocation = proxyDict["file"]

        # myproxy-get-delegation works only with environment variables
        cmdEnv = self._getExternalCmdEnvironment()
        if self._secRunningFromTrustedHost:
            cmdEnv["X509_USER_CERT"] = self._secCertLoc
            cmdEnv["X509_USER_KEY"] = self._secKeyLoc
            if "X509_USER_PROXY" in cmdEnv:
                del cmdEnv["X509_USER_PROXY"]
        else:
            cmdEnv["X509_USER_PROXY"] = proxyLocation

        cmdArgs = []
        cmdArgs.append("-s '%s'" % self._secServer)
        if useDNAsUserName:
            cmdArgs.append("-d")
        else:
            retVal = self._getUsername(chain)
            if not retVal["OK"]:
                File.deleteMultiProxy(proxyDict)
                return retVal
            mpUsername = retVal["Value"]
            cmdArgs.append('-l "%s"' % mpUsername)

        cmd = "myproxy-info %s" % " ".join(cmdArgs)
        gLogger.verbose("myproxy-info command:\n%s" % cmd)

        result = shellCall(self._secCmdTimeout, cmd, env=cmdEnv)

        File.deleteMultiProxy(proxyDict)

        if not result["OK"]:
            errMsg = "Call to myproxy-info failed: %s" % result["Message"]
            File.deleteMultiProxy(proxyDict)
            return S_ERROR(errMsg)

        status, output, error = result["Value"]

        # Clean-up files
        if status:
            errMsg = "Call to myproxy-info failed"
            extErrMsg = "Command: %s; StdOut: %s; StdErr: %s" % (cmd, result, error)
            return S_ERROR("%s %s" % (errMsg, extErrMsg))

        infoDict = {}
        usernameRE = re.compile("username\s*:\s*(\S*)")
        ownerRE = re.compile("owner\s*:\s*(\S*)")
        timeLeftRE = re.compile("timeleft\s*:\s*(\S*)")
        for line in List.fromChar(output, "\n"):
            match = usernameRE.search(line)
            if match:
                infoDict["username"] = match.group(1)
            match = ownerRE.search(line)
            if match:
                infoDict["owner"] = match.group(1)
            match = timeLeftRE.search(line)
            if match:
                try:
                    fields = List.fromChar(match.group(1), ":")
                    fields.reverse()
                    secsLeft = 0
                    for iP in range(len(fields)):
                        if iP == 0:
                            secsLeft += int(fields[iP])
                        elif iP == 1:
                            secsLeft += int(fields[iP]) * 60
                        elif iP == 2:
                            secsLeft += int(fields[iP]) * 3600
                    infoDict["timeLeft"] = secsLeft
                except Exception, x:
                    print x
Ejemplo n.º 10
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: a string
        @param proxy: 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 = File.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:
      gLogger.warn( 'Failed to execute:', cmd )
      gLogger.warn( 'Exit code:', status )
      gLogger.warn( 'StdOut' , output )
      gLogger.warn( 'StdErr' , error )
      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 )
Ejemplo n.º 11
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 = File.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:
      gLogger.warn( 'Failed to execute:', cmd )
      gLogger.warn( 'Exit code:', status )
      gLogger.warn( 'StdOut' , output )
      gLogger.warn( 'StdErr' , error )
      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 )
Ejemplo n.º 12
0
  def setVOMSAttributes( self, proxy, attribute = None, vo = None ):
    """ Sets voms attributes to a proxy
    """
    if not vo:
      return S_ERROR( "No vo specified, and can't get default in the configuration" )

    retVal = File.multiProxyArgument( proxy )
    if not retVal[ 'OK' ]:
      return retVal
    proxyDict = retVal[ 'Value' ]
    chain = proxyDict[ 'chain' ]
    proxyLocation = proxyDict[ 'file' ]

    secs = chain.getRemainingSecs()[ 'Value' ] - 300
    if secs < 0:
      return S_ERROR( "Proxy length is less that 300 secs" )
    hours = int( secs / 3600 )
    mins = int( ( secs - hours * 3600 ) / 60 )

    retVal = self._generateTemporalFile()
    if not retVal[ 'OK' ]:
      File.deleteMultiProxy( proxyDict )
      return retVal
    newProxyLocation = retVal[ 'Value' ]

    cmdArgs = []
    cmdArgs.append( '-cert "%s"' % proxyLocation )
    cmdArgs.append( '-key "%s"' % proxyLocation )
    cmdArgs.append( '-out "%s"' % newProxyLocation )
    if attribute and attribute != 'NoRole':
      cmdArgs.append( '-voms "%s:%s"' % ( vo, attribute ) )
    else:
      cmdArgs.append( '-voms "%s"' % vo )
    cmdArgs.append( '-valid "%s:%s"' % ( hours, mins ) )
    tmpDir = False
    vomsesPath = self.getVOMSESLocation()
    if vomsesPath:
      cmdArgs.append( '-vomses "%s"' % vomsesPath )

    cmd = 'voms-proxy-init %s' % " ".join( cmdArgs )
    result = shellCall( self._secCmdTimeout, cmd )
    if tmpDir:
      shutil.rmtree( tmpDir )

    File.deleteMultiProxy( proxyDict )

    if not result['OK']:
      self._unlinkFiles( newProxyLocation )
      return S_ERROR( 'Failed to call voms-proxy-init' )

    status, output, error = result['Value']

    if status:
      self._unlinkFiles( newProxyLocation )
      return S_ERROR( 'Failed to set VOMS attributes. Command: %s; StdOut: %s; StdErr: %s' % ( cmd, output, error ) )

    newChain = X509Chain()
    retVal = newChain.loadProxyFromFile( newProxyLocation )
    self._unlinkFiles( newProxyLocation )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Can't load new proxy: %s" % retVal[ 'Message' ] )

    return S_OK( newChain )
Ejemplo n.º 13
0
  def renewProxy( self, proxyToBeRenewed = False, minLifeTime = 3600, newProxyLifeTime = 43200, proxyToConnect = False ):
    """
    Renew a proxy using the ProxyManager
    Arguments:
      proxyToBeRenewed : proxy to renew
      minLifeTime : if proxy life time is less than this, renew. Skip otherwise
      newProxyLifeTime : life time of new proxy
      proxyToConnect : proxy to use for connecting to the service
    """
    retVal = File.multiProxyArgument( proxyToBeRenewed )
    if not retVal[ 'Value' ]:
      return retVal
    proxyToRenewDict = retVal[ 'Value' ]

    secs = proxyToRenewDict[ 'chain' ].getRemainingSecs()[ 'Value' ]
    if secs > minLifeTime:
      File.deleteMultiProxy( proxyToRenewDict )
      return S_OK()

    if not proxyToConnect:
      proxyToConnectDict = { 'chain': False, 'tempFile': False }
    else:
      retVal = File.multiProxyArgument( proxyToConnect )
      if not retVal[ 'Value' ]:
        File.deleteMultiProxy( proxyToRenewDict )
        return retVal
      proxyToConnectDict = retVal[ 'Value' ]

    userDN = proxyToRenewDict[ 'chain' ].getIssuerCert()[ 'Value' ].getSubjectDN()[ 'Value' ]
    retVal = proxyToRenewDict[ 'chain' ].getDIRACGroup()
    if not retVal[ 'OK' ]:
      File.deleteMultiProxy( proxyToRenewDict )
      File.deleteMultiProxy( proxyToConnectDict )
      return retVal
    userGroup = retVal[ 'Value' ]
    limited = proxyToRenewDict[ 'chain' ].isLimitedProxy()[ 'Value' ]

    voms = VOMS()
    retVal = voms.getVOMSAttributes( proxyToRenewDict[ 'chain' ] )
    if not retVal[ 'OK' ]:
      File.deleteMultiProxy( proxyToRenewDict )
      File.deleteMultiProxy( proxyToConnectDict )
      return retVal
    vomsAttrs = retVal[ 'Value' ]
    if vomsAttrs:
      retVal = self.downloadVOMSProxy( userDN,
                                       userGroup,
                                       limited = limited,
                                       requiredTimeLeft = newProxyLifeTime,
                                       requiredVOMSAttribute = vomsAttrs[0],
                                       proxyToConnect = proxyToConnectDict[ 'chain' ] )
    else:
      retVal = self.downloadProxy( userDN,
                                   userGroup,
                                   limited = limited,
                                   requiredTimeLeft = newProxyLifeTime,
                                   proxyToConnect = proxyToConnectDict[ 'chain' ] )

    File.deleteMultiProxy( proxyToRenewDict )
    File.deleteMultiProxy( proxyToConnectDict )

    if not retVal[ 'OK' ]:
      return retVal

    chain = retVal['Value']

    if not proxyToRenewDict[ 'tempFile' ]:
      return chain.dumpAllToFile( proxyToRenewDict[ 'file' ] )

    return S_OK( chain )
Ejemplo n.º 14
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: a string
        @param proxy: 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 = File.multiProxyArgument(proxy)
        if not retVal['OK']:
            return retVal
        proxyDict = retVal['Value']

        try:
            res = proxyDict['chain'].getVOMSData()
            if not res['OK']:
                return res

            data = res['Value']

            if option == 'actimeleft':
                now = Time.dateTime()
                left = data['notAfter'] - now
                return S_OK("%d\n" % left.total_seconds())
            if option == "timeleft":
                now = Time.dateTime()
                left = proxyDict['chain'].getNotAfterDate()['Value'] - now
                return S_OK("%d\n" % left.total_seconds())
            if option == "identity":
                return S_OK("%s\n" % data['subject'])
            if option == "fqan":
                return S_OK("\n".join([
                    f.replace("/Role=NULL",
                              "").replace("/Capability=NULL", "")
                    for f in data['fqan']
                ]))
            if option == "all":
                lines = []
                creds = proxyDict['chain'].getCredentials()['Value']
                lines.append("subject : %s" % creds['subject'])
                lines.append("issuer : %s" % creds['issuer'])
                lines.append("identity : %s" % creds['identity'])
                if proxyDict['chain'].isRFC():
                    lines.append("type : RFC compliant proxy")
                else:
                    lines.append("type : proxy")
                left = creds['secondsLeft']
                h = int(left / 3600)
                m = int(left / 60) - h * 60
                s = int(left) - m * 60 - h * 3600
                lines.append(
                    "timeleft  : %s:%s:%s\nkey usage : Digital Signature, Key Encipherment, Data Encipherment"
                    % (h, m, s))
                lines.append("== VO %s extension information ==" % data['vo'])
                lines.append("VO: %s" % data['vo'])
                lines.append("subject : %s" % data['subject'])
                lines.append("issuer : %s" % data['issuer'])
                for fqan in data['fqan']:
                    lines.append("attribute : %s" % fqan)
                if 'attribute' in data:
                    lines.append("attribute : %s" % data['attribute'])
                now = Time.dateTime()
                left = (data['notAfter'] - now).total_seconds()
                h = int(left / 3600)
                m = int(left / 60) - h * 60
                s = int(left) - m * 60 - h * 3600
                lines.append("timeleft : %s:%s:%s" % (h, m, s))

                return S_OK("\n".join(lines))
            else:
                return S_ERROR("NOT IMP")

        finally:
            if proxyDict['tempFile']:
                self._unlinkFiles(proxyDict['file'])