Exemplo n.º 1
0
Arquivo: ProxyDB.py Projeto: bmb/DIRAC
  def getVOMSProxy( self, userDN, userGroup, requiredLifeTime = False, requestedVOMSAttr = False ):
    """ Get proxy string from the Proxy Repository for use with userDN
        in the userGroup and VOMS attr
    """
    retVal = self.__getVOMSAttribute( userGroup, requestedVOMSAttr )
    if not retVal[ 'OK' ]:
      return retVal
    vomsAttr = retVal[ 'Value' ][ 'attribute' ]
    vomsVO = retVal[ 'Value' ][ 'VOMSVO' ]

    #Look in the cache
    retVal = self.__getPemAndTimeLeft( userDN, userGroup, vomsAttr )
    if retVal[ 'OK' ]:
      pemData = retVal[ 'Value' ][0]
      vomsTime = retVal[ 'Value' ][1]
      chain = X509Chain()
      retVal = chain.loadProxyFromString( pemData )
      if retVal[ 'OK' ]:
        retVal = chain.getRemainingSecs()
        if retVal[ 'OK' ]:
          remainingSecs = retVal[ 'Value' ]
          if requiredLifeTime and requiredLifeTime <= vomsTime and requiredLifeTime <= remainingSecs:
            return S_OK( ( chain, min( vomsTime, remainingSecs ) ) )

    retVal = self.getProxy( userDN, userGroup, requiredLifeTime )
    if not retVal[ 'OK' ]:
      return retVal
    chain, secsLeft = retVal[ 'Value' ]

    if requiredLifeTime and requiredLifeTime > secsLeft:
      return S_ERROR( "Stored proxy is not long lived enough" )

    vomsMgr = VOMS()

    retVal = vomsMgr.getVOMSAttributes( chain )
    if retVal[ 'OK' ]:
      attrs = retVal[ 'Value' ]
      if len( attrs ) > 0:
        if attrs[0] != vomsAttr:
          return S_ERROR( "Stored proxy has already a different VOMS attribute %s than requested %s" % ( vomsAttr, attrs[0] ) )
        else:
          result = self.__storeVOMSProxy( userDN, userGroup, vomsAttr, chain )
          if not result[ 'OK' ]:
            return result
          secsLeft = result[ 'Value' ]
          if requiredLifeTime and requiredLifeTime <= secsLeft:
            return S_OK( ( chain, secsLeft ) )
          return S_ERROR( "Stored proxy has already a different VOMS attribute and is not long lived enough" )

    retVal = vomsMgr.setVOMSAttributes( chain , vomsAttr, vo = vomsVO )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Cannot append voms extension: %s" % retVal[ 'Message' ] )
    chain = retVal[ 'Value' ]
    result = self.__storeVOMSProxy( userDN, userGroup, vomsAttr, chain )
    if not result[ 'OK' ]:
      return result
    secsLeft = result[ 'Value' ]
    return S_OK( ( chain, secsLeft ) )
Exemplo n.º 2
0
  def getVOMSAttributes(self, chain):
    """ Get the voms attributes for a chain

        :param X509Chain chain: proxy as a chain

        :return: S_OK(str)/S_ERROR()
    """
    return VOMS().getVOMSAttributes(chain)
Exemplo n.º 3
0
 def __storeVOMSProxy(self, userDN, userGroup, vomsAttr, chain):
     retVal = self._getConnection()
     if not retVal['OK']:
         return retVal
     connObj = retVal['Value']
     retVal1 = VOMS().getVOMSProxyInfo(chain, 'actimeleft')
     retVal2 = VOMS().getVOMSProxyInfo(chain, 'timeleft')
     if not retVal1['OK']:
         return retVal1
     if not retVal2['OK']:
         return retVal2
     try:
         vomsSecsLeft1 = int(retVal1['Value'].strip())
         vomsSecsLeft2 = int(retVal2['Value'].strip())
         vomsSecsLeft = min(vomsSecsLeft1, vomsSecsLeft2)
     except Exception, e:
         return S_ERROR("Can't parse VOMS time left: %s" % str(e))
