Beispiel #1
0
def sessionhdl(connection, authname, skipauth=False):
    # For now, trying to test the console stuff, so let's just do n4.
    authenticated = False
    authdata = None
    cfm = None
    if skipauth:
        authenticated = True
        cfm = configmanager.ConfigManager(tenant=None, username=authname)
    elif authname:
        authdata = auth.authorize(authname, element=None)
        if authdata is not None:
            cfm = authdata[1]
            authenticated = True
    send_data(connection, "Confluent -- v0 --")
    while not authenticated:  # prompt for name and passphrase
        send_data(connection, {'authpassed': 0})
        response = tlvdata.recv(connection)
        authname = response['username']
        passphrase = response['password']
        # note(jbjohnso): here, we need to authenticate, but not
        # authorize a user.  When authorization starts understanding
        # element path, that authorization will need to be called
        # per request the user makes
        authdata = auth.check_user_passphrase(authname, passphrase)
        if authdata is None:
            auditlog.log(
                {'operation': 'connect', 'user': authname, 'allowed': False})
        else:
            authenticated = True
            cfm = authdata[1]
    send_data(connection, {'authpassed': 1})
    request = tlvdata.recv(connection)
    while request is not None:
        try:
            process_request(
                connection, request, cfm, authdata, authname, skipauth)
        except exc.ConfluentException as e:
            if ((not isinstance(e, exc.LockedCredentials)) and
                    e.apierrorcode == 500):
                tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {'errorcode': e.apierrorcode,
                                   'error': e.apierrorstr,
                                   'detail': e.get_error_body()})
            send_data(connection, {'_requestdone': 1})
        except SystemExit:
            sys.exit(0)
        except:
            tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {'errorcode': 500,
                                      'error': 'Unexpected error'})
            send_data(connection, {'_requestdone': 1})
        request = tlvdata.recv(connection)
Beispiel #2
0
def sessionhdl(connection, authname, skipauth=False):
    # For now, trying to test the console stuff, so let's just do n4.
    authenticated = False
    authdata = None
    cfm = None
    if skipauth:
        authenticated = True
        cfm = configmanager.ConfigManager(tenant=None, username=authname)
    elif authname:
        authdata = auth.authorize(authname, element=None)
        if authdata is not None:
            cfm = authdata[1]
            authenticated = True
    send_data(connection, "Confluent -- v0 --")
    while not authenticated:  # prompt for name and passphrase
        send_data(connection, {'authpassed': 0})
        response = tlvdata.recv(connection)
        authname = response['username']
        passphrase = response['password']
        # note(jbjohnso): here, we need to authenticate, but not
        # authorize a user.  When authorization starts understanding
        # element path, that authorization will need to be called
        # per request the user makes
        authdata = auth.check_user_passphrase(authname, passphrase)
        if authdata is None:
            auditlog.log(
                {'operation': 'connect', 'user': authname, 'allowed': False})
        else:
            authenticated = True
            cfm = authdata[1]
    send_data(connection, {'authpassed': 1})
    request = tlvdata.recv(connection)
    while request is not None:
        try:
            process_request(
                connection, request, cfm, authdata, authname, skipauth)
        except exc.ConfluentException as e:
            if ((not isinstance(e, exc.LockedCredentials)) and
                    e.apierrorcode == 500):
                tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {'errorcode': e.apierrorcode,
                                   'error': e.apierrorstr,
                                   'detail': e.get_error_body()})
            send_data(connection, {'_requestdone': 1})
        except SystemExit:
            sys.exit(0)
        except:
            tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {'errorcode': 500,
                                      'error': 'Unexpected error'})
            send_data(connection, {'_requestdone': 1})
        request = tlvdata.recv(connection)
