Exemple #1
0
  def __discoverExtraCredentials(self):
    """ Add extra credentials informations.
        * self.__extraCredentials
          -> if KW_EXTRA_CREDENTIALS in kwargs, we set it
          -> Otherwise, if we use the server certificate, we set it to VAL_EXTRA_CREDENTIALS_HOST
          -> If we have a delegation (see bellow), we set it to (delegatedDN, delegatedGroup)
          -> otherwise it is an empty string
        * delegation:
          -> if KW_DELEGATED_DN in kwargs, or delegatedDN in threadConfig, put in in self.kwargs
          -> if KW_DELEGATED_GROUP in kwargs or delegatedGroup in threadConfig, put it in self.kwargs
          -> If we have a delegated DN but not group, we find the corresponding group in the CS

        :return: S_OK()/S_ERROR()
    """
    # which extra credentials to use?
    self.__extraCredentials = self.VAL_EXTRA_CREDENTIALS_HOST if self.__useCertificates else ""
    if self.KW_EXTRA_CREDENTIALS in self.kwargs:
      self.__extraCredentials = self.kwargs[self.KW_EXTRA_CREDENTIALS]

    # Are we delegating something?
    delegatedDN = self.kwargs.get(self.KW_DELEGATED_DN) or self.__threadConfig.getDN()
    delegatedGroup = self.kwargs.get(self.KW_DELEGATED_GROUP) or self.__threadConfig.getGroup()
    if delegatedDN:
      self.kwargs[self.KW_DELEGATED_DN] = delegatedDN
      if not delegatedGroup:
        result = Registry.findDefaultGroupForDN(delegatedDN)
        if not result['OK']:
          return result
        delegatedGroup = result['Value']
      self.kwargs[self.KW_DELEGATED_GROUP] = delegatedGroup
      self.__extraCredentials = (delegatedDN, delegatedGroup)
    return S_OK()
Exemple #2
0
    def getUsername(self, credDict):
        """
    Discover the username associated to the DN. It will check if the selected group is valid.
    The username will be included in the credentials dictionary.

    :type  credDict: dictionary
    :param credDict: Credentials to check
    :return: Boolean specifying whether the username was found
    """
        if self.KW_DN not in credDict:
            return True
        if self.KW_GROUP not in credDict:
            result = Registry.findDefaultGroupForDN(credDict[self.KW_DN])
            if not result['OK']:
                return False
            credDict[self.KW_GROUP] = result['Value']
        credDict[self.KW_PROPERTIES] = Registry.getPropertiesForGroup(
            credDict[self.KW_GROUP], [])
        usersInGroup = Registry.getUsersInGroup(credDict[self.KW_GROUP], [])
        if not usersInGroup:
            return False
        retVal = Registry.getUsernameForDN(credDict[self.KW_DN], usersInGroup)
        if retVal['OK']:
            credDict[self.KW_USERNAME] = retVal['Value']
            return True
        return False
Exemple #3
0
    def getDIRACGroup(self, ignoreDefault=False):
        """
      Get the dirac group if present

      If no group is found in the certificate, we query the CS to get the default group
      for the given user. This can be disabled using the ignoreDefault parameter

      Note that the lookup in the CS only can work for a proxy of first generation,
      since we search based on the issuer DN

      :param ignoreDefault: if True, do not lookup the CS

      :returns: S_OK(group name/bool)
    """
        try:
            return S_OK(asn1_utils.decodeDIRACGroup(self.__certObj))
        except LookupError:
            pass

        if ignoreDefault:
            return S_OK(False)

        # And here is the flaw :)
        result = self.getIssuerDN()
        if not result['OK']:
            return result
        return Registry.findDefaultGroupForDN(result['Value'])
