Beispiel #1
0
 def __processCredentials( self ):
   """
   Extract the user credentials based on the certificate or what comes from the balancer
   """
   self.__credDict = {}
   #NGINX
   if Conf.balancer() == "nginx":
     headers = self.request.headers
     if headers[ 'X-Scheme' ] == "https" and headers[ 'X-Ssl_client_verify' ] == 'SUCCESS':
       DN = headers[ 'X-Ssl_client_s_dn' ]
       self.__credDict[ 'subject' ] = DN
       self.__credDict[ 'issuer' ] = headers[ 'X-Ssl_client_i_dn' ]
       result = Registry.getUsernameForDN( DN )
       if not result[ 'OK' ]:
         self.__credDict[ 'validDN' ] = False
       else:
         self.__credDict[ 'validDN' ] = True
         self.__credDict[ 'username' ] = result[ 'Value' ]
     return
   #TORNADO
   if not self.request.protocol == "https":
     return
   derCert = self.request.get_ssl_certificate( binary_form = True )
   if not derCert:
     return
   pemCert = ssl.DER_cert_to_PEM_cert( derCert )
   chain = X509Chain()
   chain.loadChainFromString( pemCert )
   result = chain.getCredentials()
   if not result[ 'OK' ]:
     self.log.error( "Could not get client credentials %s" % result[ 'Message' ] )
     return
   self.__credDict = result[ 'Value' ]
Beispiel #2
0
 def __processCredentials(self):
     """
 Extract the user credentials based on the certificate or what comes from the balancer
 """
     self.__credDict = {}
     #NGINX
     if Conf.balancer() == "nginx":
         headers = self.request.headers
         if headers['X-Scheme'] == "https" and headers[
                 'X-Ssl_client_verify'] == 'SUCCESS':
             DN = headers['X-Ssl_client_s_dn']
             self.__credDict['subject'] = DN
             self.__credDict['issuer'] = headers['X-Ssl_client_i_dn']
             result = Registry.getUsernameForDN(DN)
             if not result['OK']:
                 self.__credDict['validDN'] = False
             else:
                 self.__credDict['validDN'] = True
                 self.__credDict['username'] = result['Value']
         return
     #TORNADO
     if not self.request.protocol == "https":
         return
     derCert = self.request.get_ssl_certificate(binary_form=True)
     if not derCert:
         return
     pemCert = ssl.DER_cert_to_PEM_cert(derCert)
     chain = X509Chain()
     chain.loadChainFromString(pemCert)
     result = chain.getCredentials()
     if not result['OK']:
         self.log.error("Could not get client credentials %s" %
                        result['Message'])
         return
     self.__credDict = result['Value']
Beispiel #3
0
 def bootstrap(self):
     """
 Configure and create web app
 """
     self.log.always("\n ====== Starting DIRAC web app ====== \n")
     #Load required CFG files
     self.__loadWebAppCFGFiles()
     #Debug mode?
     devMode = Conf.devMode()
     if devMode:
         self.log.info("Configuring in developer mode...")
     #Calculating routes
     result = self.__handlerMgr.getRoutes()
     if not result['OK']:
         return result
     routes = result['Value']
     #Initialize the session data
     SessionData.setHandlers(self.__handlerMgr.getHandlers()['Value'])
     #Create the app
     tLoader = TemplateLoader(self.__handlerMgr.getPaths("template"))
     kw = dict(devMode=devMode,
               template_loader=tLoader,
               cookie_secret=Conf.cookieSecret(),
               log_function=self._logRequest)
     #Check processes if we're under a load balancert
     if Conf.balancer() and Conf.numProcesses() not in (0, 1):
         tornado.process.fork_processes(Conf.numProcesses(), max_restarts=0)
         kw['devMode'] = False
     #Configure tornado app
     self.__app = tornado.web.Application(routes, **kw)
     self.log.notice("Configuring HTTP on port %s" % (Conf.HTTPPort()))
     #Create the web servers
     srv = tornado.httpserver.HTTPServer(self.__app)
     port = Conf.HTTPPort()
     srv.listen(port)
     self.__servers[('http', port)] = srv
     if Conf.HTTPS():
         self.log.notice("Configuring HTTPS on port %s" % Conf.HTTPSPort())
         sslops = dict(certfile=Conf.HTTPSCert(),
                       keyfile=Conf.HTTPSKey(),
                       cert_reqs=ssl.CERT_OPTIONAL,
                       ca_certs=Conf.generateCAFile())
         self.log.debug(
             " - %s" %
             "\n - ".join(["%s = %s" % (k, sslops[k]) for k in sslops]))
         srv = tornado.httpserver.HTTPServer(self.__app, ssl_options=sslops)
         port = Conf.HTTPSPort()
         srv.listen(port)
         self.__servers[('https', port)] = srv
     return result