Beispiel #3
0
def process_request(connection, request, cfm, authdata, authname, skipauth):
    if isinstance(request, tlvdata.ClientFile):
        cfm.add_client_file(request)
        return
    if not isinstance(request, dict):
        raise exc.InvalidArgumentException
    operation = request['operation']
    path = request['path']
    params = request.get('parameters', {})
    hdlr = None
    auditmsg = {
        'operation': operation,
        'target': path,
    }
    if not skipauth:
        authdata = auth.authorize(authdata[2], path, authdata[3], operation)
        if not authdata:
            auditmsg['allowed'] = False
            auditlog.log(auditmsg)
            raise exc.ForbiddenRequest()
        auditmsg['user'] = authdata[2]
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
    auditmsg['allowed'] = True
    if _should_authlog(path, operation):
        tlvdata.unicode_dictvalues(auditmsg)
        auditlog.log(auditmsg)
    try:
        if operation == 'start':
            return start_term(authname, cfm, connection, params, path,
                              authdata, skipauth)
        elif operation == 'shutdown' and skipauth:
            configmanager.ConfigManager.shutdown()
        else:
            hdlr = pluginapi.handle_path(path, operation, cfm, params)
    except exc.NotFoundException as e:
        send_data(connection, {
            "errorcode": 404,
            "error": "Target not found - " + str(e)
        })
        send_data(connection, {"_requestdone": 1})
    except exc.InvalidArgumentException as e:
        send_data(connection, {
            "errorcode": 400,
            "error": "Bad Request - " + str(e)
        })
        send_data(connection, {"_requestdone": 1})
    send_response(hdlr, connection)
    return
Beispiel #4
0
def process_request(connection, request, cfm, authdata, authname, skipauth):
    if not isinstance(request, dict):
        raise exc.InvalidArgumentException
    operation = request['operation']
    path = request['path']
    params = request.get('parameters', {})
    hdlr = None
    if not skipauth:
        authdata = auth.authorize(authdata[2], path, authdata[3], operation)
        auditmsg = {
            'operation': operation,
            'target': path,
        }
        if authdata is None:
            auditmsg['allowed'] = False
            auditlog.log(auditmsg)
            raise exc.ForbiddenRequest()
        auditmsg['user'] = authdata[2]
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
        auditmsg['allowed'] = True
        auditlog.log(auditmsg)
    try:
        if operation == 'start':
            return start_term(authname, cfm, connection, params, path)
        elif operation == 'shutdown':
            configmanager.ConfigManager.shutdown()
        else:
            hdlr = pluginapi.handle_path(path, operation, cfm, params)
    except exc.NotFoundException as e:
        send_data(connection, {"errorcode": 404,
                                  "error": "Target not found - " + str(e)})
        send_data(connection, {"_requestdone": 1})
    except exc.InvalidArgumentException as e:
        send_data(connection, {"errorcode": 400,
                                  "error": "Bad Request - " + str(e)})
        send_data(connection, {"_requestdone": 1})
    send_response(hdlr, connection)
    return
