Esempio n. 1
0
    def setUp(self):
        self.authMgr = AuthManager('/Systems/Service/Authorization')
        cfg = CFG()
        cfg.loadFromBuffer(testSystemsCFG)
        gConfig.loadCFG(cfg)
        cfg.loadFromBuffer(testRegistryCFG)
        gConfig.loadCFG(cfg)

        self.noAuthCredDict = {'group': 'group_test'}

        self.userCredDict = {
            'DN': '/User/test/DN/CN=userA',
            'group': 'group_test'
        }
        self.suspendedOtherVOUserCredDict = {
            'DN': '/User/test/DN/CN=userS',
            'group': 'group_test_other'
        }
        self.badUserCredDict = {
            'DN': '/User/test/DN/CN=userB',
            'group': 'group_bad'
        }
        self.suspendedUserCredDict = {
            'DN': '/User/test/DN/CN=userS',
            'group': 'group_test'
        }
        self.hostCredDict = {
            'DN': '/User/test/DN/CN=test.hostA.ch',
            'group': 'hosts'
        }
        self.badHostCredDict = {
            'DN': '/User/test/DN/CN=test.hostB.ch',
            'group': 'hosts'
        }
Esempio n. 2
0
    def setUp(self):
        self.authMgr = AuthManager("/Systems/Service/Authorization")
        cfg = CFG()
        cfg.loadFromBuffer(testSystemsCFG)
        gConfig.loadCFG(cfg)
        cfg.loadFromBuffer(testRegistryCFG)
        gConfig.loadCFG(cfg)

        self.noAuthCredDict = {"group": "group_test"}

        self.userCredDict = {
            "DN": "/User/test/DN/CN=userA",
            "group": "group_test"
        }
        self.suspendedOtherVOUserCredDict = {
            "DN": "/User/test/DN/CN=userS",
            "group": "group_test_other"
        }
        self.badUserCredDict = {
            "DN": "/User/test/DN/CN=userB",
            "group": "group_bad"
        }
        self.suspendedUserCredDict = {
            "DN": "/User/test/DN/CN=userS",
            "group": "group_test"
        }
        self.hostCredDict = {
            "DN": "/User/test/DN/CN=test.hostA.ch",
            "group": "hosts"
        }
        self.badHostCredDict = {
            "DN": "/User/test/DN/CN=test.hostB.ch",
            "group": "hosts"
        }
Esempio n. 3
0
  def setUp(self):

    cfg = CFG()
    cfg.loadFromBuffer(diracTestCACFG)
    gConfig.loadCFG(cfg)
    cfg.loadFromBuffer(userCFG)
    gConfig.loadCFG(cfg)

    result = ProxyProviderFactory().getProxyProvider('DIRAC_TEST_CA')
    self.assertTrue(result['OK'], '\n%s' % result.get('Message') or 'Error message is absent.')
    self.pp = result['Value']

    self.userDictClean = {
        "FullName": "DIRAC test user",
        "EMail": "*****@*****.**"
    }
    self.userDictCleanDN = {
        "DN": "/C=FR/O=DIRAC/OU=DIRAC Consortium/CN=DIRAC test user/[email protected]",
        "EMail": "*****@*****.**"
    }
    self.userDictGroup = {
        "FullName": "DIRAC test user",
        "EMail": "*****@*****.**",
        "DiracGroup": "dirac_user"
    }
    self.userDictNoGroup = {
        "FullName": "DIRAC test user",
        "EMail": "*****@*****.**",
        "DiracGroup": "dirac_no_user"
    }
Esempio n. 4
0
    def setUp(self):

        cfg = CFG()
        cfg.loadFromBuffer(diracTestCACFG)
        gConfig.loadCFG(cfg)
        cfg.loadFromBuffer(userCFG)
        gConfig.loadCFG(cfg)

        result = ProxyProviderFactory().getProxyProvider('DIRAC_TEST_CA')
        self.assertTrue(
            result['OK'], '\n%s' % result.get('Message')
            or 'Error message is absent.')
        self.pp = result['Value']