Beispiel #4
0
 def bootstrap( self ):
   """
   Configure and create web app
   """
   self.log.always( "\n ====== Starting DIRAC web app ====== \n" )
   #Load required CFG files
   self.__loadWebAppCFGFiles()
   #Debug mode?
   devMode = Conf.devMode()
   if devMode:
     self.log.info( "Configuring in developer mode..." )
   #Calculating routes
   result = self.__handlerMgr.getRoutes()
   if not result[ 'OK' ]:
     return result
   routes = result[ 'Value' ]
   #Initialize the session data
   SessionData.setHandlers( self.__handlerMgr.getHandlers()[ 'Value' ] )
   #Create the app
   tLoader = TemplateLoader( self.__handlerMgr.getPaths( "template" ) )
   kw = dict( devMode = devMode, template_loader = tLoader, cookie_secret = Conf.cookieSecret(),
              log_function = self._logRequest )
   #Check processes if we're under a load balancert
   if Conf.balancer() and Conf.numProcesses() not in ( 0, 1 ):
     tornado.process.fork_processes( Conf.numProcesses(), max_restarts=0 )
     kw[ 'devMode' ] = False
   #Configure tornado app
   self.__app = tornado.web.Application( routes, **kw )
   self.log.notice( "Configuring HTTP on port %s" % ( Conf.HTTPPort() ) )
   #Create the web servers
   srv = tornado.httpserver.HTTPServer( self.__app )
   port = Conf.HTTPPort()
   srv.listen( port )
   self.__servers[ ( 'http', port ) ] = srv
   if Conf.HTTPS():
     self.log.notice( "Configuring HTTPS on port %s" % Conf.HTTPSPort() )
     sslops = dict( certfile = Conf.HTTPSCert(),
                    keyfile = Conf.HTTPSKey(),
                    cert_reqs = ssl.CERT_OPTIONAL,
                    ca_certs = Conf.generateCAFile() )
     self.log.debug( " - %s" % "\n - ".join( [ "%s = %s" % ( k, sslops[k] ) for k in sslops ] ) )
     srv = tornado.httpserver.HTTPServer( self.__app, ssl_options = sslops )
     port = Conf.HTTPSPort()
     srv.listen( port )
     self.__servers[ ( 'https', port ) ] = srv
   return result