Beispiel #5
0
def sessionhdl(connection, authname, skipauth=False, cert=None):
    # For now, trying to test the console stuff, so let's just do n4.
    authenticated = False
    authdata = None
    cfm = None
    if skipauth:
        authenticated = True
        cfm = configmanager.ConfigManager(tenant=None, username=authname)
    elif authname:
        authdata = auth.authorize(authname, element=None)
        if authdata is not None:
            cfm = authdata[1]
            authenticated = True
    send_data(connection, "Confluent -- v0 --")
    while not authenticated:  # prompt for name and passphrase
        send_data(connection, {'authpassed': 0})
        response = tlvdata.recv(connection)
        if 'collective' in response:
            return collective.handle_connection(connection, cert,
                                                response['collective'])
        if 'dispatch' in response:
            dreq = tlvdata.recvall(connection, response['dispatch']['length'])
            return pluginapi.handle_dispatch(connection, cert, dreq,
                                             response['dispatch']['name'])
        if 'proxyconsole' in response:
            return start_proxy_term(connection, cert, response['proxyconsole'])
        authname = response['username']
        passphrase = response['password']
        # note(jbjohnso): here, we need to authenticate, but not
        # authorize a user.  When authorization starts understanding
        # element path, that authorization will need to be called
        # per request the user makes
        authdata = auth.check_user_passphrase(authname, passphrase)
        if authdata is None:
            auditlog.log({
                'operation': 'connect',
                'user': authname,
                'allowed': False
            })
        else:
            authenticated = True
            cfm = authdata[1]
    send_data(connection, {'authpassed': 1})
    request = tlvdata.recv(connection)
    if 'collective' in request and skipauth:
        if not libssl:
            tlvdata.send(
                connection, {
                    'collective': {
                        'error':
                        'Server either does not have '
                        'python-pyopenssl installed or has an '
                        'incorrect version installed '
                        '(e.g. pyOpenSSL would need to be '
                        'replaced with python-pyopenssl)'
                    }
                })
            return
        return collective.handle_connection(connection,
                                            None,
                                            request['collective'],
                                            local=True)
    while request is not None:
        try:
            process_request(connection, request, cfm, authdata, authname,
                            skipauth)
        except exc.ConfluentException as e:
            if ((not isinstance(e, exc.LockedCredentials))
                    and e.apierrorcode == 500):
                tracelog.log(traceback.format_exc(),
                             ltype=log.DataTypes.event,
                             event=log.Events.stacktrace)
            send_data(
                connection, {
                    'errorcode': e.apierrorcode,
                    'error': e.apierrorstr,
                    'detail': e.get_error_body()
                })
            send_data(connection, {'_requestdone': 1})
        except SystemExit:
            sys.exit(0)
        except:
            tracelog.log(traceback.format_exc(),
                         ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {
                'errorcode': 500,
                'error': 'Unexpected error'
            })
            send_data(connection, {'_requestdone': 1})
        request = tlvdata.recv(connection)
Beispiel #6
0
def _authorize_request(env, operation):
    """Grant/Deny access based on data from wsgi env

    """
    authdata = None
    name = ''
    sessionid = None
    cookie = Cookie.SimpleCookie()
    if 'HTTP_COOKIE' in env:
        #attempt to use the cookie.  If it matches
        cc = RobustCookie()
        cc.load(env['HTTP_COOKIE'])
        if 'confluentsessionid' in cc:
            sessionid = cc['confluentsessionid'].value
            sessid = sessionid
            if sessionid in httpsessions:
                if _csrf_valid(env, httpsessions[sessionid]):
                    if env['PATH_INFO'] == '/sessions/current/logout':
                        targets = []
                        for mythread in httpsessions[sessionid]['inflight']:
                            targets.append(mythread)
                        for mythread in targets:
                            eventlet.greenthread.kill(mythread)
                        forwarder.close_session(sessionid)
                        del httpsessions[sessionid]
                        return ('logout', )
                    httpsessions[sessionid]['expiry'] = time.time() + 90
                    name = httpsessions[sessionid]['name']
                    authdata = auth.authorize(
                        name,
                        element=None,
                        skipuserobj=httpsessions[sessionid]['skipuserobject'])
    if (not authdata) and 'HTTP_AUTHORIZATION' in env:
        if env['PATH_INFO'] == '/sessions/current/logout':
            if 'HTTP_REFERER' in env:
                # note that this doesn't actually do harm
                # otherwise, but this way do not give appearance
                # of something having a side effect if it has the smell
                # of a CSRF
                return {'code': 401}
            return ('logout', )
        name, passphrase = base64.b64decode(env['HTTP_AUTHORIZATION'].replace(
            'Basic ', '')).split(':', 1)
        authdata = auth.check_user_passphrase(name, passphrase, element=None)
        if not authdata:
            return {'code': 401}
        sessid = util.randomstring(32)
        while sessid in httpsessions:
            sessid = util.randomstring(32)
        httpsessions[sessid] = {
            'name': name,
            'expiry': time.time() + 90,
            'skipuserobject': authdata[4],
            'inflight': set([])
        }
        if 'HTTP_CONFLUENTAUTHTOKEN' in env:
            httpsessions[sessid]['csrftoken'] = util.randomstring(32)
        cookie['confluentsessionid'] = sessid
        cookie['confluentsessionid']['secure'] = 1
        cookie['confluentsessionid']['httponly'] = 1
        cookie['confluentsessionid']['path'] = '/'
    skiplog = _should_skip_authlog(env)
    if authdata:
        auditmsg = {
            'user': name,
            'operation': operation,
            'target': env['PATH_INFO'],
        }
        authinfo = {
            'code': 200,
            'cookie': cookie,
            'cfgmgr': authdata[1],
            'username': authdata[2],
            'userdata': authdata[0]
        }
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
            authinfo['tenant'] = authdata[3]
        auditmsg['user'] = authdata[2]
        if sessid is not None:
            authinfo['sessionid'] = sessid
        if not skiplog:
            auditlog.log(auditmsg)
        if 'csrftoken' in httpsessions[sessid]:
            authinfo['authtoken'] = httpsessions[sessid]['csrftoken']
        return authinfo
    else:
        return {'code': 401}