Esempio n. 5
0
  def setUp( self ):
    self.authMgr = AuthManager( '/Systems/Service/Authorization' )
    cfg = CFG()
    cfg.loadFromBuffer( testSystemsCFG )
    gConfig.loadCFG( cfg )
    cfg.loadFromBuffer( testRegistryCFG )
    gConfig.loadCFG( cfg )

    self.noAuthCredDict = { 'group': 'group_test' }

    self.userCredDict = { 'DN': '/User/test/DN/CN=userA',
                          'group': 'group_test' }

    self.badUserCredDict = { 'DN': '/User/test/DN/CN=userB',
                             'group': 'group_bad' }
    self.hostCredDict = { 'DN': '/User/test/DN/CN=test.hostA.ch',
                          'group': 'hosts' }
    self.badHostCredDict = { 'DN': '/User/test/DN/CN=test.hostB.ch',
                             'group': 'hosts' }
Esempio n. 6
0
      current = expl.pop( 0 )
      if not modCFG.isSection( current ):
        continue
      if modCFG.getOption( "%s/AbsoluteDefinition" % current, False ):
        gLogger.verbose( "%s:%s is an absolute definition" % ( modName, current ) )
        try:
          webCFG.deleteKey( current )
        except:
          pass
        modCFG.deleteKey( "%s/AbsoluteDefinition" % current )
      else:
        for sec in modCFG[ current ].listSections():
          expl.append( "%s/%s" % ( current, sec ) )
    #Add the modCFG
    webCFG = webCFG.mergeWith( modCFG )
  gConfig.loadCFG( webCFG )

def getRawSchema():
  """
  Load the schema from the CS
  """
  base = "%s/Schema" % ( BASECS )
  schema = []
  explore = [ ( "", schema ) ]
  while len( explore ):
    parentName, parentData = explore.pop( 0 )
    fullName = "%s/%s" % ( base, parentName )
    result = gConfig.getSections( fullName )
    if not result[ 'OK' ]:
      continue
    sectionsList = result[ 'Value' ]
Esempio n. 7
0
def initDIRAC( rootPath, enableDebug = False ):
    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    configDict = { 'webConfig' : {} }
    configDict[ 'webConfig' ]['dirac.webroot'] = rootPath
    diracRootPath = os.path.realpath( os.path.dirname( os.path.dirname( rootPath ) ) )
    configDict[ 'webConfig' ]['dirac.root'] = diracRootPath
    if diracRootPath not in sys.path:
      sys.path.append( diracRootPath )
    from DIRAC.FrameworkSystem.Client.Logger import gLogger
    gLogger.registerBackends( [ 'stderr' ] )
    from DIRAC.Core.Base import Script
    Script.registerSwitch( "r", "reload", "Reload for pylons" )
    Script.localCfg.addDefaultEntry( "/DIRAC/Security/UseServerCertificate", "yes" )
    Script.localCfg.addDefaultEntry( "LogColor", True )
    Script.initialize( script = "Website", ignoreErrors = True, initializeMonitor = False )
    gLogger._systemName = "Framework"
    gLogger.initialize( "Web", "/Website" )
    gLogger.setLevel( "VERBOSE" )

    from DIRAC import gMonitor, gConfig, rootPath as droot
    from DIRAC.Core.Utilities import CFG
    from DIRAC.ConfigurationSystem.Client.Helpers import getCSExtensions
    gMonitor.setComponentType( gMonitor.COMPONENT_WEB )
    gMonitor.initialize()
    gMonitor.registerActivity( "pagesServed", "Pages served", "Framework", "pages", gMonitor.OP_SUM )

    gLogger.info( "DIRAC Initialized" )

    configDict['portalVersion'] = portalVersion( rootPath )
    gLogger.info( "DIRAC portal version: %s" % configDict['portalVersion'] )

    extModules = [ '%sDIRAC' % module for module in getCSExtensions() ]
    #Load web.cfg of modules
    cfgFilePaths = [ os.path.join( droot, "etc", "web.cfg" ) ]
    for extModule in extModules:
      gLogger.info( "Adding web.cfg for %s extension" % extModule )
      extModulePath = os.path.join( diracRootPath, extModule )
      webCFGPath = os.path.join( extModulePath, "Web", "web.cfg" )
      cfgFilePaths.append( webCFGPath )
      for systemDir in os.listdir( extModulePath ):
        webCFGSystemPath = os.path.join( extModulePath, systemDir, "Web", "web.cfg" )
        cfgFilePaths.append( webCFGSystemPath )
    webCFG = CFG.CFG()
    for webCFGPath in cfgFilePaths:
      if not os.path.isfile( webCFGPath ):
        gLogger.warn( "%s does not exist" % webCFGPath )
      else:
        gLogger.info( "Loading %s" % webCFGPath )
        modCFG = CFG.CFG().loadFromFile( webCFGPath )
        if modCFG.getOption( 'Website/AbsoluteDefinition', False ):
          gLogger.info( "CFG %s is absolute" % webCFGPath )
          webCFG = modCFG
        else:
          webCFG = webCFG.mergeWith( modCFG )
    gConfig.loadCFG( webCFG )
    gLogger.showHeaders( True )
    gLogger._gLogger__initialized = False
    gLogger.initialize( "Web", "/Website" )

    #Define the controllers, templates and public directories
    for type in ( 'controllers', 'templates', 'public' ):
      configDict[ type ] = []
      for extModule in extModules:
        extModulePath = os.path.join( diracRootPath, extModule )
        typePath = os.path.join( extModulePath, "Web", type )
        if os.path.isdir( typePath ):
          gLogger.info( "Adding %s path for module %s" % ( type, extModule ) )
          configDict[ type ].append( typePath )
        for systemDir in os.listdir( extModulePath ):
          systemTypePath = os.path.join( extModulePath, systemDir, "Web", type )
          if os.path.isdir( systemTypePath ):
            gLogger.info( "Adding %s path for system %s in module %s" % ( type, systemDir, extModule ) )
            configDict[ type ].append( systemTypePath )
      #End of extensions
      configDict[ type ].append( os.path.join( rootPath, type ) )

    #Load debug.cfg?
    if enableDebug:
      debugCFGPath = os.path.join( rootPath, "debug.cfg" )
      if os.path.isfile( debugCFGPath ):
        gLogger.info( "Loading debug cfg file at %s" % debugCFGPath )
        gConfig.loadFile( debugCFGPath )

    gLogger.info( "Extension modules loaded" )

    return configDict