Exemple #4
0
def getShifterProxy(shifterType, fileName=False):
    """ This method returns a shifter's proxy

      :param str shifterType: ProductionManager / DataManager...
      :param str fileName: file name

      :return: S_OK(dict)/S_ERROR()
  """
    if fileName:
        mkDir(os.path.dirname(fileName))
    opsHelper = Operations()
    userName = opsHelper.getValue(cfgPath('Shifter', shifterType, 'User'), '')
    if not userName:
        return S_ERROR("No shifter User defined for %s" % shifterType)
    result = Registry.getDNForUsername(userName)
    if not result['OK']:
        return result
    userDN = result['Value'][0]
    result = Registry.findDefaultGroupForDN(userDN)
    if not result['OK']:
        return result
    defaultGroup = result['Value']
    userGroup = opsHelper.getValue(cfgPath('Shifter', shifterType, 'Group'),
                                   defaultGroup)
    vomsAttr = Registry.getVOMSAttributeForGroup(userGroup)
    if vomsAttr:
        gLogger.info("Getting VOMS [%s] proxy for shifter %s@%s (%s)" %
                     (vomsAttr, userName, userGroup, userDN))
        result = gProxyManager.downloadVOMSProxyToFile(userDN,
                                                       userGroup,
                                                       filePath=fileName,
                                                       requiredTimeLeft=86400,
                                                       cacheTime=86400)
    else:
        gLogger.info("Getting proxy for shifter %s@%s (%s)" %
                     (userName, userGroup, userDN))
        result = gProxyManager.downloadProxyToFile(userDN,
                                                   userGroup,
                                                   filePath=fileName,
                                                   requiredTimeLeft=86400,
                                                   cacheTime=86400)
    if not result['OK']:
        return result
    chain = result['chain']
    fileName = result['Value']
    return S_OK({
        'DN': userDN,
        'username': userName,
        'group': userGroup,
        'chain': chain,
        'proxyFile': fileName
    })
Exemple #5
0
 def getDIRACGroup( self, ignoreDefault = False ):
   """
   Get the dirac group if present
   """
   if not self.__valid:
     return S_ERROR( "No certificate loaded" )
   extList = self.__certObj.get_extensions()
   for ext in extList:
     if ext.get_sn() == "diracGroup":
       return S_OK( ext.get_value() )
   if ignoreDefault:
     return S_OK( False )
   result = self.getIssuerDN()
   if not result[ 'OK' ]:
     return result
   return Registry.findDefaultGroupForDN( result['Value'] )
Exemple #6
0
 def __auth(self, handlerRoute, group):
     """
 Authenticate request
 """
     userDN = self.getUserDN()
     if group:
         self.__credDict['group'] = group
     else:
         if userDN:
             result = Registry.findDefaultGroupForDN(userDN)
             if result['OK']:
                 self.__credDict['group'] = result['Value']
     auth = AuthManager(Conf.getAuthSectionForHandler(handlerRoute))
     ok = auth.authQuery("", self.__credDict, self.AUTH_PROPS)
     if ok and userDN:
         self.__credDict['validGroup'] = True
     return ok
 def __auth( self, handlerRoute, group ):
   """
   Authenticate request
   """
   userDN = self.getUserDN()
   if group:
     self.__credDict[ 'group' ] = group
   else:
     if userDN:
       result = Registry.findDefaultGroupForDN( userDN )
       if result[ 'OK' ]:
         self.__credDict[ 'group' ] = result[ 'Value' ]
   auth = AuthManager( Conf.getAuthSectionForHandler( handlerRoute ) )
   ok = auth.authQuery( "", self.__credDict, self.AUTH_PROPS )
   if ok and userDN:
     self.__credDict[ 'validGroup' ] = True
   return ok