Beispiel #5
0
    def bootstrap(self):
        """
    Configure and create web app
    """
        self.log.always("\n ====== Starting DIRAC web app ====== \n")

        # Load required CFG files
        if not self._loadDefaultWebCFG(
        ):  # if we have a web.cfg under etc directory we use it, otherwise we use the configuration file defined by the developer
            self._loadWebAppCFGFiles()
        # Calculating routes
        result = self.__handlerMgr.getRoutes()
        if not result['OK']:
            return result
        routes = result['Value']
        # Initialize the session data
        SessionData.setHandlers(self.__handlerMgr.getHandlers()['Value'])
        # Create the app
        tLoader = TemplateLoader(self.__handlerMgr.getPaths("template"))
        kw = dict(debug=Conf.devMode(),
                  template_loader=tLoader,
                  cookie_secret=Conf.cookieSecret(),
                  log_function=self._logRequest,
                  autoreload=Conf.numProcesses() < 2)

        #please do no move this lines. The lines must be before the fork_processes
        signal.signal(signal.SIGTERM, self.stopChildProcesses)
        signal.signal(signal.SIGINT, self.stopChildProcesses)

        # Check processes if we're under a load balancert
        if Conf.balancer() and Conf.numProcesses() not in (0, 1):
            tornado.process.fork_processes(Conf.numProcesses(), max_restarts=0)
            kw['debug'] = False
        # Debug mode?
        if kw['debug']:
            self.log.info("Configuring in developer mode...")
        # Configure tornado app
        self.__app = tornado.web.Application(routes, **kw)
        self.log.notice("Configuring HTTP on port %s" % (Conf.HTTPPort()))
        # Create the web servers
        srv = tornado.httpserver.HTTPServer(self.__app, xheaders=True)
        port = Conf.HTTPPort()
        srv.listen(port)
        self.__servers[('http', port)] = srv

        Conf.generateRevokedCertsFile()  # it is used by nginx....

        if Conf.HTTPS():
            self.log.notice("Configuring HTTPS on port %s" % Conf.HTTPSPort())
            sslops = dict(certfile=Conf.HTTPSCert(),
                          keyfile=Conf.HTTPSKey(),
                          cert_reqs=ssl.CERT_OPTIONAL,
                          ca_certs=Conf.generateCAFile(),
                          ssl_version=ssl.PROTOCOL_TLSv1)

            sslprotocol = str(Conf.SSLProrocol())
            aviableProtocols = [i for i in dir(ssl) if i.find('PROTOCOL') == 0]
            if sslprotocol and sslprotocol != "":
                if (sslprotocol in aviableProtocols):
                    sslops['ssl_version'] = getattr(ssl, sslprotocol)
                else:
                    message = "%s protocol is not provided. The following protocols are provided: %s" % (
                        sslprotocol, str(aviableProtocols))
                    gLogger.warn(message)

            self.log.debug(
                " - %s" %
                "\n - ".join(["%s = %s" % (k, sslops[k]) for k in sslops]))
            srv = tornado.httpserver.HTTPServer(self.__app,
                                                ssl_options=sslops,
                                                xheaders=True)
            port = Conf.HTTPSPort()
            srv.listen(port)
            self.__servers[('https', port)] = srv
        else:
            #when NGINX is used then the Conf.HTTPS return False, it means tornado does not have to be configured using 443 port
            Conf.generateCAFile(
            )  # if we use Nginx we have to generate the cas as well...
        return result
Beispiel #6
0
    def __processCredentials(self):
        """
    Extract the user credentials based on the certificate or what comes from the balancer
    """

        if not self.request.protocol == "https":
            return

        # OIDC auth method
        def oAuth2():
            if self.get_secure_cookie("AccessToken"):
                access_token = self.get_secure_cookie("AccessToken")
                url = Conf.getCSValue(
                    "TypeAuths/%s/authority" % typeAuth) + '/userinfo'
                heads = {
                    'Authorization': 'Bearer ' + access_token,
                    'Content-Type': 'application/json'
                }
                if 'error' in requests.get(url, headers=heads,
                                           verify=False).json():
                    self.log.error('OIDC request error: %s' % requests.get(
                        url, headers=heads, verify=False).json()['error'])
                    return
                ID = requests.get(url, headers=heads,
                                  verify=False).json()['sub']
                result = getUsernameForID(ID)
                if result['OK']:
                    self.__credDict['username'] = result['Value']
                result = getDNForUsername(self.__credDict['username'])
                if result['OK']:
                    self.__credDict['validDN'] = True
                    self.__credDict['DN'] = result['Value'][0]
                result = getCAForUsername(self.__credDict['username'])
                if result['OK']:
                    self.__credDict['issuer'] = result['Value'][0]
                return

        # Type of Auth
        if not self.get_secure_cookie("TypeAuth"):
            self.set_secure_cookie("TypeAuth", 'Certificate')
        typeAuth = self.get_secure_cookie("TypeAuth")
        self.log.info("Type authentication: %s" % str(typeAuth))
        if typeAuth == "Visitor":
            return
        retVal = Conf.getCSSections("TypeAuths")
        if retVal['OK']:
            if typeAuth in retVal.get("Value"):
                method = Conf.getCSValue("TypeAuths/%s/method" % typeAuth,
                                         'default')
                if method == "oAuth2":
                    oAuth2()

        # NGINX
        if Conf.balancer() == "nginx":
            headers = self.request.headers
            if headers['X-Scheme'] == "https" and headers[
                    'X-Ssl_client_verify'] == 'SUCCESS':
                DN = headers['X-Ssl_client_s_dn']
                if not DN.startswith('/'):
                    items = DN.split(',')
                    items.reverse()
                    DN = '/' + '/'.join(items)
                self.__credDict['DN'] = DN
                self.__credDict['issuer'] = headers['X-Ssl_client_i_dn']
                result = Registry.getUsernameForDN(DN)
                if not result['OK']:
                    self.__credDict['validDN'] = False
                else:
                    self.__credDict['validDN'] = True
                    self.__credDict['username'] = result['Value']
            return

        # TORNADO
        derCert = self.request.get_ssl_certificate(binary_form=True)
        if not derCert:
            return
        pemCert = ssl.DER_cert_to_PEM_cert(derCert)
        chain = X509Chain()
        chain.loadChainFromString(pemCert)
        result = chain.getCredentials()
        if not result['OK']:
            self.log.error("Could not get client credentials %s" %
                           result['Message'])
            return
        self.__credDict = result['Value']
        # Hack. Data coming from OSSL directly and DISET difer in DN/subject
        try:
            self.__credDict['DN'] = self.__credDict['subject']
        except KeyError:
            pass