Beispiel #7
0
def _authorize_request(env, operation):
    """Grant/Deny access based on data from wsgi env

    """
    authdata = None
    name = ''
    sessionid = None
    cookie = Cookie.SimpleCookie()
    if 'HTTP_COOKIE' in env:
        #attempt to use the cookie.  If it matches
        cc = RobustCookie()
        cc.load(env['HTTP_COOKIE'])
        if 'confluentsessionid' in cc:
            sessionid = cc['confluentsessionid'].value
            sessid = sessionid
            if sessionid in httpsessions:
                if _csrf_valid(env, httpsessions[sessionid]):
                    if env['PATH_INFO'] == '/sessions/current/logout':
                        targets = []
                        for mythread in httpsessions[sessionid]['inflight']:
                            targets.append(mythread)
                        for mythread in targets:
                            eventlet.greenthread.kill(mythread)
                        del httpsessions[sessionid]
                        return ('logout',)
                    httpsessions[sessionid]['expiry'] = time.time() + 90
                    name = httpsessions[sessionid]['name']
                    authdata = auth.authorize(
                        name, element=None,
                        skipuserobj=httpsessions[sessionid]['skipuserobject'])
    if (not authdata) and 'HTTP_AUTHORIZATION' in env:
        if env['PATH_INFO'] == '/sessions/current/logout':
            if 'HTTP_REFERER' in env:
                # note that this doesn't actually do harm
                # otherwise, but this way do not give appearance
                # of something having a side effect if it has the smell
                # of a CSRF
                return {'code': 401}
            return ('logout',)
        name, passphrase = base64.b64decode(
            env['HTTP_AUTHORIZATION'].replace('Basic ', '')).split(':', 1)
        authdata = auth.check_user_passphrase(name, passphrase, element=None)
        if not authdata:
            return {'code': 401}
        sessid = util.randomstring(32)
        while sessid in httpsessions:
            sessid = util.randomstring(32)
        httpsessions[sessid] = {'name': name, 'expiry': time.time() + 90,
                                'skipuserobject': authdata[4],
                                'inflight': set([])}
        if 'HTTP_CONFLUENTAUTHTOKEN' in env:
            httpsessions[sessid]['csrftoken'] = util.randomstring(32)
        cookie['confluentsessionid'] = sessid
        cookie['confluentsessionid']['secure'] = 1
        cookie['confluentsessionid']['httponly'] = 1
        cookie['confluentsessionid']['path'] = '/'
    skiplog = _should_skip_authlog(env)
    if authdata:
        auditmsg = {
            'user': name,
            'operation': operation,
            'target': env['PATH_INFO'],
        }
        authinfo = {'code': 200,
                    'cookie': cookie,
                    'cfgmgr': authdata[1],
                    'username': authdata[2],
                    'userdata': authdata[0]}
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
            authinfo['tenant'] = authdata[3]
        auditmsg['user'] = authdata[2]
        if sessid is not None:
            authinfo['sessionid'] = sessid
        if not skiplog:
            auditlog.log(auditmsg)
        if 'csrftoken' in httpsessions[sessid]:
            authinfo['authtoken'] = httpsessions[sessid]['csrftoken']
        return authinfo
    else:
        return {'code': 401}
