예제 #1
0
def main():
    userParams = Params()
    userParams.registerCLISwitches()

    # Check time
    deviation = getClockDeviation()
    if not deviation["OK"]:
        gLogger.warn(deviation["Message"])
    elif deviation["Value"] > 60:
        gLogger.fatal(f"Your host's clock seems to deviate by {(int(deviation['Value']) / 60):.0f} minutes!")
        sys.exit(1)

    Script.disableCS()
    Script.parseCommandLine(ignoreErrors=True)
    # It's server installation?
    if gConfig.useServerCertificate():
        # In this case you do not need to login.
        gLogger.notice("You should not need to run this command in a DIRAC server. Exiting.")
        DIRAC.exit(1)

    userParams.group, userParams.scopes = Script.getPositionalArgs(group=True)
    # If you have chosen to use a certificate then a proxy will be generated locally using the specified certificate
    if userParams.authWith == "certificate":
        result = userParams.loginWithCertificate()

    # Otherwise, you must log in to the authorization server to gain access
    else:
        result = userParams.doOAuthMagic()

    # Print authorization status
    if result["OK"] and userParams.enableCS:
        result = userParams.getAuthStatus()

    if not result["OK"]:
        print(HTML(f"<red>{result['Message']}</red>"))
        sys.exit(1)

    userParams.howToSwitch()
    sys.exit(0)
예제 #2
0
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 )
예제 #3
0
from DIRAC.Core.Security.ProxyInfo import getProxyInfo, getProxyStepsInfo, formatProxyInfoAsString, formatProxyStepsInfoAsString
from DIRAC.Core.Security import VOMS
from DIRAC.FrameworkSystem.Client.ProxyManagerClient import gProxyManager
from DIRAC.ConfigurationSystem.Client.Helpers import Registry


__RCSID__ = "$Id$"


if params.csEnabled:
  retVal = Script.enableCS()
  if not retVal[ 'OK' ]:
    print "Cannot contact CS to get user list"

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." )
    elif deviation > 180:
      gLogger.error( "Your host clock seems to be off by more than THREE minutes! Thats bad." )
    elif deviation > 60:
      gLogger.error( "Your host clock seems to be off by more than a minute! Thats not good." )


result = getProxyInfo( params.proxyLoc, not params.vomsEnabled )
if not result[ 'OK' ]:
  gLogger.error( result[ 'Message' ] )
  sys.exit( 1 )