Esempio n. 8
0
  IdProviders
  {
    SomeIdP
    {
      ProviderType = OAuth2
      issuer = https://idp.url/
      client_id = IdP_client_id
      client_secret = IdP_client_secret
      redirect_uri = https://dirac/redirect
      jwks_uri = https://idp.url/jwk
      scope = openid+profile+offline_access+eduperson_entitlement
    }
  }
}
""")
gConfig.loadCFG(cfg)

from authlib.jose import jwt
from DIRAC.Resources.IdProvider.IdProviderFactory import IdProviderFactory
from DIRAC.FrameworkSystem.private.authorization.utils.Clients import DEFAULT_CLIENTS

idps = IdProviderFactory()


def test_getDIRACClients():
    """Try to load default DIRAC authorization client"""
    # Try to get DIRAC client authorization settings
    result = idps.getIdProvider("DIRACCLI")
    assert result["OK"], result["Message"]
    assert result["Value"].issuer == "https://issuer.url/"
    assert result["Value"].client_id == DEFAULT_CLIENTS["DIRACCLI"][
Esempio n. 9
0
def initDIRAC(rootPath, enableDebug=False):
    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    configDict = {'webConfig': {}}
    configDict['webConfig']['dirac.webroot'] = rootPath
    diracRootPath = os.path.realpath(os.path.dirname(
        os.path.dirname(rootPath)))
    configDict['webConfig']['dirac.root'] = diracRootPath
    if diracRootPath not in sys.path:
        sys.path.append(diracRootPath)
    from DIRAC.FrameworkSystem.Client.Logger import gLogger
    gLogger.registerBackends(['stderr'])
    from DIRAC.Core.Base import Script
    Script.registerSwitch("r", "reload", "Reload for pylons")
    Script.localCfg.addDefaultEntry("/DIRAC/Security/UseServerCertificate",
                                    "yes")
    Script.localCfg.addDefaultEntry("LogColor", True)
    Script.initialize(script="Website",
                      ignoreErrors=True,
                      initializeMonitor=False)
    gLogger._systemName = "Framework"
    gLogger.initialize("Web", "/Website")
    gLogger.setLevel("VERBOSE")

    from DIRAC import gMonitor, gConfig, rootPath as droot
    from DIRAC.Core.Utilities import CFG
    from DIRAC.ConfigurationSystem.Client.Helpers import getCSExtensions
    gMonitor.setComponentType(gMonitor.COMPONENT_WEB)
    gMonitor.initialize()
    gMonitor.registerActivity("pagesServed", "Pages served", "Framework",
                              "pages", gMonitor.OP_SUM)

    gLogger.info("DIRAC Initialized")

    configDict['portalVersion'] = portalVersion(rootPath)
    gLogger.info("DIRAC portal version: %s" % configDict['portalVersion'])

    extModules = ['%sDIRAC' % module for module in getCSExtensions()]
    #Load web.cfg of modules
    cfgFilePaths = [os.path.join(droot, "etc", "web.cfg")]
    for extModule in extModules:
        gLogger.info("Adding web.cfg for %s extension" % extModule)
        extModulePath = os.path.join(diracRootPath, extModule)
        webCFGPath = os.path.join(extModulePath, "Web", "web.cfg")
        cfgFilePaths.append(webCFGPath)
        for systemDir in os.listdir(extModulePath):
            webCFGSystemPath = os.path.join(extModulePath, systemDir, "Web",
                                            "web.cfg")
            cfgFilePaths.append(webCFGSystemPath)
    webCFG = CFG.CFG()
    for webCFGPath in cfgFilePaths:
        if not os.path.isfile(webCFGPath):
            gLogger.warn("%s does not exist" % webCFGPath)
        else:
            gLogger.info("Loading %s" % webCFGPath)
            modCFG = CFG.CFG().loadFromFile(webCFGPath)
            if modCFG.getOption('Website/AbsoluteDefinition', False):
                gLogger.info("CFG %s is absolute" % webCFGPath)
                webCFG = modCFG
            else:
                webCFG = webCFG.mergeWith(modCFG)
    gConfig.loadCFG(webCFG)
    gLogger.showHeaders(True)
    gLogger._gLogger__initialized = False
    gLogger.initialize("Web", "/Website")

    #Define the controllers, templates and public directories
    for type in ('controllers', 'templates', 'public'):
        configDict[type] = []
        for extModule in extModules:
            extModulePath = os.path.join(diracRootPath, extModule)
            typePath = os.path.join(extModulePath, "Web", type)
            if os.path.isdir(typePath):
                gLogger.info("Adding %s path for module %s" %
                             (type, extModule))
                configDict[type].append(typePath)
            for systemDir in os.listdir(extModulePath):
                systemTypePath = os.path.join(extModulePath, systemDir, "Web",
                                              type)
                if os.path.isdir(systemTypePath):
                    gLogger.info("Adding %s path for system %s in module %s" %
                                 (type, systemDir, extModule))
                    configDict[type].append(systemTypePath)
        #End of extensions
        configDict[type].append(os.path.join(rootPath, type))

    #Load debug.cfg?
    if enableDebug:
        debugCFGPath = os.path.join(rootPath, "debug.cfg")
        if os.path.isfile(debugCFGPath):
            gLogger.info("Loading debug cfg file at %s" % debugCFGPath)
            gConfig.loadFile(debugCFGPath)

    gLogger.info("Extension modules loaded")

    return configDict
Esempio n. 10
0
            if not modCFG.isSection(current):
                continue
            if modCFG.getOption("%s/AbsoluteDefinition" % current, False):
                gLogger.verbose("%s:%s is an absolute definition" %
                                (modName, current))
                try:
                    webCFG.deleteKey(current)
                except:
                    pass
                modCFG.deleteKey("%s/AbsoluteDefinition" % current)
            else:
                for sec in modCFG[current].listSections():
                    expl.append("%s/%s" % (current, sec))
        #Add the modCFG
        webCFG = webCFG.mergeWith(modCFG)
    gConfig.loadCFG(webCFG)


def getRawSchema():
    """
  Load the schema from the CS
  """
    base = "%s/Schema" % (BASECS)
    schema = []
    explore = [("", schema)]
    while len(explore):
        parentName, parentData = explore.pop(0)
        fullName = "%s/%s" % (base, parentName)
        result = gConfig.getSections(fullName)
        if not result['OK']:
            continue
Esempio n. 11
0
    def setUpClass(cls):
        cls.failed = False

        # Add configuration
        cfg = CFG()
        cfg.loadFromBuffer(diracTestCACFG)
        gConfig.loadCFG(cfg)
        cfg.loadFromBuffer(userCFG)
        gConfig.loadCFG(cfg)

        # Prepare CA
        lines = []
        cfgDict = {}
        cls.caPath = os.path.join(certsPath, "ca")
        cls.caConfigFile = os.path.join(cls.caPath, "openssl_config_ca.cnf")
        # Save original configuration file
        shutil.copyfile(cls.caConfigFile, cls.caConfigFile + "bak")
        # Parse
        fields = [
            "dir", "database", "serial", "new_certs_dir", "private_key",
            "certificate"
        ]
        with open(cls.caConfigFile, "r") as caCFG:
            for line in caCFG:
                if re.findall("=", re.sub(r"#.*", "", line)):
                    field = re.sub(r"#.*", "",
                                   line).replace(" ",
                                                 "").rstrip().split("=")[0]
                    line = "dir = %s #PUT THE RIGHT DIR HERE!\n" % (
                        cls.caPath) if field == "dir" else line
                    val = re.sub(r"#.*", "",
                                 line).replace(" ", "").rstrip().split("=")[1]
                    if field in fields:
                        for i in fields:
                            if cfgDict.get(i):
                                val = val.replace("$%s" % i, cfgDict[i])
                        cfgDict[field] = val
                        if not cfgDict[field]:
                            cls.failed = "%s have empty value in %s" % (
                                field, cls.caConfigFile)
                lines.append(line)
        with open(cls.caConfigFile, "w") as caCFG:
            caCFG.writelines(lines)
        for field in fields:
            if field not in cfgDict.keys():
                cls.failed = "%s value is absent in %s" % (field,
                                                           cls.caConfigFile)
        cls.hostCert = os.path.join(certsPath, "host/hostcert.pem")
        cls.hostKey = os.path.join(certsPath, "host/hostkey.pem")
        cls.caCert = cfgDict["certificate"]
        cls.caKey = cfgDict["private_key"]
        os.chmod(cls.caKey, stat.S_IREAD)
        # Check directory for new certificates
        cls.newCertDir = cfgDict["new_certs_dir"]
        if not os.path.exists(cls.newCertDir):
            os.makedirs(cls.newCertDir)
        for f in os.listdir(cls.newCertDir):
            os.remove(os.path.join(cls.newCertDir, f))
        # Empty the certificate database
        cls.index = cfgDict["database"]
        with open(cls.index, "w") as indx:
            indx.write("")
        # Write down serial
        cls.serial = cfgDict["serial"]
        with open(cls.serial, "w") as serialFile:
            serialFile.write("1000")

        # Create temporaly directory for users certificates
        cls.userDir = tempfile.mkdtemp(dir=certsPath)

        # Create user certificates
        for userName in ["no_user", "user", "user_1", "user_2", "user_3"]:
            userConf = """[ req ]
        default_bits           = 4096
        encrypt_key            = yes
        distinguished_name     = req_dn
        prompt                 = no
        req_extensions         = v3_req
        [ req_dn ]
        C                      = CC
        O                      = DN
        0.O                    = DIRAC
        CN                     = %s
        [ v3_req ]
        # Extensions for client certificates (`man x509v3_config`).
        nsComment = "OpenSSL Generated Client Certificate"
        keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
        extendedKeyUsage = clientAuth
        """ % (userName)
            userConfFile = os.path.join(cls.userDir, userName + ".cnf")
            userReqFile = os.path.join(cls.userDir, userName + ".req")
            userKeyFile = os.path.join(cls.userDir, userName + ".key.pem")
            userCertFile = os.path.join(cls.userDir, userName + ".cert.pem")
            with open(userConfFile, "w") as f:
                f.write(userConf)
            status, output = commands.getstatusoutput(
                "openssl genrsa -out %s" % userKeyFile)
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)
            os.chmod(userKeyFile, stat.S_IREAD)
            status, output = commands.getstatusoutput(
                "openssl req -config %s -key %s -new -out %s" %
                (userConfFile, userKeyFile, userReqFile))
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)
            cmd = "openssl ca -config %s -extensions usr_cert -batch -days 375 -in %s -out %s"
            cmd = cmd % (cls.caConfigFile, userReqFile, userCertFile)
            status, output = commands.getstatusoutput(cmd)
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)

        # Result
        status, output = commands.getstatusoutput("ls -al %s" % cls.userDir)
        if status:
            gLogger.error(output)
            exit()
        gLogger.debug("User certificates:\n", output)
Esempio n. 12
0
class App(object):
    def __init__(self):
        self.__handlerMgr = HandlerMgr(Conf.rootURL())
        self.__servers = {}
        self.log = gLogger.getSubLogger("Web")

    def _logRequest(self, handler):
        status = handler.get_status()
        if status < 400:
            logm = self.log.notice
        elif status < 500:
            logm = self.log.warn
        else:
            logm = self.log.error
        request_time = 1000.0 * handler.request.request_time()
        logm("%d %s %.2fms" %
             (status, handler._request_summary(), request_time))

    def __reloadAppCB(self):
        gLogger.notice("\n !!!!!! Reloading web app...\n")

    def _loadWebAppCFGFiles(self):
        """
    Load WebApp/web.cfg definitions
    """
        exts = []
        for ext in CSGlobals.getCSExtensions():
            if ext == "DIRAC":
                continue
            if ext[-5:] != "DIRAC":
                ext = "%sDIRAC" % ext
            if ext != "WebAppDIRAC":
                exts.append(ext)
        exts.append("DIRAC")
        exts.append("WebAppDIRAC")
        webCFG = CFG()
        for modName in reversed(exts):
            try:
                modPath = imp.find_module(modName)[1]
            except ImportError:
                continue
            gLogger.verbose("Found module %s at %s" % (modName, modPath))
            cfgPath = os.path.join(modPath, "WebApp", "web.cfg")
            if not os.path.isfile(cfgPath):
                gLogger.verbose("Inexistant %s" % cfgPath)
                continue
            try:
                modCFG = CFG().loadFromFile(cfgPath)
            except Exception, excp:
                gLogger.error("Could not load %s: %s" % (cfgPath, excp))
                continue
            gLogger.verbose("Loaded %s" % cfgPath)
            expl = [Conf.BASECS]
            while len(expl):
                current = expl.pop(0)
                if not modCFG.isSection(current):
                    continue
                if modCFG.getOption("%s/AbsoluteDefinition" % current, False):
                    gLogger.verbose("%s:%s is an absolute definition" %
                                    (modName, current))
                    try:
                        webCFG.deleteKey(current)
                    except:
                        pass
                    modCFG.deleteKey("%s/AbsoluteDefinition" % current)
                else:
                    for sec in modCFG[current].listSections():
                        expl.append("%s/%s" % (current, sec))
            # Add the modCFG
            webCFG = webCFG.mergeWith(modCFG)
        gConfig.loadCFG(webCFG)
Esempio n. 13
0
            isLoaded = False
        else:
            try:
                modCFG = CFG().loadFromFile(cfgPath)
            except Exception, excp:
                isLoaded = False
                gLogger.error("Could not load %s: %s" % (cfgPath, excp))

        if modCFG:
            if modCFG.isSection("/Website"):
                gLogger.warn(
                    "%s configuration file is not correct. It is used by the old portal!"
                    % (cfgPath))
                isLoaded = False
            else:
                gConfig.loadCFG(modCFG)
        else:
            isLoaded = False

        return isLoaded

    def stopChildProcesses(self, sig, frame):
        """
    It is used to properly stop tornado when more than one process is used.
    In principle this is doing the job of runsv....
    :param int sig: the signal sent to the process
    :param object frame: execution frame which contains the child processes
    """
        # tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5, sys.exit)
        for child in frame.f_locals.get('children', []):
            gLogger.info("Stopping child processes: %d" % child)
Esempio n. 14
0
    isLoaded = True
    if not os.path.isfile( cfgPath ):
      isLoaded = False
    else:
      try:
        modCFG = CFG().loadFromFile( cfgPath )
      except Exception, excp:
        isLoaded = False
        gLogger.error( "Could not load %s: %s" % ( cfgPath, excp ) )

    if modCFG:
      if modCFG.isSection( "/Website" ):
        gLogger.warn( "%s configuration file is not correct. It is used by the old portal!" % ( cfgPath ) )
        isLoaded = False
      else:
        gConfig.loadCFG( modCFG )
    else:
      isLoaded = False

    return isLoaded
  
  def stopChildProcesses( self, sig, frame ):
    """
    It is used to properly stop tornado when more than one process is used.
    In principle this is doing the job of runsv....
    :param int sig: the signal sent to the process
    :param object frame: execution frame which contains the child processes
    """
    # tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5, sys.exit)
    for child in frame.f_locals.get( 'children', [] ):
      gLogger.info( "Stopping child processes: %d" % child )
Esempio n. 15
0
    def setUpClass(cls):
        cls.failed = False

        # Add configuration
        cfg = CFG()
        cfg.loadFromBuffer(diracTestCACFG)
        gConfig.loadCFG(cfg)
        cfg.loadFromBuffer(userCFG)
        gConfig.loadCFG(cfg)

        # Prepare CA
        lines = []
        cfgDict = {}
        cls.caPath = os.path.join(certsPath, 'ca')
        cls.caConfigFile = os.path.join(cls.caPath, 'openssl_config_ca.cnf')
        # Save original configuration file
        shutil.copyfile(cls.caConfigFile, cls.caConfigFile + 'bak')
        # Parse
        fields = [
            'dir', 'database', 'serial', 'new_certs_dir', 'private_key',
            'certificate'
        ]
        with open(cls.caConfigFile, "r") as caCFG:
            for line in caCFG:
                if re.findall('=', re.sub(r'#.*', '', line)):
                    field = re.sub(r'#.*', '',
                                   line).replace(' ',
                                                 '').rstrip().split('=')[0]
                    line = 'dir = %s #PUT THE RIGHT DIR HERE!\n' % (
                        cls.caPath) if field == 'dir' else line
                    val = re.sub(r'#.*', '',
                                 line).replace(' ', '').rstrip().split('=')[1]
                    if field in fields:
                        for i in fields:
                            if cfgDict.get(i):
                                val = val.replace('$%s' % i, cfgDict[i])
                        cfgDict[field] = val
                        if not cfgDict[field]:
                            cls.failed = '%s have empty value in %s' % (
                                field, cls.caConfigFile)
                lines.append(line)
        with open(cls.caConfigFile, "w") as caCFG:
            caCFG.writelines(lines)
        for field in fields:
            if field not in cfgDict.keys():
                cls.failed = '%s value is absent in %s' % (field,
                                                           cls.caConfigFile)
        cls.hostCert = os.path.join(certsPath, 'host/hostcert.pem')
        cls.hostKey = os.path.join(certsPath, 'host/hostkey.pem')
        cls.caCert = cfgDict['certificate']
        cls.caKey = cfgDict['private_key']
        os.chmod(cls.caKey, stat.S_IREAD)
        # Check directory for new certificates
        cls.newCertDir = cfgDict['new_certs_dir']
        if not os.path.exists(cls.newCertDir):
            os.makedirs(cls.newCertDir)
        for f in os.listdir(cls.newCertDir):
            os.remove(os.path.join(cls.newCertDir, f))
        # Empty the certificate database
        cls.index = cfgDict['database']
        with open(cls.index, 'w') as indx:
            indx.write('')
        # Write down serial
        cls.serial = cfgDict['serial']
        with open(cls.serial, 'w') as serialFile:
            serialFile.write('1000')

        # Create temporaly directory for users certificates
        cls.userDir = tempfile.mkdtemp(dir=certsPath)

        # Create user certificates
        for userName in ['no_user', 'user_1', 'user_2', 'user_3']:
            userConf = """[ req ]
        default_bits           = 2048
        encrypt_key            = yes
        distinguished_name     = req_dn
        prompt                 = no
        req_extensions         = v3_req
        [ req_dn ]
        C                      = DN
        O                      = DIRAC
        CN                     = %s
        [ v3_req ]
        # Extensions for client certificates (`man x509v3_config`).
        nsComment = "OpenSSL Generated Client Certificate"
        keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
        extendedKeyUsage = clientAuth
        """ % (userName)
            userConfFile = os.path.join(cls.userDir, userName + '.cnf')
            userReqFile = os.path.join(cls.userDir, userName + '.req')
            userKeyFile = os.path.join(cls.userDir, userName + '.key.pem')
            userCertFile = os.path.join(cls.userDir, userName + '.cert.pem')
            with open(userConfFile, "w") as f:
                f.write(userConf)
            status, output = commands.getstatusoutput(
                'openssl genrsa -out %s 2048' % userKeyFile)
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)
            os.chmod(userKeyFile, stat.S_IREAD)
            status, output = commands.getstatusoutput(
                'openssl req -config %s -key %s -new -out %s' %
                (userConfFile, userKeyFile, userReqFile))
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)
            cmd = 'openssl ca -config %s -extensions usr_cert -batch -days 375 -in %s -out %s'
            cmd = cmd % (cls.caConfigFile, userReqFile, userCertFile)
            status, output = commands.getstatusoutput(cmd)
            if status:
                gLogger.error(output)
                exit()
            gLogger.debug(output)