Beispiel #8
0
def sessionhdl(connection, authname, skipauth=False):
    # For now, trying to test the console stuff, so let's just do n4.
    authenticated = False
    authdata = None
    cfm = None
    if skipauth:
        authenticated = True
        cfm = configmanager.ConfigManager(tenant=None)
    elif authname:
        authdata = auth.authorize(authname, element=None)
        if authdata is not None:
            cfm = authdata[1]
            authenticated = True
    send_data(connection, "Confluent -- v0 --")
    while not authenticated:  # prompt for name and passphrase
        send_data(connection, {'authpassed': 0})
        response = tlvdata.recv(connection)
        authname = response['username']
        passphrase = response['password']
        # note(jbjohnso): here, we need to authenticate, but not
        # authorize a user.  When authorization starts understanding
        # element path, that authorization will need to be called
        # per request the user makes
        authdata = auth.check_user_passphrase(authname, passphrase)
        if authdata is None:
            auditlog.log(
                {'operation': 'connect', 'user': authname, 'allowed': False})
        else:
            authenticated = True
            cfm = authdata[1]
    send_data(connection, {'authpassed': 1})
    request = tlvdata.recv(connection)
    while request is not None:
        try:
            process_request(
                connection, request, cfm, authdata, authname, skipauth)
        except exc.ForbiddenRequest:
            send_data(connection, {'errorcode': 403,
                                      'error': 'Forbidden'})
            send_data(connection, {'_requestdone': 1})
        except exc.TargetEndpointBadCredentials:
            send_data(connection, {'errorcode': 502,
                                      'error': 'Bad Credentials'})
            send_data(connection, {'_requestdone': 1})
        except exc.TargetEndpointUnreachable as tu:
            send_data(connection, {'errorcode': 504,
                                      'error': 'Unreachable Target - ' + str(
                                          tu)})
            send_data(connection, {'_requestdone': 1})
        except exc.NotImplementedException:
            send_data(connection, {'errorcode': 501,
                                      'error': 'Not Implemented'})
            send_data(connection, {'_requestdone': 1})
        except exc.NotFoundException as nfe:
            send_data(connection, {'errorcode': 404,
                                      'error': str(nfe)})
            send_data(connection, {'_requestdone': 1})
        except exc.InvalidArgumentException as iae:
            send_data(connection, {'errorcode': 400,
                                      'error': 'Bad Request - ' + str(iae)})
            send_data(connection, {'_requestdone': 1})
        except exc.LockedCredentials as lockedcred:
            send_data(connection, {'errorcode': 500,
                                      'error': 'Locked Credential Store'})
            send_data(connection, {'_requestdone': 1})
        except SystemExit:
            sys.exit(0)
        except:
            tracelog.log(traceback.format_exc(), ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {'errorcode': 500,
                                      'error': 'Unexpected error'})
            send_data(connection, {'_requestdone': 1})
        request = tlvdata.recv(connection)