Exemplo n.º 4
0
def getProxyInfo(proxy=False, disableVOMS=False):
    """
  :Returns: a dict with all the proxy info:

    * values that will be there always
        * 'chain' : chain object containing the proxy
        * 'subject' : subject of the proxy
        * 'issuer' : issuer of the proxy
        * 'isProxy' : bool
        * 'isLimitedProxy' : bool
        * 'validDN' : Valid DN in DIRAC
        * 'validGroup' : Valid Group in DIRAC
        * 'secondsLeft' : Seconds left
    * values that can be there
        * 'path' : path to the file,
        * 'group' : DIRAC group
        * 'groupProperties' : Properties that apply to the DIRAC Group
        * 'username' : DIRAC username
        * 'identity' : DN that generated the proxy
        * 'hostname' : DIRAC host nickname
        * 'VOMS'

  """
    # Discover proxy location
    proxyLocation = False
    if isinstance(proxy, X509Chain):
        chain = proxy
    else:
        if not proxy:
            proxyLocation = Locations.getProxyLocation()
        elif isinstance(proxy, basestring):
            proxyLocation = proxy
        if not proxyLocation:
            return S_ERROR(DErrno.EPROXYFIND)
        chain = X509Chain()
        retVal = chain.loadProxyFromFile(proxyLocation)
        if not retVal['OK']:
            return S_ERROR(DErrno.EPROXYREAD,
                           "%s: %s " % (proxyLocation, retVal['Message']))

    retVal = chain.getCredentials()
    if not retVal['OK']:
        return retVal

    infoDict = retVal['Value']
    infoDict['chain'] = chain
    if proxyLocation:
        infoDict['path'] = proxyLocation

    if not disableVOMS and chain.isVOMS()['Value']:
        infoDict['hasVOMS'] = True
        retVal = VOMS().getVOMSAttributes(chain)
        if retVal['OK']:
            infoDict['VOMS'] = retVal['Value']
        else:
            infoDict['VOMSError'] = retVal['Message'].strip()

    return S_OK(infoDict)
Exemplo n.º 5
0
def getProxyInfo(proxy=False, disableVOMS=False):
    """
  Returns a dict with all the proxy info
  * values that will be there always
   'chain' : chain object containing the proxy
   'subject' : subject of the proxy
   'issuer' : issuer of the proxy
   'isProxy' : bool
   'isLimitedProxy' : bool
   'validDN' : Valid DN in DIRAC
   'validGroup' : Valid Group in DIRAC
   'secondsLeft' : Seconds left
  * values that can be there
   'path' : path to the file,
   'group' : DIRAC group
   'groupProperties' : Properties that apply to the DIRAC Group
   'username' : DIRAC username
   'identity' : DN that generated the proxy
   'hostname' : DIRAC host nickname
   'VOMS'
  """
    #Discover proxy location
    proxyLocation = False
    if type(proxy) == g_X509ChainType:
        chain = proxy
    else:
        if not proxy:
            proxyLocation = Locations.getProxyLocation()
        elif type(proxy) in (types.StringType, types.UnicodeType):
            proxyLocation = proxy
        if not proxyLocation:
            return S_ERROR("Can't find a valid proxy")
        chain = X509Chain()
        retVal = chain.loadProxyFromFile(proxyLocation)
        if not retVal['OK']:
            return S_ERROR("Can't load %s: %s " %
                           (proxyLocation, retVal['Message']))

    retVal = chain.getCredentials()
    if not retVal['OK']:
        return retVal

    infoDict = retVal['Value']
    infoDict['chain'] = chain
    if proxyLocation:
        infoDict['path'] = proxyLocation

    if not disableVOMS and chain.isVOMS()['Value']:
        infoDict['hasVOMS'] = True
        retVal = VOMS().getVOMSAttributes(chain)
        if retVal['OK']:
            infoDict['VOMS'] = retVal['Value']
        else:
            infoDict['VOMSError'] = retVal['Message'].strip()

    return S_OK(infoDict)