Exemple #8
0
    def __auth(self, handlerRoute, group):
        """
    Authenticate request
    """
        userDN = self.getUserDN()
        if group:
            self.__credDict['group'] = group
        else:
            if userDN:
                result = Registry.findDefaultGroupForDN(userDN)
                if result['OK']:
                    self.__credDict['group'] = result['Value']
        self.__credDict['validGroup'] = False

        if type(self.AUTH_PROPS) not in (types.ListType, types.TupleType):
            self.AUTH_PROPS = [
                p.strip() for p in self.AUTH_PROPS.split(",") if p.strip()
            ]
        allAllowed = False
        for p in self.AUTH_PROPS:
            if p.lower() in ('all', 'any'):
                allAllowed = True

        auth = AuthManager(Conf.getAuthSectionForHandler(handlerRoute))
        ok = auth.authQuery("", self.__credDict, self.AUTH_PROPS)
        if ok:
            if userDN:
                self.__credDict['validGroup'] = True
                self.log.info("AUTH OK: %s by %s@%s (%s)" %
                              (handlerRoute, self.__credDict['username'],
                               self.__credDict['group'], userDN))
            else:
                self.__credDict['validDN'] = False
                self.log.info("AUTH OK: %s by visitor" % (handlerRoute))
        elif allAllowed:
            self.log.info("AUTH ALL: %s by %s" % (handlerRoute, userDN))
            ok = True
        else:
            self.log.info("AUTH KO: %s by %s@%s" %
                          (handlerRoute, userDN, group))
        return ok
Exemple #9
0
    def __auth(self, handlerRoute, group, method):
        """
    Authenticate request
    :param str handlerRoute: the name of the handler
    :param str group: DIRAC group
    :param str method: the name of the method
    :return: bool
    """
        userDN = self.getUserDN()
        if group:
            self.__credDict['group'] = group
        else:
            if userDN:
                result = Registry.findDefaultGroupForDN(userDN)
                if result['OK']:
                    self.__credDict['group'] = result['Value']
        self.__credDict['validGroup'] = False

        if type(self.AUTH_PROPS) not in (types.ListType, types.TupleType):
            self.AUTH_PROPS = [
                p.strip() for p in self.AUTH_PROPS.split(",") if p.strip()
            ]

        auth = AuthManager(Conf.getAuthSectionForHandler(handlerRoute))
        ok = auth.authQuery(method, self.__credDict, self.AUTH_PROPS)
        if ok:
            if userDN:
                self.__credDict['validGroup'] = True
                self.log.info("AUTH OK: %s by %s@%s (%s)" %
                              (handlerRoute, self.__credDict['username'],
                               self.__credDict['group'], userDN))
            else:
                self.__credDict['validDN'] = False
                self.log.info("AUTH OK: %s by visitor" % (handlerRoute))
        elif self.isTrustedHost(self.__credDict.get('DN')):
            self.log.info("Request is coming from Trusted host")
            return True
        else:
            self.log.info("AUTH KO: %s by %s@%s" %
                          (handlerRoute, userDN, group))
        return ok
Exemple #10
0
 def __auth( self, handlerRoute, methodName, group ):
   """
   Authenticate request
   """
   userDN = self.getUserDN()
   if group:
     self.__credDict[ 'group' ] = group
   else:
     if userDN:
       result = Registry.findDefaultGroupForDN( userDN )
       if result[ 'OK' ]:
         self.__credDict[ 'group' ] = result[ 'Value' ]
   auth = AuthManager( Conf.getAuthSectionForRoute( handlerRoute ) )
   try:
     defProps = getattr( self, "auth_%s" % methodName )
   except AttributeError:
     defProps = [ 'all' ]
   ok = auth.authQuery( methodName, self.__credDict, defProps )
   if ok and userDN:
     self.__credDict[ 'validGroup' ] = True
   return ok
Exemple #11
0
 def __auth(self, handlerRoute, methodName, group):
     """
 Authenticate request
 """
     userDN = self.getUserDN()
     if group:
         self.__credDict['group'] = group
     else:
         if userDN:
             result = Registry.findDefaultGroupForDN(userDN)
             if result['OK']:
                 self.__credDict['group'] = result['Value']
     auth = AuthManager(Conf.getAuthSectionForRoute(handlerRoute))
     try:
         defProps = getattr(self, "auth_%s" % methodName)
     except AttributeError:
         defProps = ['all']
     ok = auth.authQuery(methodName, self.__credDict, defProps)
     if ok and userDN:
         self.__credDict['validGroup'] = True
     return ok