Beispiel #9
0
def process_request(connection, request, cfm, authdata, authname, skipauth):
    if not isinstance(request, dict):
        raise ValueError
    operation = request['operation']
    path = request['path']
    params = request.get('parameters', None)
    hdlr = None
    if not skipauth:
        authdata = auth.authorize(authdata[2], path, authdata[3], operation)
        auditmsg = {
            'operation': operation,
            'user': authdata[2],
            'target': path,
        }
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
        if authdata is None:
            auditmsg['allowed'] = False
            auditlog.log(auditmsg)
            raise exc.ForbiddenRequest()
        auditmsg['allowed'] = True
        auditlog.log(auditmsg)
    try:
        if operation == 'start':
            elems = path.split('/')
            if elems[3] != "console":
                raise exc.InvalidArgumentException()
            node = elems[2]
            ccons = ClientConsole(connection)
            skipreplay = False
            if params and 'skipreplay' in params and params['skipreplay']:
                skipreplay = True
            consession = consoleserver.ConsoleSession(
                node=node, configmanager=cfm, username=authname,
                datacallback=ccons.sendall, skipreplay=skipreplay)
            if consession is None:
                raise Exception("TODO")
            send_data(connection, {'started': 1})
            ccons.startsending()
            bufferage = consession.get_buffer_age()
            if bufferage is not False:
                send_data(connection, {'bufferage': bufferage})
            while consession is not None:
                data = tlvdata.recv(connection)
                if type(data) == dict:
                    if data['operation'] == 'stop':
                        consession.destroy()
                        return
                    elif data['operation'] == 'break':
                        consession.send_break()
                        continue
                    elif data['operation'] == 'reopen':
                        consession.reopen()
                        continue
                    else:
                        raise Exception("TODO")
                if not data:
                    consession.destroy()
                    return
                consession.write(data)
        elif operation == 'shutdown':
            configmanager.ConfigManager.shutdown()
        else:
            hdlr = pluginapi.handle_path(path, operation, cfm, params)
    except exc.NotFoundException as e:
        send_data(connection, {"errorcode": 404,
                                  "error": "Target not found - " + str(e)})
        send_data(connection, {"_requestdone": 1})
    except exc.InvalidArgumentException as e:
        send_data(connection, {"errorcode": 400,
                                  "error": "Bad Request - " + str(e)})
        send_data(connection, {"_requestdone": 1})
    send_response(hdlr, connection)
    return
Beispiel #10
0
def wsock_handler(ws):
    sessid = ws.wait()
    sessid = sessid.replace('ConfluentSessionId:', '')
    sessid = sessid[:-1]
    currsess = httpsessions.get(sessid, None)
    if not currsess:
        return
    authtoken = ws.wait()
    authtoken = authtoken.replace('ConfluentAuthToken:', '')
    authtoken = authtoken[:-1]
    if currsess['csrftoken'] != authtoken:
        return
    mythreadid = greenlet.getcurrent()
    httpsessions[sessid]['inflight'].add(mythreadid)
    name = httpsessions[sessid]['name']
    authdata = auth.authorize(name, ws.path)
    if not authdata:
        return
    if '/console/session' in ws.path or '/shell/sessions/' in ws.path:
        #hard bake JSON into this path, do not support other incarnations
        if '/console/session' in ws.path:
            prefix, _, _ = ws.path.partition('/console/session')
            shellsession = False
        elif '/shell/sessions/' in ws.path:
            prefix, _, _ = ws.path.partition('/shell/sessions')
            shellsession = True
        _, _, nodename = prefix.rpartition('/')
        geom = ws.wait()
        geom = geom[1:]
        geom = json.loads(geom)
        width = geom['width']
        height = geom['height']
        skipreplay = geom.get('skipreplay', False)
        cfgmgr = httpsessions[sessid]['cfgmgr']
        username = httpsessions[sessid]['name']

        def datacallback(data):
            if isinstance(data, dict):
                data = json.dumps(data)
                ws.send(u'!' + data)
            else:
                try:
                    data = data.decode('utf8')
                except UnicodeDecodeError:
                    data = data.decode('cp437')
                ws.send(u' ' + data)

        try:
            if shellsession:
                consession = shellserver.ShellSession(
                    node=nodename,
                    configmanager=cfgmgr,
                    username=username,
                    skipreplay=skipreplay,
                    datacallback=datacallback,
                    width=width,
                    height=height)
            else:
                consession = consoleserver.ConsoleSession(
                    node=nodename,
                    configmanager=cfgmgr,
                    username=username,
                    skipreplay=skipreplay,
                    datacallback=datacallback,
                    width=width,
                    height=height)
        except exc.NotFoundException:
            return
        clientmsg = ws.wait()
        try:
            while clientmsg is not None:
                if clientmsg[0] == ' ':
                    consession.write(clientmsg[1:])
                elif clientmsg[0] == '!':
                    cmd = json.loads(clientmsg[1:])
                    action = cmd.get('action', None)
                    if action == 'break':
                        consession.send_break()
                    elif action == 'resize':
                        consession.resize(width=cmd['width'],
                                          height=cmd['height'])
                elif clientmsg[0] == '?':
                    ws.send(u'?')
                clientmsg = ws.wait()
        finally:
            consession.destroy()