Exemplo n.º 6
0
 def __storeVOMSProxy(self, userDN, userGroup, vomsAttr, chain):
     retVal = self._getConnection()
     if not retVal['OK']:
         return retVal
     connObj = retVal['Value']
     cmd = "DELETE FROM `ProxyDB_VOMSProxies` WHERE UserDN='%s' AND UserGroup='%s' AND VOMSAttr='%s'" % (
         userDN, userGroup, vomsAttr)
     retVal = self._update(cmd, conn=connObj)
     if not retVal['OK']:
         return retVal
     retVal1 = VOMS().getVOMSProxyInfo(chain, 'actimeleft')
     retVal2 = VOMS().getVOMSProxyInfo(chain, 'timeleft')
     if not retVal1['OK']:
         return retVal1
     if not retVal2['OK']:
         return retVal2
     try:
         vomsSecsLeft1 = int(retVal1['Value'].strip())
         vomsSecsLeft2 = int(retVal2['Value'].strip())
         vomsSecsLeft = min(vomsSecsLeft1, vomsSecsLeft2)
     except Exception, e:
         return S_ERROR("Can't parse VOMS time left: %s" % str(e))
Exemplo n.º 7
0
Arquivo: ProxyDB.py Projeto: bmb/DIRAC
 def __checkVOMSisAlignedWithGroup( self, userGroup, chain ):
   #HACK: We deny proxies with VOMS extensions
   result = chain.isVOMS()
   if result[ 'OK' ] and result[ 'Value' ]:
     return S_ERROR( "Proxies with VOMS extensions are not allowed to be uploaded" )
   #END HACK
   voms = VOMS()
   if not voms.vomsInfoAvailable():
     if self.__vomsRequired:
       return S_ERROR( "VOMS is required, but it's not available" )
     self.log.warn( "voms-proxy-info is not available" )
     return S_OK()
   retVal = voms.getVOMSAttributes( chain )
   if not retVal[ 'OK' ]:
     return retVal
   attr = retVal[ 'Value' ]
   validVOMSAttr = Registry.getVOMSAttributeForGroup( userGroup )
   if len( attr ) == 0 or attr[0] == validVOMSAttr:
     return S_OK( 'OK' )
   msg = "VOMS attributes are not aligned with dirac group"
   msg += "Attributes are %s and allowed is %s for group %s" % ( attr, validVOMSAttr, userGroup )
   return S_ERROR( msg )
Exemplo n.º 8
0
 def __storeVOMSProxy(self, userDN, userGroup, vomsAttr, chain):
     retVal = self._getConnection()
     if not retVal['OK']:
         return retVal
     connObj = retVal['Value']
     retVal1 = VOMS().getVOMSProxyInfo(chain, 'actimeleft')
     retVal2 = VOMS().getVOMSProxyInfo(chain, 'timeleft')
     if not retVal1['OK']:
         return retVal1
     if not retVal2['OK']:
         return retVal2
     try:
         vomsSecsLeft1 = int(retVal1['Value'].strip())
         vomsSecsLeft2 = int(retVal2['Value'].strip())
         vomsSecsLeft = min(vomsSecsLeft1, vomsSecsLeft2)
     except Exception as e:
         return S_ERROR("Can't parse VOMS time left: %s" % str(e))
     secsLeft = min(vomsSecsLeft, chain.getRemainingSecs()['Value'])
     pemData = chain.dumpAllToString()['Value']
     result = Registry.getUsernameForDN(userDN)
     if not result['OK']:
         userName = ""
     else:
         userName = result['Value']
     try:
         sUserName = self._escapeString(userName)['Value']
         sUserDN = self._escapeString(userDN)['Value']
         sUserGroup = self._escapeString(userGroup)['Value']
         sVomsAttr = self._escapeString(vomsAttr)['Value']
         sPemData = self._escapeString(pemData)['Value']
     except KeyError:
         return S_ERROR("Could not escape some data")
     cmd = "REPLACE INTO `ProxyDB_VOMSProxies` ( UserName, UserDN, UserGroup, VOMSAttr, Pem, ExpirationTime ) VALUES "
     cmd += "( %s, %s, %s, %s, %s, TIMESTAMPADD( SECOND, %d, UTC_TIMESTAMP() ) )" % (
         sUserName, sUserDN, sUserGroup, sVomsAttr, sPemData, secsLeft)
     result = self._update(cmd, conn=connObj)
     if not result['OK']:
         return result
     return S_OK(secsLeft)
