def doOAuthMagic(self): """ Magic method :return: S_OK()/S_ERROR() """ nAuth = notebookAuth(self.__piParams.diracGroup, voms=self.__piParams.addVOMSExt, proxyPath=self.__piParams.proxyLoc) result = nAuth.getToken() if not result['OK']: return result aToken = result['Value'].get('access_token') if not aToken: return S_ERROR('Access token is absent in resporse.') result = nAuth.getProxyWithToken(aToken) if not result['OK']: return result result = Script.enableCS() if not result['OK']: return S_ERROR("Cannot contact CS to get user list") threading.Thread(target=self.checkCAs).start() gConfig.forceRefresh(fromMaster=True) return S_OK(self.__piParams.proxyLoc)
host = DIRAC.gConfig.getValue(cfgInstallPath("Host"), "") if host: DIRAC.gConfig.setOptionValue(cfgPath("DIRAC", "Hostname"), host) if skipCAChecks: DIRAC.gLogger.verbose('/DIRAC/Security/SkipCAChecks =', 'yes') #Being sure it was not there before Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks') Script.localCfg.addDefaultEntry('/DIRAC/Security/SkipCAChecks', 'yes') else: # Necessary to allow initial download of CA's if not skipCADownload: DIRAC.gConfig.setOptionValue('/DIRAC/Security/SkipCAChecks', 'yes') if not skipCADownload: Script.enableCS() try: dirName = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'certificates') if not os.path.exists(dirName): os.makedirs(dirName) except: DIRAC.gLogger.exception() DIRAC.gLogger.fatal('Fail to create directory:', dirName) DIRAC.exit(-1) try: from DIRAC.FrameworkSystem.Client.BundleDeliveryClient import BundleDeliveryClient bdc = BundleDeliveryClient() result = bdc.syncCAs() if result['OK']: result = bdc.syncCRLs()
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 )
Script.disableCS() Script.parseCommandLine() 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." )
params = Params( ) Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1], 'Usage:', ' %s [options] [section[.option[=value]]]...' % Script.scriptName, 'Arguments:', ' section: display all options in section', '++ OR ++', ' section.option: display option', '++ OR ++', ' section.option=value: set option value',] ) ) Script.registerSwitch( "m", "minimal", "verify and fill minimal configuration", params.setMinimal ) Script.enableCS( ) Script.parseCommandLine( ignoreErrors = True ) args = Script.getPositionalArgs() if params.minimal: createMinimalConfig( ) dconfig = DConfig( ) modified = False for arg in args: value = None section = None option = None
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)
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)
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, 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." )
def main(): global logLevel global setup global configurationServer global includeAllServers global gatewayServer global siteName global useServerCert global skipCAChecks global skipCADownload global useVersionsDir global architecture global localSE global ceName global vo global update global outputFile global skipVOMSDownload global extensions Script.disableCS() Script.registerSwitch("S:", "Setup=", "Set <setup> as DIRAC setup", setSetup) Script.registerSwitch("e:", "Extensions=", "Set <extensions> as DIRAC extensions", setExtensions) Script.registerSwitch("C:", "ConfigurationServer=", "Set <server> as DIRAC configuration server", setServer) Script.registerSwitch("I", "IncludeAllServers", "include all Configuration Servers", setAllServers) Script.registerSwitch("n:", "SiteName=", "Set <sitename> as DIRAC Site Name", setSiteName) Script.registerSwitch("N:", "CEName=", "Determiner <sitename> from <cename>", setCEName) Script.registerSwitch("V:", "VO=", "Set the VO name", setVO) Script.registerSwitch("W:", "gateway=", "Configure <gateway> as DIRAC Gateway for the site", setGateway) Script.registerSwitch("U", "UseServerCertificate", "Configure to use Server Certificate", setServerCert) Script.registerSwitch("H", "SkipCAChecks", "Configure to skip check of CAs", setSkipCAChecks) Script.registerSwitch("D", "SkipCADownload", "Configure to skip download of CAs", setSkipCADownload) Script.registerSwitch("M", "SkipVOMSDownload", "Configure to skip download of VOMS info", setSkipVOMSDownload) Script.registerSwitch("v", "UseVersionsDir", "Use versions directory", setUseVersionsDir) Script.registerSwitch("A:", "Architecture=", "Configure /Architecture=<architecture>", setArchitecture) Script.registerSwitch("L:", "LocalSE=", "Configure LocalSite/LocalSE=<localse>", setLocalSE) Script.registerSwitch( "F", "ForceUpdate", "Force Update of cfg file (i.e. dirac.cfg) (otherwise nothing happens if dirac.cfg already exists)", forceUpdate) Script.registerSwitch("O:", "output=", "output configuration file", setOutput) Script.setUsageMessage('\n'.join([ __doc__.split('\n')[1], '\nUsage:', ' %s [options] ...\n' % Script.scriptName ])) Script.parseCommandLine(ignoreErrors=True) args = Script.getExtraCLICFGFiles() if not logLevel: logLevel = DIRAC.gConfig.getValue(cfgInstallPath('LogLevel'), '') if logLevel: DIRAC.gLogger.setLevel(logLevel) else: DIRAC.gConfig.setOptionValue(cfgInstallPath('LogLevel'), logLevel) if not gatewayServer: newGatewayServer = DIRAC.gConfig.getValue(cfgInstallPath('Gateway'), '') if newGatewayServer: setGateway(newGatewayServer) if not configurationServer: newConfigurationServer = DIRAC.gConfig.getValue( cfgInstallPath('ConfigurationServer'), '') if newConfigurationServer: setServer(newConfigurationServer) if not includeAllServers: newIncludeAllServer = DIRAC.gConfig.getValue( cfgInstallPath('IncludeAllServers'), False) if newIncludeAllServer: setAllServers(True) if not setup: newSetup = DIRAC.gConfig.getValue(cfgInstallPath('Setup'), '') if newSetup: setSetup(newSetup) if not siteName: newSiteName = DIRAC.gConfig.getValue(cfgInstallPath('SiteName'), '') if newSiteName: setSiteName(newSiteName) if not ceName: newCEName = DIRAC.gConfig.getValue(cfgInstallPath('CEName'), '') if newCEName: setCEName(newCEName) if not useServerCert: newUserServerCert = DIRAC.gConfig.getValue( cfgInstallPath('UseServerCertificate'), False) if newUserServerCert: setServerCert(newUserServerCert) if not skipCAChecks: newSkipCAChecks = DIRAC.gConfig.getValue( cfgInstallPath('SkipCAChecks'), False) if newSkipCAChecks: setSkipCAChecks(newSkipCAChecks) if not skipCADownload: newSkipCADownload = DIRAC.gConfig.getValue( cfgInstallPath('SkipCADownload'), False) if newSkipCADownload: setSkipCADownload(newSkipCADownload) if not useVersionsDir: newUseVersionsDir = DIRAC.gConfig.getValue( cfgInstallPath('UseVersionsDir'), False) if newUseVersionsDir: setUseVersionsDir(newUseVersionsDir) # Set proper Defaults in configuration (even if they will be properly overwrite by gComponentInstaller instancePath = os.path.dirname(os.path.dirname(DIRAC.rootPath)) rootPath = os.path.join(instancePath, 'pro') DIRAC.gConfig.setOptionValue(cfgInstallPath('InstancePath'), instancePath) DIRAC.gConfig.setOptionValue(cfgInstallPath('RootPath'), rootPath) if not architecture: newArchitecture = DIRAC.gConfig.getValue( cfgInstallPath('Architecture'), '') if newArchitecture: setArchitecture(newArchitecture) if not vo: newVO = DIRAC.gConfig.getValue(cfgInstallPath('VirtualOrganization'), '') if newVO: setVO(newVO) if not extensions: newExtensions = DIRAC.gConfig.getValue(cfgInstallPath('Extensions'), '') if newExtensions: setExtensions(newExtensions) DIRAC.gLogger.notice('Executing: %s ' % (' '.join(sys.argv))) DIRAC.gLogger.notice('Checking DIRAC installation at "%s"' % DIRAC.rootPath) if update: if outputFile: DIRAC.gLogger.notice('Will update the output file %s' % outputFile) else: DIRAC.gLogger.notice('Will update %s' % DIRAC.gConfig.diracConfigFilePath) if setup: DIRAC.gLogger.verbose('/DIRAC/Setup =', setup) if vo: DIRAC.gLogger.verbose('/DIRAC/VirtualOrganization =', vo) if configurationServer: DIRAC.gLogger.verbose('/DIRAC/Configuration/Servers =', configurationServer) if siteName: DIRAC.gLogger.verbose('/LocalSite/Site =', siteName) if architecture: DIRAC.gLogger.verbose('/LocalSite/Architecture =', architecture) if localSE: DIRAC.gLogger.verbose('/LocalSite/localSE =', localSE) if not useServerCert: DIRAC.gLogger.verbose('/DIRAC/Security/UseServerCertificate =', 'no') # Being sure it was not there before Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate') Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'no') else: DIRAC.gLogger.verbose('/DIRAC/Security/UseServerCertificate =', 'yes') # Being sure it was not there before Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate') Script.localCfg.addDefaultEntry('/DIRAC/Security/UseServerCertificate', 'yes') host = DIRAC.gConfig.getValue(cfgInstallPath("Host"), "") if host: DIRAC.gConfig.setOptionValue(cfgPath("DIRAC", "Hostname"), host) if skipCAChecks: DIRAC.gLogger.verbose('/DIRAC/Security/SkipCAChecks =', 'yes') # Being sure it was not there before Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks') Script.localCfg.addDefaultEntry('/DIRAC/Security/SkipCAChecks', 'yes') else: # Necessary to allow initial download of CA's if not skipCADownload: DIRAC.gConfig.setOptionValue('/DIRAC/Security/SkipCAChecks', 'yes') if not skipCADownload: Script.enableCS() try: dirName = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'certificates') mkDir(dirName) except BaseException: DIRAC.gLogger.exception() DIRAC.gLogger.fatal('Fail to create directory:', dirName) DIRAC.exit(-1) try: bdc = BundleDeliveryClient() result = bdc.syncCAs() if result['OK']: result = bdc.syncCRLs() except Exception as e: DIRAC.gLogger.error('Failed to sync CAs and CRLs: %s' % str(e)) if not skipCAChecks: Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks') if ceName or siteName: # This is used in the pilot context, we should have a proxy, or a certificate, and access to CS if useServerCert: # Being sure it was not there before Script.localCfg.deleteOption( '/DIRAC/Security/UseServerCertificate') Script.localCfg.addDefaultEntry( '/DIRAC/Security/UseServerCertificate', 'yes') Script.enableCS() # Get the site resource section gridSections = DIRAC.gConfig.getSections('/Resources/Sites/') if not gridSections['OK']: DIRAC.gLogger.warn('Could not get grid sections list') grids = [] else: grids = gridSections['Value'] # try to get siteName from ceName or Local SE from siteName using Remote Configuration for grid in grids: siteSections = DIRAC.gConfig.getSections('/Resources/Sites/%s/' % grid) if not siteSections['OK']: DIRAC.gLogger.warn('Could not get %s site list' % grid) sites = [] else: sites = siteSections['Value'] if not siteName: if ceName: for site in sites: res = DIRAC.gConfig.getSections( '/Resources/Sites/%s/%s/CEs/' % (grid, site), []) if not res['OK']: DIRAC.gLogger.warn('Could not get %s CEs list' % site) if ceName in res['Value']: siteName = site break if siteName: DIRAC.gLogger.notice('Setting /LocalSite/Site = %s' % siteName) Script.localCfg.addDefaultEntry('/LocalSite/Site', siteName) DIRAC.__siteName = False if ceName: DIRAC.gLogger.notice('Setting /LocalSite/GridCE = %s' % ceName) Script.localCfg.addDefaultEntry('/LocalSite/GridCE', ceName) if not localSE and siteName in sites: localSE = getSEsForSite(siteName) if localSE['OK'] and localSE['Value']: localSE = ','.join(localSE['Value']) DIRAC.gLogger.notice('Setting /LocalSite/LocalSE =', localSE) Script.localCfg.addDefaultEntry( '/LocalSite/LocalSE', localSE) break if gatewayServer: DIRAC.gLogger.verbose('/DIRAC/Gateways/%s =' % DIRAC.siteName(), gatewayServer) Script.localCfg.addDefaultEntry( '/DIRAC/Gateways/%s' % DIRAC.siteName(), gatewayServer) # Create the local cfg if it is not yet there if not outputFile: outputFile = DIRAC.gConfig.diracConfigFilePath outputFile = os.path.abspath(outputFile) if not os.path.exists(outputFile): configDir = os.path.dirname(outputFile) mkDir(configDir) update = True DIRAC.gConfig.dumpLocalCFGToFile(outputFile) if includeAllServers: # We need user proxy or server certificate to continue in order to get all the CS URLs if not useServerCert: Script.enableCS() result = getProxyInfo() if not result['OK']: DIRAC.gLogger.notice( 'Configuration is not completed because no user proxy is available' ) DIRAC.gLogger.notice( 'Create one using dirac-proxy-init and execute again with -F option' ) sys.exit(1) else: Script.localCfg.deleteOption( '/DIRAC/Security/UseServerCertificate') # When using Server Certs CA's will be checked, the flag only disables initial download # this will be replaced by the use of SkipCADownload Script.localCfg.addDefaultEntry( '/DIRAC/Security/UseServerCertificate', 'yes') Script.enableCS() DIRAC.gConfig.setOptionValue('/DIRAC/Configuration/Servers', ','.join(DIRAC.gConfig.getServersList())) DIRAC.gLogger.verbose('/DIRAC/Configuration/Servers =', ','.join(DIRAC.gConfig.getServersList())) if useServerCert: # always removing before dumping Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate') Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks') Script.localCfg.deleteOption('/DIRAC/Security/SkipVOMSDownload') if update: DIRAC.gConfig.dumpLocalCFGToFile(outputFile) # ## LAST PART: do the vomsdir/vomses magic # This has to be done for all VOs in the installation if skipVOMSDownload: # We stop here sys.exit(0) result = Registry.getVOMSServerInfo() if not result['OK']: sys.exit(1) error = '' vomsDict = result['Value'] for vo in vomsDict: voName = vomsDict[vo]['VOMSName'] vomsDirPath = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'vomsdir', voName) vomsesDirPath = os.path.join(DIRAC.rootPath, 'etc', 'grid-security', 'vomses') for path in (vomsDirPath, vomsesDirPath): mkDir(path) vomsesLines = [] for vomsHost in vomsDict[vo].get('Servers', {}): hostFilePath = os.path.join(vomsDirPath, "%s.lsc" % vomsHost) try: DN = vomsDict[vo]['Servers'][vomsHost]['DN'] CA = vomsDict[vo]['Servers'][vomsHost]['CA'] port = vomsDict[vo]['Servers'][vomsHost]['Port'] if not DN or not CA or not port: DIRAC.gLogger.error('DN = %s' % DN) DIRAC.gLogger.error('CA = %s' % CA) DIRAC.gLogger.error('Port = %s' % port) DIRAC.gLogger.error('Missing Parameter for %s' % vomsHost) continue with open(hostFilePath, "wt") as fd: fd.write("%s\n%s\n" % (DN, CA)) vomsesLines.append('"%s" "%s" "%s" "%s" "%s" "24"' % (voName, vomsHost, port, DN, voName)) DIRAC.gLogger.notice("Created vomsdir file %s" % hostFilePath) except Exception: DIRAC.gLogger.exception( "Could not generate vomsdir file for host", vomsHost) error = "Could not generate vomsdir file for VO %s, host %s" % ( voName, vomsHost) try: vomsesFilePath = os.path.join(vomsesDirPath, voName) with open(vomsesFilePath, "wt") as fd: fd.write("%s\n" % "\n".join(vomsesLines)) DIRAC.gLogger.notice("Created vomses file %s" % vomsesFilePath) except Exception: DIRAC.gLogger.exception("Could not generate vomses file") error = "Could not generate vomses file for VO %s" % voName if useServerCert: Script.localCfg.deleteOption('/DIRAC/Security/UseServerCertificate') # When using Server Certs CA's will be checked, the flag only disables initial download # this will be replaced by the use of SkipCADownload Script.localCfg.deleteOption('/DIRAC/Security/SkipCAChecks') if error: sys.exit(1) sys.exit(0)
def main(): params = Params() from DIRAC.Core.Base import Script 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)
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 )
import json import sys from DIRAC import gLogger from DIRAC.Core.Base import Script from DIRAC.Core.Security.X509Chain import X509Chain from DIRAC.Core.Security.ProxyInfo import getProxyInfo class CertEncoder(json.JSONEncoder): """ JSON encoder for data structures possibly including certificate objects. """ def default(self, obj): if isinstance(obj, X509Chain): return obj.dumpAllToString() return json.JSONEncoder.default(self, obj) if __name__ == "__main__": # Suppress error messages, since stdout of this script is expected to be in JSON format gLogger.setLevel("FATAL") Script.enableCS() # Required so dict includes username ProxyInfo = getProxyInfo() if not ProxyInfo["OK"]: sys.exit(1) print(json.dumps(ProxyInfo["Value"], cls=CertEncoder))