Exemple #12
0
  def __auth(self, handlerRoute, group, method):
    """
    Authenticate request
    :param str handlerRoute: the name of the handler
    :param str group: DIRAC group
    :param str method: the name of the method
    :return: bool
    """
    userDN = self.getUserDN()
    if group:
      self.__credDict['group'] = group
    else:
      if userDN:
        result = Registry.findDefaultGroupForDN(userDN)
        if result['OK']:
          self.__credDict['group'] = result['Value']
    self.__credDict['validGroup'] = False

    if type(self.AUTH_PROPS) not in (types.ListType, types.TupleType):
      self.AUTH_PROPS = [p.strip() for p in self.AUTH_PROPS.split(",") if p.strip()]

    auth = AuthManager(Conf.getAuthSectionForHandler(handlerRoute))
    ok = auth.authQuery(method, self.__credDict, self.AUTH_PROPS)
    if ok:
      if userDN:
        self.__credDict['validGroup'] = True
        self.log.info("AUTH OK: %s by %s@%s (%s)" %
                      (handlerRoute, self.__credDict['username'], self.__credDict['group'], userDN))
      else:
        self.__credDict['validDN'] = False
        self.log.info("AUTH OK: %s by visitor" % (handlerRoute))
    elif self.isTrustedHost(self.__credDict.get('DN')):
      self.log.info("Request is coming from Trusted host")
      return True
    else:
      self.log.info("AUTH KO: %s by %s@%s" % (handlerRoute, userDN, group))
    return ok
Exemple #13
0
  def __auth( self, handlerRoute, group ):
    """
    Authenticate request
    """
    userDN = self.getUserDN()
    if group:
      self.__credDict[ 'group' ] = group
    else:
      if userDN:
        result = Registry.findDefaultGroupForDN( userDN )
        if result[ 'OK' ]:
          self.__credDict[ 'group' ] = result[ 'Value' ]
    self.__credDict[ 'validGroup' ] = False

    if type( self.AUTH_PROPS ) not in ( types.ListType, types.TupleType ):
      self.AUTH_PROPS = [ p.strip() for p in self.AUTH_PROPS.split( "," ) if p.strip() ]
    allAllowed = False
    for p in self.AUTH_PROPS:
      if p.lower() in ( 'all', 'any' ):
        allAllowed = True

    auth = AuthManager( Conf.getAuthSectionForHandler( handlerRoute ) )
    ok = auth.authQuery( "", self.__credDict, self.AUTH_PROPS )
    if ok:
      if userDN:
        self.__credDict[ 'validGroup' ] = True
        self.log.info( "AUTH OK: %s by %s@%s (%s)" % ( handlerRoute, self.__credDict[ 'username' ], self.__credDict[ 'group' ], userDN ) )
      else:
        self.__credDict[ 'validDN' ] = False
        self.log.info( "AUTH OK: %s by visitor" % ( handlerRoute ) )
    elif allAllowed:
      self.log.info( "AUTH ALL: %s by %s" % ( handlerRoute, userDN ) )
      ok = True
    else:
      self.log.info( "AUTH KO: %s by %s@%s" % ( handlerRoute, userDN, group ) )
    return ok