infoDict = result[ 'Value' ]
예제 #4
0
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)
예제 #5
0
def main():
    params = Params()

    Script.registerSwitch("f:", "file=", "File to use as user key", params.setProxyLocation)
    Script.registerSwitch("i", "version", "Print version", params.showVersion)
    Script.registerSwitch("n", "novoms", "Disable VOMS", params.disableVOMS)
    Script.registerSwitch("v", "checkvalid", "Return error if the proxy is invalid", params.validityCheck)
    Script.registerSwitch("x", "nocs", "Disable CS", params.disableCS)
    Script.registerSwitch("e", "steps", "Show steps info", params.showSteps)
    Script.registerSwitch("j", "noclockcheck", "Disable checking if time is ok", params.disableClockCheck)
    Script.registerSwitch("m", "uploadedinfo", "Show uploaded proxies info", params.setManagerInfo)

    Script.disableCS()
    Script.parseCommandLine()

    from DIRAC.Core.Utilities.NTP import getClockDeviation
    from DIRAC import gLogger
    from DIRAC.Core.Security.ProxyInfo import getProxyInfo, getProxyStepsInfo
    from DIRAC.Core.Security.ProxyInfo import formatProxyInfoAsString, formatProxyStepsInfoAsString
    from DIRAC.Core.Security import VOMS
    from DIRAC.FrameworkSystem.Client.ProxyManagerClient import gProxyManager
    from DIRAC.ConfigurationSystem.Client.Helpers import Registry

    if params.csEnabled:
        retVal = Script.enableCS()
        if not retVal["OK"]:
            print("Cannot contact CS to get user list")

    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.")
            elif deviation > 180:
                gLogger.error("Your host clock seems to be off by more than THREE minutes! Thats bad.")
            elif deviation > 60:
                gLogger.error("Your host clock seems to be off by more than a minute! Thats not good.")

    result = getProxyInfo(params.proxyLoc, not params.vomsEnabled)
    if not result["OK"]:
        gLogger.error(result["Message"])
        sys.exit(1)
    infoDict = result["Value"]
    gLogger.notice(formatProxyInfoAsString(infoDict))
    if not infoDict["isProxy"]:
        gLogger.error("==============================\n!!! The proxy is not valid !!!")

    if params.steps:
        gLogger.notice("== Steps extended info ==")
        chain = infoDict["chain"]
        stepInfo = getProxyStepsInfo(chain)["Value"]
        gLogger.notice(formatProxyStepsInfoAsString(stepInfo))

    def invalidProxy(msg):
        gLogger.error("Invalid proxy:", msg)
        sys.exit(1)

    if params.uploadedInfo:
        result = gProxyManager.getUserProxiesInfo()
        if not result["OK"]:
            gLogger.error("Could not retrieve the uploaded proxies info", result["Message"])
        else:
            uploadedInfo = result["Value"]
            if not uploadedInfo:
                gLogger.notice("== No proxies uploaded ==")
            if uploadedInfo:
                gLogger.notice("== Proxies uploaded ==")
                maxDNLen = 0
                maxGroupLen = 0
                for userDN in uploadedInfo:
                    maxDNLen = max(maxDNLen, len(userDN))
                    for group in uploadedInfo[userDN]:
                        maxGroupLen = max(maxGroupLen, len(group))
                gLogger.notice(" %s | %s | Until (GMT)" % ("DN".ljust(maxDNLen), "Group".ljust(maxGroupLen)))
                for userDN in uploadedInfo:
                    for group in uploadedInfo[userDN]:
                        gLogger.notice(
                            " %s | %s | %s"
                            % (
                                userDN.ljust(maxDNLen),
                                group.ljust(maxGroupLen),
                                uploadedInfo[userDN][group].strftime("%Y/%m/%d %H:%M"),
                            )
                        )

    if params.checkValid:
        if infoDict["secondsLeft"] == 0:
            invalidProxy("Proxy is expired")
        if params.csEnabled and not infoDict["validGroup"]:
            invalidProxy("Group %s is not valid" % infoDict["group"])
        if "hasVOMS" in infoDict and infoDict["hasVOMS"]:
            requiredVOMS = Registry.getVOMSAttributeForGroup(infoDict["group"])
            if "VOMS" not in infoDict or not infoDict["VOMS"]:
                invalidProxy("Unable to retrieve VOMS extension")
            if len(infoDict["VOMS"]) > 1:
                invalidProxy("More than one voms attribute found")
            if requiredVOMS not in infoDict["VOMS"]:
                invalidProxy(
                    "Unexpected VOMS extension %s. Extension expected for DIRAC group is %s"
                    % (infoDict["VOMS"][0], requiredVOMS)
                )
            result = VOMS.VOMS().getVOMSProxyInfo(infoDict["chain"], "actimeleft")
            if not result["OK"]:
                invalidProxy("Cannot determine life time of VOMS attributes: %s" % result["Message"])
            if int(result["Value"].strip()) == 0:
                invalidProxy("VOMS attributes are expired")

    sys.exit(0)