Exemplo n.º 9
0
 def __checkVOMSisAlignedWithGroup(self, userGroup, chain):
     #HACK: We deny proxies with VOMS extensions
     result = chain.isVOMS()
     if result['OK'] and result['Value']:
         return S_ERROR(
             "Proxies with VOMS extensions are not allowed to be uploaded")
     #END HACK
     voms = VOMS()
     if not voms.vomsInfoAvailable():
         if self.__vomsRequired:
             return S_ERROR("VOMS is required, but it's not available")
         self.log.warn("voms-proxy-info is not available")
         return S_OK()
     retVal = voms.getVOMSAttributes(chain)
     if not retVal['OK']:
         return retVal
     attr = retVal['Value']
     validVOMSAttr = CS.getVOMSAttributeForGroup(userGroup)
     if len(attr) == 0 or attr[0] == validVOMSAttr:
         return S_OK('OK')
     msg = "VOMS attributes are not aligned with dirac group"
     msg += "Attributes are %s and allowed is %s for group %s" % (
         attr, validVOMSAttr, userGroup)
     return S_ERROR(msg)
Exemplo n.º 10
0
 def hash(self):
     if not self.__loadedChain:
         return S_ERROR("No chain loaded")
     if self.__hash:
         return S_OK(self.__hash)
     sha1 = hashlib.sha1()
     for cert in self.__certList:
         sha1.update(cert.get_subject().one_line())
     sha1.update(str(self.getRemainingSecs()['Value'] / 3600))
     sha1.update(self.getDIRACGroup()['Value'])
     if self.isVOMS():
         sha1.update("VOMS")
         from DIRAC.Core.Security.VOMS import VOMS
         result = VOMS().getVOMSAttributes(self)
         if result['OK']:
             sha1.update(str(result['Value']))
     self.__hash = sha1.hexdigest()
     return S_OK(self.__hash)
Exemplo n.º 11
0
    def hash(self):
        """ Get a hash of the chain
        In practice, this is only used to index the chain in a DictCache

        :returns: S_OK(string hash)
    """

        if self.__hash:
            return S_OK(self.__hash)
        sha1 = hashlib.sha1()
        for cert in self._certList:
            sha1.update(str(cert.getSubjectNameObject()))
        sha1.update(str(self.getRemainingSecs()['Value'] / 3600))
        sha1.update(self.getDIRACGroup()['Value'])
        if self.isVOMS():
            sha1.update("VOMS")
            from DIRAC.Core.Security.VOMS import VOMS
            result = VOMS().getVOMSAttributes(self)
            if result['OK']:
                sha1.update(str(result['Value']))
        self.__hash = sha1.hexdigest()
        return S_OK(self.__hash)
Exemplo n.º 12
0
  def renewProxy(self, proxyToBeRenewed=None, minLifeTime=3600, newProxyLifeTime=43200, proxyToConnect=None):
    """ Renew a proxy using the ProxyManager

        :param X509Chain proxyToBeRenewed: proxy to renew
        :param int minLifeTime: if proxy life time is less than this, renew. Skip otherwise
        :param int newProxyLifeTime: life time of new proxy
        :param X509Chain proxyToConnect: proxy to use for connecting to the service

        :return: S_OK(X509Chain)/S_ERROR()
    """
    retVal = multiProxyArgument(proxyToBeRenewed)
    if not retVal['Value']:
      return retVal
    proxyToRenewDict = retVal['Value']

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

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

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

    voms = VOMS()
    retVal = voms.getVOMSAttributes(proxyToRenewDict['chain'])
    if not retVal['OK']:
      deleteMultiProxy(proxyToRenewDict)
      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'])

    deleteMultiProxy(proxyToRenewDict)
    deleteMultiProxy(proxyToConnectDict)

    if not retVal['OK']:
      return retVal

    chain = retVal['Value']

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

    return S_OK(chain)
Exemplo n.º 13
0
 def getVOMSAttributes(self, chain):
     """
 Get the voms attributes for a chain
 """
     return VOMS().getVOMSAttributes(chain)