def generateProxy( params ):

  if params.checkClock:
    result = getClockDeviation()
    if result[ 'OK' ]:
      deviation = result[ 'Value' ]
      if deviation > 600:
        gLogger.error( "Your host clock seems to be off by more than TEN MINUTES! Thats really bad." )
        gLogger.error( "We're cowardly refusing to generate a proxy. Please fix your system time" )
        sys.exit( 1 )
      elif deviation > 180:
        gLogger.error( "Your host clock seems to be off by more than THREE minutes! Thats bad." )
        gLogger.notice( "We'll generate the proxy but please fix your system time" )
      elif deviation > 60:
        gLogger.error( "Your host clock seems to be off by more than a minute! Thats not good." )
        gLogger.notice( "We'll generate the proxy but please fix your system time" )

  certLoc = params.certLoc
  keyLoc = params.keyLoc
  if not certLoc or not keyLoc:
    cakLoc = Locations.getCertificateAndKeyLocation()
    if not cakLoc:
      return S_ERROR( "Can't find user certificate and key" )
    if not certLoc:
      certLoc = cakLoc[0]
    if not keyLoc:
      keyLoc = cakLoc[1]
  params.certLoc = certLoc
  params.keyLoc = keyLoc

  #Load password
  testChain = X509Chain()
  retVal = testChain.loadChainFromFile( params.certLoc )
  if not retVal[ 'OK' ]:
    return S_ERROR( "Cannot load certificate %s: %s" % ( params.certLoc, retVal[ 'Message' ] ) )
  timeLeft = testChain.getRemainingSecs()[ 'Value' ] / 86400
  if timeLeft < 30:
    gLogger.notice( "\nYour certificate will expire in %d days. Please renew it!\n" % timeLeft )
  retVal = testChain.loadKeyFromFile( params.keyLoc, password = params.userPasswd )
  if not retVal[ 'OK' ]:
    passwdPrompt = "Enter Certificate password:"******"\n" )
    else:
      userPasswd = getpass.getpass( passwdPrompt )
    params.userPasswd = userPasswd

  #Find location
  proxyLoc = params.proxyLoc
  if not proxyLoc:
    proxyLoc = Locations.getDefaultProxyLocation()

  chain = X509Chain()
  #Load user cert and key
  retVal = chain.loadChainFromFile( certLoc )
  if not retVal[ 'OK' ]:
    gLogger.warn( retVal[ 'Message' ] )
    return S_ERROR( "Can't load %s" % certLoc )
  retVal = chain.loadKeyFromFile( keyLoc, password = params.userPasswd )
  if not retVal[ 'OK' ]:
    gLogger.warn( retVal[ 'Message' ] )
    if 'bad decrypt' in retVal[ 'Message' ]:
      return S_ERROR( "Bad passphrase" )
    return S_ERROR( "Can't load %s" % keyLoc )

  if params.checkWithCS:
    retVal = chain.generateProxyToFile( proxyLoc,
                                        params.proxyLifeTime,
                                        strength = params.proxyStrength,
                                        limited = params.limitedProxy,
                                        rfc = params.rfc )

    gLogger.info( "Contacting CS..." )
    retVal = Script.enableCS()
    if not retVal[ 'OK' ]:
      gLogger.warn( retVal[ 'Message' ] )
      if 'Unauthorized query' in retVal[ 'Message' ]:
        # add hint for users
        return S_ERROR( "Can't contact DIRAC CS: %s (User possibly not registered with dirac server) "
                        % retVal[ 'Message' ] )
      return S_ERROR( "Can't contact DIRAC CS: %s" % retVal[ 'Message' ] )
    userDN = chain.getCertInChain( -1 )['Value'].getSubjectDN()['Value']
    if not params.diracGroup:
      result = Registry.findDefaultGroupForDN( userDN )
      if not result[ 'OK' ]:
        gLogger.warn( "Could not get a default group for DN %s: %s" % ( userDN, result[ 'Message' ] ) )
      else:
        params.diracGroup = result[ 'Value' ]
        gLogger.info( "Default discovered group is %s" % params.diracGroup )
    gLogger.info( "Checking DN %s" % userDN )
    retVal = Registry.getUsernameForDN( userDN )
    if not retVal[ 'OK' ]:
      gLogger.warn( retVal[ 'Message' ] )
      return S_ERROR( "DN %s is not registered" % userDN )
    username = retVal[ 'Value' ]
    gLogger.info( "Username is %s" % username )
    retVal = Registry.getGroupsForUser( username )
    if not retVal[ 'OK' ]:
      gLogger.warn( retVal[ 'Message' ] )
      return S_ERROR( "User %s has no groups defined" % username )
    groups = retVal[ 'Value' ]
    if params.diracGroup not in groups:
      return S_ERROR( "Requested group %s is not valid for DN %s" % ( params.diracGroup, userDN ) )
    gLogger.info( "Creating proxy for %s@%s (%s)" % ( username, params.diracGroup, userDN ) )

  if params.summary:
    h = int( params.proxyLifeTime / 3600 )
    m = int( params.proxyLifeTime / 60 ) - h * 60
    gLogger.notice( "Proxy lifetime will be %02d:%02d" % ( h, m ) )
    gLogger.notice( "User cert is %s" % certLoc )
    gLogger.notice( "User key  is %s" % keyLoc )
    gLogger.notice( "Proxy will be written to %s" % proxyLoc )
    if params.diracGroup:
      gLogger.notice( "DIRAC Group will be set to %s" % params.diracGroup )
    else:
      gLogger.notice( "No DIRAC Group will be set" )
    gLogger.notice( "Proxy strength will be %s" % params.proxyStrength )
    if params.limitedProxy:
      gLogger.notice( "Proxy will be limited" )

  retVal = chain.generateProxyToFile( proxyLoc,
                                      params.proxyLifeTime,
                                      params.diracGroup,
                                      strength = params.proxyStrength,
                                      limited = params.limitedProxy,
                                      rfc = params.rfc )

  if not retVal[ 'OK' ]:
    gLogger.warn( retVal[ 'Message' ] )
    return S_ERROR( "Couldn't generate proxy: %s" % retVal[ 'Message' ] )
  return S_OK( proxyLoc )