Beispiel #7
0
  def __processCredentials(self):
    """
    Extract the user credentials based on the certificate or what comes from the balancer
    """

    if not self.request.protocol == "https":
      return

    # OIDC auth method
    def oAuth2():
      if self.get_secure_cookie("AccessToken"):
        access_token = self.get_secure_cookie("AccessToken")
        url = Conf.getCSValue("TypeAuths/%s/authority" % typeAuth) + '/userinfo'
        heads = {'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json'}
        if 'error' in requests.get(url, headers=heads, verify=False).json():
          self.log.error('OIDC request error: %s' % requests.get(url, headers=heads, verify=False).json()['error'])
          return
        ID = requests.get(url, headers=heads, verify=False).json()['sub']
        result = getUsernameForID(ID)
        if result['OK']:
          self.__credDict['username'] = result['Value']
        result = getDNForUsername(self.__credDict['username'])
        if result['OK']:
          self.__credDict['validDN'] = True
          self.__credDict['DN'] = result['Value'][0]
        result = getCAForUsername(self.__credDict['username'])
        if result['OK']:
          self.__credDict['issuer'] = result['Value'][0]
        return

    # Type of Auth
    if not self.get_secure_cookie("TypeAuth"):
      self.set_secure_cookie("TypeAuth", 'Certificate')
    typeAuth = self.get_secure_cookie("TypeAuth")
    self.log.info("Type authentication: %s" % str(typeAuth))
    if typeAuth == "Visitor":
      return
    retVal = Conf.getCSSections("TypeAuths")
    if retVal['OK']:
      if typeAuth in retVal.get("Value"):
        method = Conf.getCSValue("TypeAuths/%s/method" % typeAuth, 'default')
        if method == "oAuth2":
          oAuth2()

    # NGINX
    if Conf.balancer() == "nginx":
      headers = self.request.headers
      if headers['X-Scheme'] == "https" and headers['X-Ssl_client_verify'] == 'SUCCESS':
        DN = headers['X-Ssl_client_s_dn']
        if not DN.startswith('/'):
          items = DN.split(',')
          items.reverse()
          DN = '/' + '/'.join(items)
        self.__credDict['DN'] = DN
        self.__credDict['issuer'] = headers['X-Ssl_client_i_dn']
        result = Registry.getUsernameForDN(DN)
        if not result['OK']:
          self.__credDict['validDN'] = False
        else:
          self.__credDict['validDN'] = True
          self.__credDict['username'] = result['Value']
      return

    # TORNADO
    derCert = self.request.get_ssl_certificate(binary_form=True)
    if not derCert:
      return
    pemCert = ssl.DER_cert_to_PEM_cert(derCert)
    chain = X509Chain()
    chain.loadChainFromString(pemCert)
    result = chain.getCredentials()
    if not result['OK']:
      self.log.error("Could not get client credentials %s" % result['Message'])
      return
    self.__credDict = result['Value']
    # Hack. Data coming from OSSL directly and DISET difer in DN/subject
    try:
      self.__credDict['DN'] = self.__credDict['subject']
    except KeyError:
      pass