Exemplo n.º 14
0
    def _monitorProxy(self, payloadProxy=None):
        """Base class for the monitor and update of the payload proxy, to be used in
        derived classes for the basic renewal of the proxy, if further actions are
        necessary they should be implemented there

        :param str payloadProxy: location of the payload proxy file

        :returns: S_OK(filename)/S_ERROR
        """
        if not payloadProxy:
            return S_ERROR("No payload proxy")

        # This will get the pilot proxy
        ret = getProxyInfo()
        if not ret["OK"]:
            pilotProxy = None
        else:
            pilotProxy = ret["Value"]["path"]
            self.log.notice("Pilot Proxy:", pilotProxy)

        retVal = getProxyInfo(payloadProxy)
        if not retVal["OK"]:
            self.log.error("Could not get payload proxy info", retVal)
            return retVal
        self.log.verbose("Payload Proxy information:\n%s" %
                         formatProxyInfoAsString(retVal["Value"]))

        payloadProxyDict = retVal["Value"]
        payloadSecs = payloadProxyDict["chain"].getRemainingSecs()["Value"]
        if payloadSecs > self.minProxyTime:
            self.log.verbose("No need to renew payload Proxy")
            return S_OK()

        # if there is no pilot proxy, assume there is a certificate and try a renewal
        if not pilotProxy:
            self.log.info(
                "Using default credentials to get a new payload Proxy")
            return gProxyManager.renewProxy(
                proxyToBeRenewed=payloadProxy,
                minLifeTime=self.minProxyTime,
                newProxyLifeTime=self.defaultProxyTime,
                proxyToConnect=pilotProxy,
            )

        # if there is pilot proxy
        retVal = getProxyInfo(pilotProxy)
        if not retVal["OK"]:
            return retVal
        pilotProxyDict = retVal["Value"]

        if "groupProperties" not in pilotProxyDict:
            self.log.error("Invalid Pilot Proxy",
                           "Group has no properties defined")
            return S_ERROR("Proxy has no group properties defined")

        pilotProps = pilotProxyDict["groupProperties"]

        # if running with a pilot proxy, use it to renew the proxy of the payload
        if Properties.PILOT in pilotProps or Properties.GENERIC_PILOT in pilotProps:
            self.log.info("Using Pilot credentials to get a new payload Proxy")
            return gProxyManager.renewProxy(
                proxyToBeRenewed=payloadProxy,
                minLifeTime=self.minProxyTime,
                newProxyLifeTime=self.defaultProxyTime,
                proxyToConnect=pilotProxy,
            )

        # if we are running with other type of proxy check if they are for the same user and group
        # and copy the pilot proxy if necessary

        self.log.info("Trying to copy pilot Proxy to get a new payload Proxy")
        pilotProxySecs = pilotProxyDict["chain"].getRemainingSecs()["Value"]
        if pilotProxySecs <= payloadSecs:
            errorStr = "Pilot Proxy is not longer than payload Proxy"
            self.log.error(errorStr)
            return S_ERROR("Can not renew by copy: %s" % errorStr)

        # check if both proxies belong to the same user and group
        pilotDN = pilotProxyDict["chain"].getIssuerCert(
        )["Value"].getSubjectDN()["Value"]
        retVal = pilotProxyDict["chain"].getDIRACGroup()
        if not retVal["OK"]:
            return retVal
        pilotGroup = retVal["Value"]

        payloadDN = payloadProxyDict["chain"].getIssuerCert(
        )["Value"].getSubjectDN()["Value"]
        retVal = payloadProxyDict["chain"].getDIRACGroup()
        if not retVal["OK"]:
            return retVal
        payloadGroup = retVal["Value"]
        if pilotDN != payloadDN or pilotGroup != payloadGroup:
            errorStr = "Pilot Proxy and payload Proxy do not have same DN and Group"
            self.log.error(errorStr)
            return S_ERROR("Can not renew by copy: %s" % errorStr)

        if pilotProxyDict.get("hasVOMS", False):
            return pilotProxyDict["chain"].dumpAllToFile(payloadProxy)

        attribute = Registry.getVOMSAttributeForGroup(payloadGroup)
        vo = Registry.getVOMSVOForGroup(payloadGroup)

        retVal = VOMS().setVOMSAttributes(pilotProxyDict["chain"],
                                          attribute=attribute,
                                          vo=vo)
        if not retVal["OK"]:
            return retVal

        chain = retVal["Value"]
        return chain.dumpAllToFile(payloadProxy)