Exemple #15
0
    def authQuery(self, methodQuery, credDict, defaultProperties=False):
        """
    Check if the query is authorized for a credentials dictionary

    :type  methodQuery: string
    :param methodQuery: Method to test
    :type  credDict: dictionary
    :param credDict: dictionary containing credentials for test. The dictionary can contain the DN
                        and selected group.
    :return: Boolean result of test
    """
        userString = ""
        if self.KW_DN in credDict:
            userString += "DN=%s" % credDict[self.KW_DN]
        if self.KW_GROUP in credDict:
            userString += " group=%s" % credDict[self.KW_GROUP]
        if self.KW_EXTRA_CREDENTIALS in credDict:
            userString += " extraCredentials=%s" % str(
                credDict[self.KW_EXTRA_CREDENTIALS])
        self.__authLogger.debug("Trying to authenticate %s" % userString)
        # Get properties
        requiredProperties = self.getValidPropertiesForMethod(
            methodQuery, defaultProperties)
        # Extract valid groups
        validGroups = self.getValidGroups(requiredProperties)
        lowerCaseProperties = [prop.lower() for prop in requiredProperties]
        if not lowerCaseProperties:
            lowerCaseProperties = ['any']

        allowAll = "any" in lowerCaseProperties or "all" in lowerCaseProperties
        # Set no properties by default
        credDict[self.KW_PROPERTIES] = []
        # Check non secure backends
        if self.KW_DN not in credDict or not credDict[self.KW_DN]:
            if allowAll and not validGroups:
                self.__authLogger.debug(
                    "Accepted request from unsecure transport")
                return True
            else:
                self.__authLogger.debug(
                    "Explicit property required and query seems to be coming through an unsecure transport"
                )
                return False
        # Check if query comes though a gateway/web server
        if self.forwardedCredentials(credDict):
            self.__authLogger.debug("Query comes from a gateway")
            self.unpackForwardedCredentials(credDict)
            return self.authQuery(methodQuery, credDict, requiredProperties)
        # Get the properties
        # Check for invalid forwarding
        if self.KW_EXTRA_CREDENTIALS in credDict:
            # Invalid forwarding?
            if not isinstance(credDict[self.KW_EXTRA_CREDENTIALS], basestring):
                self.__authLogger.debug(
                    "The credentials seem to be forwarded by a host, but it is not a trusted one"
                )
                return False
        # Is it a host?
        if self.KW_EXTRA_CREDENTIALS in credDict and credDict[
                self.KW_EXTRA_CREDENTIALS] == self.KW_HOSTS_GROUP:
            # Get the nickname of the host
            credDict[self.KW_GROUP] = credDict[self.KW_EXTRA_CREDENTIALS]
        # HACK TO MAINTAIN COMPATIBILITY
        else:
            if self.KW_EXTRA_CREDENTIALS in credDict and self.KW_GROUP not in credDict:
                credDict[self.KW_GROUP] = credDict[self.KW_EXTRA_CREDENTIALS]
        # END OF HACK
        # Get the username
        if self.KW_DN in credDict and credDict[self.KW_DN]:
            if self.KW_GROUP not in credDict:
                result = Registry.findDefaultGroupForDN(credDict[self.KW_DN])
                if not result['OK']:
                    credDict[self.KW_USERNAME] = "anonymous"
                    credDict[self.KW_GROUP] = "visitor"
                else:
                    credDict[self.KW_GROUP] = result['Value']
            if credDict[self.KW_GROUP] == self.KW_HOSTS_GROUP:
                # For host
                if not self.getHostNickName(credDict):
                    self.__authLogger.warn("Host is invalid")
                    if not allowAll:
                        return False
                    # If all, then set anon credentials
                    credDict[self.KW_USERNAME] = "anonymous"
                    credDict[self.KW_GROUP] = "visitor"
            else:
                # For users
                username = self.getUsername(credDict)
                suspended = self.isUserSuspended(credDict)
                if not username:
                    self.__authLogger.warn(
                        "User is invalid or does not belong to the group it's saying"
                    )
                if suspended:
                    self.__authLogger.warn("User is Suspended")

                if not username or suspended:
                    if not allowAll:
                        return False
                    # If all, then set anon credentials
                    credDict[self.KW_USERNAME] = "anonymous"
                    credDict[self.KW_GROUP] = "visitor"
        else:
            if not allowAll:
                return False
            credDict[self.KW_USERNAME] = "anonymous"
            credDict[self.KW_GROUP] = "visitor"

        # If any or all in the props, allow
        allowGroup = not validGroups or credDict[self.KW_GROUP] in validGroups
        if allowAll and allowGroup:
            return True
        # Check authorized groups
        if "authenticated" in lowerCaseProperties and allowGroup:
            return True
        if not self.matchProperties(credDict, requiredProperties):
            self.__authLogger.warn(
                "Client is not authorized\nValid properties: %s\nClient: %s" %
                (requiredProperties, credDict))
            return False
        elif not allowGroup:
            self.__authLogger.warn(
                "Client is not authorized\nValid groups: %s\nClient: %s" %
                (validGroups, credDict))
            return False
        return True