Beispiel #8
0
  def bootstrap( self ):
    """
    Configure and create web app
    """
    self.log.always( "\n ====== Starting DIRAC web app ====== \n" )

    # Load required CFG files
    if not self._loadDefaultWebCFG():  # if we have a web.cfg under etc directory we use it, otherwise we use the configuration file defined by the developer
      self._loadWebAppCFGFiles()
    # Calculating routes
    result = self.__handlerMgr.getRoutes()
    if not result[ 'OK' ]:
      return result
    routes = result[ 'Value' ]
    # Initialize the session data
    SessionData.setHandlers( self.__handlerMgr.getHandlers()[ 'Value' ] )
    # Create the app
    tLoader = TemplateLoader( self.__handlerMgr.getPaths( "template" ) )
    kw = dict( debug = Conf.devMode(), template_loader = tLoader, cookie_secret = Conf.cookieSecret(),
               log_function = self._logRequest, autoreload = Conf.numProcesses() < 2 )
    
    #please do no move this lines. The lines must be before the fork_processes
    signal.signal(signal.SIGTERM, self.stopChildProcesses)
    signal.signal(signal.SIGINT, self.stopChildProcesses)
    
    # Check processes if we're under a load balancert
    if Conf.balancer() and Conf.numProcesses() not in ( 0, 1 ):
      tornado.process.fork_processes( Conf.numProcesses(), max_restarts = 0 )
      kw[ 'debug' ] = False
    # Debug mode?
    if kw[ 'debug' ]:
      self.log.info( "Configuring in developer mode..." )
    # Configure tornado app
    self.__app = tornado.web.Application( routes, **kw )
    self.log.notice( "Configuring HTTP on port %s" % ( Conf.HTTPPort() ) )
    # Create the web servers
    srv = tornado.httpserver.HTTPServer( self.__app, xheaders = True )
    port = Conf.HTTPPort()
    srv.listen( port )
    self.__servers[ ( 'http', port ) ] = srv

    Conf.generateRevokedCertsFile()  # it is used by nginx....

    if Conf.HTTPS():
      self.log.notice( "Configuring HTTPS on port %s" % Conf.HTTPSPort() )
      sslops = dict( certfile = Conf.HTTPSCert(),
                     keyfile = Conf.HTTPSKey(),
                     cert_reqs = ssl.CERT_OPTIONAL,
                     ca_certs = Conf.generateCAFile(),
                     ssl_version = ssl.PROTOCOL_TLSv1 ) 

      sslprotocol = str( Conf.SSLProrocol() )
      aviableProtocols = [ i for i in dir( ssl ) if  i.find( 'PROTOCOL' ) == 0]
      if  sslprotocol and sslprotocol != "":
        if ( sslprotocol in aviableProtocols ):
          sslops['ssl_version'] = getattr( ssl, sslprotocol )
        else:
          message = "%s protocol is not provided. The following protocols are provided: %s" % ( sslprotocol, str( aviableProtocols ) )
          gLogger.warn( message )

      self.log.debug( " - %s" % "\n - ".join( [ "%s = %s" % ( k, sslops[k] ) for k in sslops ] ) )
      srv = tornado.httpserver.HTTPServer( self.__app, ssl_options = sslops, xheaders = True )
      port = Conf.HTTPSPort()
      srv.listen( port )
      self.__servers[ ( 'https', port ) ] = srv
    else:
      #when NGINX is used then the Conf.HTTPS return False, it means tornado does not have to be configured using 443 port
      Conf.generateCAFile()  # if we use Nginx we have to generate the cas as well...
    return result