Exemplo n.º 15
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 = multiProxyArgument( proxyToBeRenewed )
    if not retVal[ 'Value' ]:
      return retVal
    proxyToRenewDict = retVal[ 'Value' ]

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

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

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

    voms = VOMS()
    retVal = voms.getVOMSAttributes( proxyToRenewDict[ 'chain' ] )
    if not retVal[ 'OK' ]:
      deleteMultiProxy( proxyToRenewDict )
      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' ] )

    deleteMultiProxy( proxyToRenewDict )
    deleteMultiProxy( proxyToConnectDict )

    if not retVal[ 'OK' ]:
      return retVal

    chain = retVal['Value']

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

    return S_OK( chain )
Exemplo n.º 16
0
    if not success and cliParams.strict:
      sys.exit( 1 )

  cliParams.setDIRACGroup( proxyInfo[ 'group' ] )
  if myProxyFlag:
    uploadProxyToMyProxy( cliParams, False )
  success = uploadProxyToDIRACProxyManager( cliParams )
  if not success and cliParams.strict:
    sys.exit( 1 )

  finalChain = proxyInfo[ 'chain' ]

  vomsMapping = CS.getVOMSAttributeForGroup( proxyInfo[ 'group' ] )
  vo = CS.getVOMSVOForGroup( proxyInfo[ 'group' ] )
  if vomsMapping:
    voms = VOMS()
    retVal = voms.setVOMSAttributes( finalChain, vomsMapping, vo )
    if not retVal[ 'OK' ]:
      #print "Cannot add voms attribute %s to proxy %s: %s" % ( attr, proxyInfo[ 'path' ], retVal[ 'Message' ] )
      msg = "Warning : Cannot add voms attribute %s to proxy\n" % ( vomsMapping )
      msg += "          Accessing data in the grid storage from the user interface will not be possible.\n"
      msg += "          The grid jobs will not be affected."
      if cliParams.strict:
        gLogger.error( msg )
        sys.exit( 1 )
      gLogger.warn( msg )
    else:
      finalChain = retVal[ 'Value' ]

  retVal = finalChain.dumpAllToFile( proxyInfo[ 'path' ] )
  if not retVal[ 'OK' ]:
Exemplo n.º 17
0
    def getVOMSProxy(self,
                     userDN,
                     userGroup,
                     requiredLifeTime=False,
                     requestedVOMSAttr=False):
        """ Get proxy string from the Proxy Repository for use with userDN
        in the userGroup and VOMS attr
    """
        retVal = self.__getVOMSAttribute(userGroup, requestedVOMSAttr)
        if not retVal['OK']:
            return retVal
        vomsAttr = retVal['Value']['attribute']
        vomsVO = retVal['Value']['VOMSVO']

        #Look in the cache
        retVal = self.__getPemAndTimeLeft(userDN, userGroup, vomsAttr)
        if retVal['OK']:
            pemData = retVal['Value'][0]
            vomsTime = retVal['Value'][1]
            chain = X509Chain()
            retVal = chain.loadProxyFromString(pemData)
            if retVal['OK']:
                retVal = chain.getRemainingSecs()
                if retVal['OK']:
                    remainingSecs = retVal['Value']
                    if requiredLifeTime and requiredLifeTime <= vomsTime and requiredLifeTime <= remainingSecs:
                        return S_OK((chain, min(vomsTime, remainingSecs)))

        retVal = self.getProxy(userDN, userGroup, requiredLifeTime)
        if not retVal['OK']:
            return retVal
        chain, secsLeft = retVal['Value']

        if requiredLifeTime and requiredLifeTime > secsLeft:
            return S_ERROR("Stored proxy is not long lived enough")

        vomsMgr = VOMS()

        retVal = vomsMgr.getVOMSAttributes(chain)
        if retVal['OK']:
            attrs = retVal['Value']
            if len(attrs) > 0:
                if attrs[0] != vomsAttr:
                    return S_ERROR(
                        "Stored proxy has already a different VOMS attribute %s than requested %s"
                        % (vomsAttr, attrs[0]))
                else:
                    result = self.__storeVOMSProxy(userDN, userGroup, vomsAttr,
                                                   chain)
                    if not result['OK']:
                        return result
                    secsLeft = result['Value']
                    if requiredLifeTime and requiredLifeTime <= secsLeft:
                        return S_OK((chain, secsLeft))
                    return S_ERROR(
                        "Stored proxy has already a different VOMS attribute and is not long lived enough"
                    )

        retVal = vomsMgr.setVOMSAttributes(chain, vomsAttr, vo=vomsVO)
        if not retVal['OK']:
            return S_ERROR("Cannot append voms extension: %s" %
                           retVal['Message'])
        chain = retVal['Value']
        result = self.__storeVOMSProxy(userDN, userGroup, vomsAttr, chain)
        if not result['OK']:
            return result
        secsLeft = result['Value']
        return S_OK((chain, secsLeft))