예제 #6
0
def generateProxy(params):

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

    testChain = X509Chain()
    retVal = testChain.loadKeyFromFile(keyLoc, password=params.userPasswd)
    if not retVal['OK']:
        passwdPrompt = "Enter Certificate password:"******"\n")
        else:
            userPasswd = getpass.getpass(passwdPrompt)
        params.userPasswd = userPasswd

    proxyLoc = params.proxyLoc
    if not proxyLoc:
        proxyLoc = Locations.getDefaultProxyLocation()

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

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

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

        params.debugMsg("Contacting CS...")

        retVal = Script.enableCS()
        if not retVal['OK']:
            params.debugMsg("ERROR: %s" % retVal['Message'])
            return S_ERROR("Can't contact DIRAC CS: %s" % retVal['Message'])
        if not params.diracGroup:
            params.diracGroup = CS.getDefaultUserGroup()
        userDN = chain.getCertInChain(-1)['Value'].getSubjectDN()['Value']
        params.debugMsg("Checking DN %s" % userDN)
        retVal = CS.getUsernameForDN(userDN)
        if not retVal['OK']:
            params.debugMsg("ERROR: %s" % retVal['Message'])
            return S_ERROR("DN %s is not registered" % userDN)
        username = retVal['Value']
        params.debugMsg("Username is %s" % username)
        retVal = CS.getGroupsForUser(username)
        if not retVal['OK']:
            params.debugMsg("ERROR: %s" % 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 user %s" %
                           (params.diracGroup, username))
        params.debugMsg("Creating proxy for %s@%s (%s)" %
                        (username, params.diracGroup, userDN))

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

    if not retVal['OK']:
        params.debugMsg("ERROR: %s" % retVal['Message'])
        return S_ERROR("Couldn't generate proxy: %s" % retVal['Message'])
    return S_OK(proxyLoc)
예제 #7
0
from DIRAC.Core.Utilities.NTP import getClockDeviation
from DIRAC import gLogger
from DIRAC.Core.Security.ProxyInfo import getProxyInfo, getProxyStepsInfo, formatProxyInfoAsString, formatProxyStepsInfoAsString
from DIRAC.Core.Security import VOMS
from DIRAC.FrameworkSystem.Client.ProxyManagerClient import gProxyManager
from DIRAC.ConfigurationSystem.Client.Helpers import Registry

__RCSID__ = "$Id$"

if params.csEnabled:
    retVal = Script.enableCS()
    if not retVal['OK']:
        print "Cannot contact CS to get user list"

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."
            )
        elif deviation > 180:
            gLogger.error(
                "Your host clock seems to be off by more than THREE minutes! Thats bad."
            )
        elif deviation > 60:
            gLogger.error(
                "Your host clock seems to be off by more than a minute! Thats not good."
            )
예제 #8
0
def generateProxy( params ):

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

  testChain = X509Chain()
  retVal = testChain.loadKeyFromFile( keyLoc, password = params.userPasswd )
  if not retVal[ 'OK' ]:
    passwdPrompt = "Enter Certificate password:"******"\n" )
    else:
      userPasswd = getpass.getpass( passwdPrompt )
    params.userPasswd = userPasswd

  proxyLoc = params.proxyLoc
  if not proxyLoc:
    proxyLoc = Locations.getDefaultProxyLocation()

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

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

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

    params.debugMsg( "Contacting CS..." )

    retVal = Script.enableCS()
    if not retVal[ 'OK' ]:
      params.debugMsg( "ERROR: %s" % retVal[ 'Message' ] )
      return S_ERROR( "Can't contact DIRAC CS: %s" % retVal[ 'Message' ] )
    if not params.diracGroup:
      params.diracGroup = CS.getDefaultUserGroup()
    userDN = chain.getCertInChain( -1 )['Value'].getSubjectDN()['Value']
    params.debugMsg( "Checking DN %s" % userDN )
    retVal = CS.getUsernameForDN( userDN )
    if not retVal[ 'OK' ]:
      params.debugMsg( "ERROR: %s" % retVal[ 'Message' ] )
      return S_ERROR( "DN %s is not registered" % userDN )
    username = retVal[ 'Value' ]
    params.debugMsg( "Username is %s" % username )
    retVal = CS.getGroupsForUser( username )
    if not retVal[ 'OK' ]:
      params.debugMsg( "ERROR: %s" % 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 user %s" % ( params.diracGroup, username ) )
    params.debugMsg( "Creating proxy for %s@%s (%s)" % ( username, params.diracGroup, userDN ) )

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

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