def generateProxy(params):

    if params.checkClock:
        result = getClockDeviation()
        if result['OK']:
            deviation = result['Value']
            if deviation > 600:
                gLogger.error(
                    "Your host clock seems to be off by more than TEN MINUTES! Thats really bad."
                )
                gLogger.error(
                    "We're cowardly refusing to generate a proxy. Please fix your system time"
                )
                sys.exit(1)
            elif deviation > 180:
                gLogger.error(
                    "Your host clock seems to be off by more than THREE minutes! Thats bad."
                )
                gLogger.notice(
                    "We'll generate the proxy but please fix your system time")
            elif deviation > 60:
                gLogger.error(
                    "Your host clock seems to be off by more than a minute! Thats not good."
                )
                gLogger.notice(
                    "We'll generate the proxy but please fix your system time")

    certLoc = params.certLoc
    keyLoc = params.keyLoc
    if not certLoc or not keyLoc:
        cakLoc = Locations.getCertificateAndKeyLocation()
        if not cakLoc:
            return S_ERROR("Can't find user certificate and key")
        if not certLoc:
            certLoc = cakLoc[0]
        if not keyLoc:
            keyLoc = cakLoc[1]
    params.certLoc = certLoc
    params.keyLoc = keyLoc

    #Load password
    testChain = X509Chain()
    retVal = testChain.loadChainFromFile(params.certLoc)
    if not retVal['OK']:
        return S_ERROR("Cannot load certificate %s: %s" %
                       (params.certLoc, retVal['Message']))
    timeLeft = testChain.getRemainingSecs()['Value'] / 86400
    if timeLeft < 30:
        gLogger.notice(
            "\nYour certificate will expire in %d days. Please renew it!\n" %
            timeLeft)
    retVal = testChain.loadKeyFromFile(params.keyLoc,
                                       password=params.userPasswd)
    if not retVal['OK']:
        passwdPrompt = "Enter Certificate password:"******"\n")
        else:
            userPasswd = getpass.getpass(passwdPrompt)
        params.userPasswd = userPasswd

    #Find location
    proxyLoc = params.proxyLoc
    if not proxyLoc:
        proxyLoc = Locations.getDefaultProxyLocation()

    chain = X509Chain()
    #Load user cert and key
    retVal = chain.loadChainFromFile(certLoc)
    if not retVal['OK']:
        gLogger.warn(retVal['Message'])
        return S_ERROR("Can't load %s" % certLoc)
    retVal = chain.loadKeyFromFile(keyLoc, password=params.userPasswd)
    if not retVal['OK']:
        gLogger.warn(retVal['Message'])
        if 'bad decrypt' in retVal['Message']:
            return S_ERROR("Bad passphrase")
        return S_ERROR("Can't load %s" % keyLoc)

    if params.checkWithCS:
        retVal = chain.generateProxyToFile(proxyLoc,
                                           params.proxyLifeTime,
                                           strength=params.proxyStrength,
                                           limited=params.limitedProxy)

        gLogger.info("Contacting CS...")
        retVal = Script.enableCS()
        if not retVal['OK']:
            gLogger.warn(retVal['Message'])
            if 'Unauthorized query' in retVal['Message']:
                # add hint for users
                return S_ERROR(
                    "Can't contact DIRAC CS: %s (User possibly not registered with dirac server) "
                    % retVal['Message'])
            return S_ERROR("Can't contact DIRAC CS: %s" % retVal['Message'])
        userDN = chain.getCertInChain(-1)['Value'].getSubjectDN()['Value']
        if not params.diracGroup:
            result = Registry.findDefaultGroupForDN(userDN)
            if not result['OK']:
                gLogger.warn("Could not get a default group for DN %s: %s" %
                             (userDN, result['Message']))
            else:
                params.diracGroup = result['Value']
                gLogger.info("Default discovered group is %s" %
                             params.diracGroup)
        gLogger.info("Checking DN %s" % userDN)
        retVal = Registry.getUsernameForDN(userDN)
        if not retVal['OK']:
            gLogger.warn(retVal['Message'])
            return S_ERROR("DN %s is not registered" % userDN)
        username = retVal['Value']
        gLogger.info("Username is %s" % username)
        retVal = Registry.getGroupsForUser(username)
        if not retVal['OK']:
            gLogger.warn(retVal['Message'])
            return S_ERROR("User %s has no groups defined" % username)
        groups = retVal['Value']
        if params.diracGroup not in groups:
            return S_ERROR("Requested group %s is not valid for DN %s" %
                           (params.diracGroup, userDN))
        gLogger.info("Creating proxy for %s@%s (%s)" %
                     (username, params.diracGroup, userDN))

    if params.summary:
        h = int(params.proxyLifeTime / 3600)
        m = int(params.proxyLifeTime / 60) - h * 60
        gLogger.notice("Proxy lifetime will be %02d:%02d" % (h, m))
        gLogger.notice("User cert is %s" % certLoc)
        gLogger.notice("User key  is %s" % keyLoc)
        gLogger.notice("Proxy will be written to %s" % proxyLoc)
        if params.diracGroup:
            gLogger.notice("DIRAC Group will be set to %s" % params.diracGroup)
        else:
            gLogger.notice("No DIRAC Group will be set")
        gLogger.notice("Proxy strength will be %s" % params.proxyStrength)
        if params.limitedProxy:
            gLogger.notice("Proxy will be limited")

    retVal = chain.generateProxyToFile(proxyLoc,
                                       params.proxyLifeTime,
                                       params.diracGroup,
                                       strength=params.proxyStrength,
                                       limited=params.limitedProxy)

    if not retVal['OK']:
        gLogger.warn(retVal['Message'])
        return S_ERROR("Couldn't generate proxy: %s" % retVal['Message'])
    return S_OK(proxyLoc)