Exemplo n.º 18
0
        # Create local proxy with group
        self.outputFile = self.outputFile or getDefaultProxyLocation()
        parameters = (self.outputFile, int(self.lifetime or 12) * 3600, self.group)

        # Add a VOMS extension if the group requires it
        if (result := chain.generateProxyToFile(*parameters))["OK"] and (result := self.__enableCS())["OK"]:
            if not self.group and (result := findDefaultGroupForDN(credentials["DN"]))["OK"]:
                self.group = result["Value"]  # Use default group if user don't set it
            # based on the configuration we decide whether to add VOMS extensions
            if getGroupOption(self.group, "AutoAddVOMS", False):
                if not (vomsAttr := getVOMSAttributeForGroup(self.group)):
                    print(HTML(f"<yellow>No VOMS attribute foud for {self.group}</yellow>"))
                else:
                    vo = getVOMSVOForGroup(self.group)
                    if not (result := VOMS().setVOMSAttributes(self.outputFile, attribute=vomsAttr, vo=vo))["OK"]:
                        return S_ERROR(f"Failed adding VOMS attribute: {result['Message']}")
                    chain = result["Value"]
                    result = chain.generateProxyToFile(*parameters)
        if not result["OK"]:
            return S_ERROR(f"Couldn't generate proxy: {result['Message']}")

        if self.enableCS:
            # After creating the proxy, we can try to connect to the server
            if not (result := self.__enableCS())["OK"]:
                return result

            # Step 2: Upload proxy to DIRAC server
            result = gProxyManager.getUploadedProxyLifeTime(credentials["subject"])
            if not result["OK"]:
                return result