Beispiel #11
0
def _authorize_request(env, operation):
    """Grant/Deny access based on data from wsgi env

    """
    authdata = None
    name = ''
    sessionid = None
    cookie = Cookie.SimpleCookie()
    element = env['PATH_INFO']
    if element.startswith('/sessions/current/'):
        element = None
    if 'HTTP_COOKIE' in env:
        cidx = (env['HTTP_COOKIE']).find('confluentsessionid=')
        if cidx >= 0:
            sessionid = env['HTTP_COOKIE'][cidx + 19:cidx + 51]
            sessid = sessionid
            sessid = sessionid
            if sessionid in httpsessions:
                if _csrf_valid(env, httpsessions[sessionid]):
                    if env['PATH_INFO'] == '/sessions/current/logout':
                        targets = []
                        for mythread in httpsessions[sessionid]['inflight']:
                            targets.append(mythread)
                        for mythread in targets:
                            eventlet.greenthread.kill(mythread)
                        forwarder.close_session(sessionid)
                        del httpsessions[sessionid]
                        return ('logout', )
                    httpsessions[sessionid]['expiry'] = time.time() + 90
                    name = httpsessions[sessionid]['name']
                    authdata = auth.authorize(
                        name,
                        element=element,
                        operation=operation,
                        skipuserobj=httpsessions[sessionid]['skipuserobject'])
    if (not authdata) and 'HTTP_AUTHORIZATION' in env:
        if env['PATH_INFO'] == '/sessions/current/logout':
            if 'HTTP_REFERER' in env:
                # note that this doesn't actually do harm
                # otherwise, but this way do not give appearance
                # of something having a side effect if it has the smell
                # of a CSRF
                return {'code': 401}
            return ('logout', )
        if env['HTTP_AUTHORIZATION'].startswith('MultiBasic '):
            name, passphrase = base64.b64decode(
                env['HTTP_AUTHORIZATION'].replace('MultiBasic ',
                                                  '')).split(b':', 1)
            passphrase = json.loads(passphrase)
        else:
            name, passphrase = base64.b64decode(
                env['HTTP_AUTHORIZATION'].replace('Basic ',
                                                  '')).split(b':', 1)
        try:
            authdata = auth.check_user_passphrase(name,
                                                  passphrase,
                                                  operation=operation,
                                                  element=element)
        except Exception as e:
            if hasattr(e, 'prompts'):
                return {'code': 403, 'prompts': e.prompts}
            raise
        if authdata is False:
            return {'code': 403}
        elif not authdata:
            return {'code': 401}
        sessid = util.randomstring(32)
        while sessid in httpsessions:
            sessid = util.randomstring(32)
        httpsessions[sessid] = {
            'name': name,
            'expiry': time.time() + 90,
            'skipuserobject': authdata[4],
            'inflight': set([])
        }
        if 'HTTP_CONFLUENTAUTHTOKEN' in env:
            httpsessions[sessid]['csrftoken'] = util.randomstring(32)
        cookie['confluentsessionid'] = util.stringify(sessid)
        cookie['confluentsessionid']['secure'] = 1
        cookie['confluentsessionid']['httponly'] = 1
        cookie['confluentsessionid']['path'] = '/'
    skiplog = _should_skip_authlog(env)
    if authdata:
        auditmsg = {
            'user': util.stringify(name),
            'operation': operation,
            'target': env['PATH_INFO'],
        }
        authinfo = {
            'code': 200,
            'cookie': cookie,
            'cfgmgr': authdata[1],
            'username': authdata[2],
            'userdata': authdata[0]
        }
        if authdata[3] is not None:
            auditmsg['tenant'] = authdata[3]
            authinfo['tenant'] = authdata[3]
        auditmsg['user'] = util.stringify(authdata[2])
        if sessid is not None:
            authinfo['sessionid'] = sessid
        if not skiplog:
            auditlog.log(auditmsg)
        if 'csrftoken' in httpsessions[sessid]:
            authinfo['authtoken'] = httpsessions[sessid]['csrftoken']
        httpsessions[sessid]['cfgmgr'] = authdata[1]
        return authinfo
    elif authdata is None:
        return {'code': 401}
    else:
        return {'code': 403}