Exemplo n.º 19
0
    def _monitorProxy(self, pilotProxy, payloadProxy):
        """Base class for the monitor and update of the payload proxy, to be used in
      derived classes for the basic renewal of the proxy, if further actions are
      necessary they should be implemented there
    """
        retVal = getProxyInfo(payloadProxy)
        if not retVal['OK']:
            self.log.error('Could not get payload proxy info', retVal)
            return retVal
        self.log.verbose('Payload Proxy information:\n%s' %
                         formatProxyInfoAsString(retVal['Value']))

        payloadProxyDict = retVal['Value']
        payloadSecs = payloadProxyDict['chain'].getRemainingSecs()['Value']
        if payloadSecs > self.minProxyTime:
            self.log.verbose('No need to renew payload Proxy')
            return S_OK()

        # if there is no pilot proxy, assume there is a certificate and try a renewal
        if not pilotProxy:
            self.log.info(
                'Using default credentials to get a new payload Proxy')
            return gProxyManager.renewProxy(
                proxyToBeRenewed=payloadProxy,
                minLifeTime=self.minProxyTime,
                newProxyLifeTime=self.defaultProxyTime,
                proxyToConnect=pilotProxy)

        # if there is pilot proxy
        retVal = getProxyInfo(pilotProxy)
        if not retVal['OK']:
            return retVal
        pilotProxyDict = retVal['Value']

        if not 'groupProperties' in pilotProxyDict:
            self.log.error('Invalid Pilot Proxy',
                           'Group has no properties defined')
            return S_ERROR('Proxy has no group properties defined')

        pilotProps = pilotProxyDict['groupProperties']

        # if running with a pilot proxy, use it to renew the proxy of the payload
        if Properties.PILOT in pilotProps or Properties.GENERIC_PILOT in pilotProps:
            self.log.info('Using Pilot credentials to get a new payload Proxy')
            return gProxyManager.renewProxy(
                proxyToBeRenewed=payloadProxy,
                minLifeTime=self.minProxyTime,
                newProxyLifeTime=self.defaultProxyTime,
                proxyToConnect=pilotProxy)

        # if we are running with other type of proxy check if they are for the same user and group
        # and copy the pilot proxy if necessary

        self.log.info('Trying to copy pilot Proxy to get a new payload Proxy')
        pilotProxySecs = pilotProxyDict['chain'].getRemainingSecs()['Value']
        if pilotProxySecs <= payloadSecs:
            errorStr = 'Pilot Proxy is not longer than payload Proxy'
            self.log.error(errorStr)
            return S_ERROR('Can not renew by copy: %s' % errorStr)

        # check if both proxies belong to the same user and group
        pilotDN = pilotProxyDict['chain'].getIssuerCert(
        )['Value'].getSubjectDN()['Value']
        retVal = pilotProxyDict['chain'].getDIRACGroup()
        if not retVal['OK']:
            return retVal
        pilotGroup = retVal['Value']

        payloadDN = payloadProxyDict['chain'].getIssuerCert(
        )['Value'].getSubjectDN()['Value']
        retVal = payloadProxyDict['chain'].getDIRACGroup()
        if not retVal['OK']:
            return retVal
        payloadGroup = retVal['Value']
        if pilotDN != payloadDN or pilotGroup != payloadGroup:
            errorStr = 'Pilot Proxy and payload Proxy do not have same DN and Group'
            self.log.error(errorStr)
            return S_ERROR('Can not renew by copy: %s' % errorStr)

        if pilotProxyDict.get('hasVOMS', False):
            return pilotProxyDict['chain'].dumpAllToFile(payloadProxy)

        attribute = CS.getVOMSAttributeForGroup(payloadGroup)
        vo = CS.getVOMSVOForGroup(payloadGroup)

        retVal = VOMS().setVOMSAttributes(pilotProxyDict['chain'],
                                          attribute=attribute,
                                          vo=vo)
        if not retVal['OK']:
            return retVal

        chain = retVal['Value']
        return chain.dumpAllToFile(payloadProxy)
Exemplo n.º 20
0
    #uploadProxyToMyProxy( cliParams, True )
    success = uploadProxyToDIRACProxyManager(cliParams)
    if not success and cliParams.strict:
        sys.exit(1)

cliParams.setDIRACGroup(proxyInfo['group'])
#uploadProxyToMyProxy( cliParams, False )
success = uploadProxyToDIRACProxyManager(cliParams)
if not success and cliParams.strict:
    sys.exit(1)

finalChain = proxyInfo['chain']

vomsMapping = CS.getVOMSAttributeForGroup(proxyInfo['group'])
if vomsMapping:
    voms = VOMS()
    retVal = voms.setVOMSAttributes(finalChain, vomsMapping, 'vo.cta.in2p3.fr')
    if not retVal['OK']:
        #print "Cannot add voms attribute %s to proxy %s: %s" % ( attr, proxyInfo[ 'path' ], retVal[ 'Message' ] )
        print "Warning : Cannot add voms attribute %s to proxy" % (vomsMapping)
        print "          Accessing data in the grid storage from the user interface will not be possible."
        print "          The grid jobs will not be affected."
        if cliParams.strict:
            sys.exit(1)
    else:
        finalChain = retVal['Value']

retVal = finalChain.dumpAllToFile(proxyInfo['path'])
if not retVal['OK']:
    print "Cannot write proxy to file %s" % proxyInfo['path']
    sys.exit(1)