Beispiel #12
0
def sessionhdl(connection, authname, skipauth=False):
    # For now, trying to test the console stuff, so let's just do n4.
    authenticated = False
    authdata = None
    cfm = None
    if skipauth:
        authenticated = True
        cfm = configmanager.ConfigManager(tenant=None, username=authname)
    elif authname:
        authdata = auth.authorize(authname, element=None)
        if authdata is not None:
            cfm = authdata[1]
            authenticated = True
    send_data(connection, "Confluent -- v0 --")
    while not authenticated:  # prompt for name and passphrase
        send_data(connection, {'authpassed': 0})
        response = tlvdata.recv(connection)
        authname = response['username']
        passphrase = response['password']
        # note(jbjohnso): here, we need to authenticate, but not
        # authorize a user.  When authorization starts understanding
        # element path, that authorization will need to be called
        # per request the user makes
        authdata = auth.check_user_passphrase(authname, passphrase)
        if authdata is None:
            auditlog.log({
                'operation': 'connect',
                'user': authname,
                'allowed': False
            })
        else:
            authenticated = True
            cfm = authdata[1]
    send_data(connection, {'authpassed': 1})
    request = tlvdata.recv(connection)
    while request is not None:
        try:
            process_request(connection, request, cfm, authdata, authname,
                            skipauth)
        except exc.ForbiddenRequest:
            send_data(connection, {'errorcode': 403, 'error': 'Forbidden'})
            send_data(connection, {'_requestdone': 1})
        except exc.TargetEndpointBadCredentials:
            send_data(connection, {
                'errorcode': 502,
                'error': 'Bad Credentials'
            })
            send_data(connection, {'_requestdone': 1})
        except exc.TargetEndpointUnreachable as tu:
            send_data(connection, {
                'errorcode': 504,
                'error': 'Unreachable Target - ' + str(tu)
            })
            send_data(connection, {'_requestdone': 1})
        except exc.NotImplementedException:
            send_data(connection, {
                'errorcode': 501,
                'error': 'Not Implemented'
            })
            send_data(connection, {'_requestdone': 1})
        except exc.NotFoundException as nfe:
            send_data(connection, {'errorcode': 404, 'error': str(nfe)})
            send_data(connection, {'_requestdone': 1})
        except exc.InvalidArgumentException as iae:
            send_data(connection, {
                'errorcode': 400,
                'error': 'Bad Request - ' + str(iae)
            })
            send_data(connection, {'_requestdone': 1})
        except exc.LockedCredentials as lockedcred:
            send_data(connection, {
                'errorcode': 500,
                'error': 'Locked Credential Store'
            })
            send_data(connection, {'_requestdone': 1})
        except exc.ConfluentException as e:
            if e.apierrorcode == 500:
                tracelog.log(traceback.format_exc(),
                             ltype=log.DataTypes.event,
                             event=log.Events.stacktrace)
            send_data(
                connection, {
                    'errorcode': e.apierrorcode,
                    'error': e.apierrorstr,
                    'detail': e.get_error_body()
                })
            send_data(connection, {'_requestdone': 1})
        except SystemExit:
            sys.exit(0)
        except:
            tracelog.log(traceback.format_exc(),
                         ltype=log.DataTypes.event,
                         event=log.Events.stacktrace)
            send_data(connection, {
                'errorcode': 500,
                'error': 'Unexpected error'
            })
            send_data(connection, {'_requestdone': 1})
        request = tlvdata.recv(connection)