Example #1
0
    def on_open(self, request):
        from settings import COOKIE_SECRET
        from tornado.web import decode_signed_value

        self.session_id = None
        self.logged_in = None

        if 'session_id' in request.cookies:
            self.session_id = decode_signed_value(
                COOKIE_SECRET, 'session_id',
                unicode(request.get_cookie('session_id').value))

            global CURRENT_SESSIONS
            CURRENT_SESSIONS[self.session_id] = self

        if 'logged_in' in request.cookies:
            val = decode_signed_value(
                COOKIE_SECRET, 'logged_in',
                unicode(request.get_cookie('logged_in').value))
            if val != '':
                self.logged_in = val

            if self.logged_in is not None:
                global LOGGED_IN_SESSIONS
                LOGGED_IN_SESSIONS[self.logged_in] = self
Example #2
0
 def get_current_user(self):
     max_days_valid = 365
     # check for https comunication
     using_ssl = (self.request.headers.get('X-Scheme', 'http') == 'https')
     if not using_ssl:
         info('Not using SSL')
     else:
         info('Using SSL')
     # get the token for authentication
     token = self.request.headers.get("Linc-Api-AuthToken")
     res = None
     if token:
         # Decode to test
         try:
             token = token_decode(token, self.settings['token_secret'])
             vtoken = web.decode_signed_value(
                 self.settings["cookie_secret"],
                 'authtoken',
                 token,
                 max_age_days=max_days_valid)
         except Exception as e:
             info(e)
             vtoken = None
         if vtoken:
             dtoken = loads(vtoken.decode('utf-8'))
             if dtoken['username'] in self.settings['tokens'].keys() and \
                self.settings['tokens'][dtoken['username']]['token'] == dtoken['token']:
                 res = dtoken
         else:
             # Validation error
             self.token_passed_but_invalid = True
     return res
Example #3
0
    def get_current_user(self):

        #判断从app端过来的请求
        user_id = ''
        self.get_paras_dict()
        try:

            user_agent = self.request.headers.get('Request-Type') \
                if self.request.headers.get('Request-Type') else self.qdict.get('Request-Type')

            if user_agent and user_agent == 'apicloud':  #从apicloud来

                login_token = self.request.headers.get('login_token') \
                    if self.request.headers.get('login_token') else self.qdict.get('login_token')#获取客户端token

                if login_token:
                    user_json = decode_signed_value(
                        self.application.settings["cookie_secret"],
                        'loginuser', login_token)  #判断token合法性
                    if user_json:
                        user_info = ujson.loads(user_json)
                        user_id = user_info.get('Fid')

            else:  #微信端
                user_json = self.get_secure_cookie("loginuser", None)
                if user_json:
                    user_info = ujson.loads(user_json)
                    user_id = user_info.get('Fid')

        except Exception, e:
            pass
Example #4
0
    def test_register_post(self, mock_time):
        mock_time.return_value = 100
        response = self.fetch("/register",
                              method="POST",
                              body=urllib.parse.urlencode({
                                  "register-name":
                                  "New User",
                                  "register-email":
                                  "*****@*****.**",
                                  "register-password":
                                  "******"
                              }))
        self.assertEqual(302, response.code)
        self.assert_redirected_path_equals("/", response)

        user = self.store.fetch(User, "*****@*****.**")
        self.assertIsNotNone(user, "creates new user")
        self.assertEqual("New User", user.name)
        self.assertTrue(user.authenticate("whatever"))
        self.assertEqual("*****@*****.**", user.email)

        self.assertTrue("Set-Cookie" in response.headers)

        cookie = Cookie.SimpleCookie()
        cookie.load(response.headers["Set-Cookie"])

        self.assertTrue("token" in cookie)
        token_value = decode_signed_value(config.COOKIE_SECRET, "token",
                                          cookie["token"].value)

        self.assertEqual(user.token, token_value.decode("utf8"))
Example #5
0
    def test_login(self):

    
        ws = yield websocket_connect('ws://localhost:%i/swipe/websocket'%self.get_http_port(), io_loop=self.io_loop)

        # correct username and password
        ws.write_message("login/diego/password/"+self.sid)
        result = yield ws.read_message()
        assert result == 'login success'

        # confirm that session was created

        db = couch.AsyncCouch(os.environ["D_and_D_DATABASE"])
        sessions = yield db.get_doc('sessions')

        key = decode_signed_value(
                    'swipe',
                    'sid', 
                    self.sid, 
                    max_age_days=31,
                    min_version=None)

        assert sessions.get(key) != None, "there is no session with that key"

        
        # correct username but wrong password
        ws.write_message("login/diego/wrongpassword/"+self.sid)
        result = yield ws.read_message()
        assert result == 'wrong password'

        # correct username but wrong password
        ws.write_message("login/wrongusername/password/"+self.sid)
        result = yield ws.read_message()
        assert result == 'account does not exist'
Example #6
0
    def on_open(self, request):
        self.user = None
        try:
            value = json.loads(request.cookies['u'].coded_value)
        except KeyError:
            self.broadcast([self], json.dumps([['connect_ret', {'code': -1}]]))
            return False

        key = decode_signed_value(config.COOKIE_SECRET,
                                  'u',
                                  value,
                                  max_age_days=31,
                                  min_version=None)
        user = User.get_by_key(key)
        if user is None:
            self.broadcast([self], json.dumps([['connect_ret', {'code': -1}]]))
            return False

        self.user = user
        self.broadcast([self],
                       json.dumps([[
                           'connect_ret', {
                               'code': 0,
                               'username': user.username,
                               "msg_log": ChatLog.get_list()
                           }
                       ]]))
        self.visitors.add(self)
Example #7
0
 def get_current_user(self):
     if not self.opts.get("password"):
         return "authorized"
     auth_header = self.request.headers.get("Authorization",
                                            "").split(" ")[-1]
     return decode_signed_value(self.application.settings['cookie_secret'],
                                'token', auth_header)
Example #8
0
 def override_user(self):
     '''
     Use ``X-Gramex-User`` HTTP header to override current user for the session.
     Use ``X-Gramex-OTP`` HTTP header to set user based on OTP.
     ``?gramex-otp=`` is a synonym for X-Gramex-OTP.
     '''
     headers = self.request.headers
     cipher = headers.get('X-Gramex-User')
     if cipher:
         import json
         try:
             user = json.loads(decode_signed_value(
                 conf.app.settings['cookie_secret'], 'user', cipher,
                 max_age_days=self._session_expiry))
         except Exception:
             reason = '%s: invalid X-Gramex-User: %s' % (self.name, cipher)
             raise HTTPError(BAD_REQUEST, reason=reason)
         else:
             app_log.debug('%s: Overriding user to %r', self.name, user)
             self.session['user'] = user
             return
     otp = headers.get('X-Gramex-OTP') or self.get_argument('gramex-otp', None)
     if otp:
         otp_data = self._session_store.load('otp:' + otp, None)
         if not isinstance(otp_data, dict) or '_t' not in otp_data or 'user' not in otp_data:
             reason = '%s: invalid X-Gramex-OTP: %s' % (self.name, otp)
             raise HTTPError(BAD_REQUEST, reason=reason)
         elif otp_data['_t'] < time.time():
             reason = '%s: expired X-Gramex-OTP: %s' % (self.name, otp)
             raise HTTPError(BAD_REQUEST, reason=reason)
         self._session_store.dump('otp:' + otp, None)
         self.session['user'] = otp_data['user']
Example #9
0
 def get_cookie(self, name):
     cookie = decode_signed_value(
         config.COOKIE_SECRET, name, self.cookies[name].value
     )
     if cookie:
         return cookie.decode()
     return None
Example #10
0
 def get_current_user(self):
     self.require_setting("secret_key", "secure key")
     secret = self.application.settings["secret_key"]
     auth = self.request.headers.get('Authorization')
     if auth:
         x = auth.split()
         if len(x) == 2:
             # idea: 可以根据不同的 x[0] 使用不同的验证机制
             if x[0] == 'OOC':
                 sid = decode_signed_value(secret, "Sid", x[1])
                 if not sid:
                     logging.warning("fake sid!")
                     # FIXME!
                     # raise HTTPError(403, reason="fake_sid")
                     return
                 sid = sid.decode()
                 s = self.db.query(Session).filter_by(sid=sid).first()
                 if s:
                     if s.is_valid():
                         s.user.last_active = datetime.datetime.utcnow()
                         s.refresh_expired()
                         return s.user
                     else:
                         # FIXME!
                         # raise HTTPError(403, reason="session_expired")
                         logging.warn('%s: session is expired',
                                      s.user.username)
Example #11
0
 def get_secure_cookie(self, name):
     '''A helper method to get a cookie that was set securely.'''
     for cookie in self.auth_handler._new_cookies:
         if name in cookie.keys():
             cookie_value = cookie[name].value
             result = decode_signed_value(settings.COOKIE_SECRET, name, cookie_value)
             return result
Example #12
0
 def get_current_user(self):
     self.require_setting("secret_key", "secure key")
     secret = self.application.settings["secret_key"]
     auth = self.request.headers.get('Authorization')
     if auth:
         x = auth.split()
         if len(x) == 2:
             # idea: 可以根据不同的 x[0] 使用不同的验证机制
             if x[0] == 'OOC':
                 sid = decode_signed_value(secret, "Sid", x[1])
                 if not sid:
                     logging.warning("fake sid!")
                     # FIXME!
                     # raise HTTPError(403, reason="fake_sid")
                     return
                 sid = sid.decode()
                 s = self.db.query(Session).filter_by(sid=sid).first()
                 if s:
                     if s.is_valid():
                         s.user.last_active = datetime.datetime.utcnow()
                         s.refresh_expired()
                         return s.user
                     else:
                         # FIXME!
                         # raise HTTPError(403, reason="session_expired")
                         logging.warn('%s: session is expired',
                                      s.user.username)
Example #13
0
 def assert_cookie_value(self, name, value, response):
     self.assertTrue("Set-Cookie" in response.headers)
     cookie = Cookie.SimpleCookie(response.headers["Set-Cookie"])
     self.assertTrue(name in cookie, "expected {} cookie".format(name))
     actual_value = decode_signed_value(
         config.COOKIE_SECRET, name, cookie[name].value)
     self.assertEqual(value, actual_value)
Example #14
0
 def user(self):
     from ..config import config
     user = self.cookies.get('user')
     if user is None or config.cookie_secret is None:
         return None
     return decode_signed_value(config.cookie_secret, 'user',
                                user).decode('utf-8')
Example #15
0
 def valid(self, token):
     raw = web.decode_signed_value(self.key, self.value_name, token,
                                   self.lifetime)
     if raw is None:
         raise ValueError("Invalid token")
     else:
         return json.loads(raw)
    def test_register_post(self, mock_time):
        mock_time.return_value = 100
        response = self.fetch(
            "/register", method="POST", body=urllib.urlencode({
                "register-name": "New User",
                "register-email": "*****@*****.**",
                "register-password": "******"
            }))
        self.assertEqual(302, response.code)
        self.assert_redirected_path_equals("/", response)

        user = self.store.fetch(User, "*****@*****.**")
        self.assertIsNotNone(user, "creates new user")
        self.assertEqual("New User", user.name)
        self.assertTrue(user.authenticate("whatever"))
        self.assertEqual("*****@*****.**", user.email)

        self.assertTrue("Set-Cookie" in response.headers)

        cookie = Cookie.SimpleCookie()
        cookie.load(response.headers["Set-Cookie"])

        self.assertTrue("token" in cookie)
        token_value = decode_signed_value(
            config.COOKIE_SECRET, "token", cookie["token"].value)

        self.assertEqual(user.token, token_value)
Example #17
0
def foo():
    hash = hmac.new(secret, digestmod=hashlib.sha1)
    hash.update(str(remote_ip))
    hash.update(user_agent)
    hash.update(id)
    hash.update(domain)
    identity = base64.urlsafe_b64encode(hash.digest()).rstrip('=')
    access_token = decode_signed_value("access_token", access_token)
Example #18
0
def info_get_secure_cookie(info, name, value=None, max_age_days=31,
                      min_version=None):

    if value is None:
        value = get_morsel_cookie(info,name)
    return decode_signed_value(SETTINGS["cookie_secret"],
                                   name, value, max_age_days=max_age_days,
                                   min_version=min_version)   
Example #19
0
 def get_secure_cookie(self, name):
     '''A helper method to get a cookie that was set securely.'''
     for cookie in self.auth_handler._new_cookies:
         if name in cookie.keys():
             cookie_value = cookie[name].value
             result = decode_signed_value(settings.COOKIE_SECRET, name,
                                          cookie_value)
             return result
Example #20
0
 def DecodeUnsubscribeCookie(cls, unsubscribe_cookie):
   """Decode a user unsubscribe cookie that is passed as an argument to the unsubscribe handler.
   Returns the unsubscribe dict containing the user_id and email_type originally passed to
   CreateUnsubscribeCookie.
   """
   value = web.decode_signed_value(secrets.GetSecret('invite_signing'),
                                   'unsubscribe',
                                   unsubscribe_cookie)
   return None if value is None else json.loads(value)
Example #21
0
 def access_token(self):
     from ..config import config
     access_token = self.cookies.get('access_token')
     if access_token is None:
         return None
     access_token = decode_signed_value(config.cookie_secret, 'access_token', access_token)
     if self.encryption is None:
         return access_token.decode('utf-8')
     return self.encryption.decrypt(access_token).decode('utf-8')
Example #22
0
 def get_current_user(self):
     if not self.opts.get("password"):
         return "authorized"
     auth_header = self.request.headers.get(
         "Authorization", "").split(" ")[-1]
     return decode_signed_value(
         self.application.settings['cookie_secret'],
         'token',
         auth_header
     )
Example #23
0
def decode_cookie(response, name, max_age):
    cookies = response.headers.get_list('Set-Cookie')
    for cookie in cookies:
        parsed = parse_cookie(cookie)
        if name not in parsed:
            continue
        result = decode_signed_value(secret_conf.cookie_secret, name,
                                     parsed[name], max_age)
        return result
    return None
Example #24
0
def decode_play_id(play_id):
    data = web.decode_signed_value(
        secret=config['play']['secret'],
        name='play_id',
        value=play_id,
        max_age_days=0.3,
    )
    if not data:
        raise web.HTTPError(400, 'Play id invalid')
    return utils.json_loads(data)
Example #25
0
    def decrypt_value(self, key: str, value: str) -> bytes:
        """Decrypt a value that is encrypted using Tornado's secure cookie
        signing methods.

        :param key: The name of the field containing the value
        :param value: The value to decrypt
        :rtype: str

        """
        return web.decode_signed_value(self.settings['cookie_secret'], key,
                                       value)
Example #26
0
def setup_secrets(path, max_age_days=1000000, clear=True):
    '''
    Load ``<path>`` (which must be Path) as a YAML file. Update it into gramex.config.variables.

    If there's a ``SECRETS_URL:`` and ``SECRETS_KEY:`` key, the text from ``SECRETS_URL:`` is
    decrypted using ``secrets_key``.

    If there's a ``SECRETS_IMPORT:`` string, list or dict, the values are treated as file patterns
    pointing to other secrets file to be imported.
    '''
    if not path.is_file():
        return

    with path.open(encoding='utf-8') as handle:
        result = yaml.load(handle, Loader=yaml.SafeLoader)
    # Ignore empty .secrets.yaml
    if not result:
        return
    # If it's non-empty, it must be a dict
    if not isinstance(result, dict):
        raise ValueError('%s: must be a YAML file with a single dict' % path)
    # Clear secrets if we are re-initializing. Not if we're importing recursively.
    if clear:
        secrets.clear()
    # If SECRETS_URL: and SECRETS_KEY: are set, fetch secrets from URL and decrypted with the key.
    # This allows changing secrets remotely without access to the server.
    secrets_url = result.pop('SECRETS_URL', None)
    secrets_key = result.pop('SECRETS_KEY', None)
    if secrets_url and secrets_key:
        from urllib.request import urlopen
        from tornado.web import decode_signed_value
        app_log.info('Fetching remote secrets from %s', secrets_url)
        # Load string from the URL -- but ignore comments. file:// URLs are fine too
        value = yaml.load(urlopen(secrets_url),
                          Loader=yaml.SafeLoader)  # nosec
        value = decode_signed_value(secrets_key,
                                    '',
                                    value,
                                    max_age_days=max_age_days)
        result.update(loads(value.decode('utf-8')))
    # If SECRETS_IMPORT: is set, fetch secrets from those file(s) as well.
    # SECRETS_IMPORT: can be a file pattern, or a list/dict of file patterns
    secrets_import = result.pop('SECRETS_IMPORT', None)
    if secrets_import:
        # Create a list of file patterns to import from
        imports = (list(secrets_import.values()) if isinstance(
            secrets_import, dict) else
                   secrets_import if isinstance(secrets_import,
                                                (list,
                                                 tuple)) else [secrets_import])
        for pattern in imports:
            for import_path in path.parent.glob(pattern):
                setup_secrets(import_path, max_age_days, clear=False)
    secrets.update(result)
Example #27
0
def decrypt_value(key, value):
    """Decrypt a value that is encrypted using Tornado's secure cookie
    signing methods.

    :param str or bytes key: The name of the field containing the value
    :param str or bytes value: The value to decrypt
    :rtype: str

    """
    return web.decode_signed_value(
        os.environ.get('COOKIE_SECRET', DEFAULT_COOKIE_SECRET), key, value)
Example #28
0
 def get_edtr_current_user(self, user_cookie, callback):
     username = decode_signed_value(settings["cookie_secret"],
         "user", user_cookie.value,
         max_age_days=settings['cookie_expires'])
     # TODO cache
     user = yield motor.Op(
         UserModel.find_one, self.db, {"_id": username})
     if user:
         callback(user)
     else:
         callback(None)
Example #29
0
    def on_open(self, request):
        from settings import COOKIE_SECRET
        from tornado.web import decode_signed_value

        self.session_id = None
        self.logged_in = None

        if 'session_id' in request.cookies:
            self.session_id = decode_signed_value(COOKIE_SECRET, 'session_id', unicode(request.get_cookie('session_id').value))

            global CURRENT_SESSIONS
            CURRENT_SESSIONS[self.session_id] = self

        if 'logged_in' in request.cookies:
            val = decode_signed_value(COOKIE_SECRET, 'logged_in', unicode(request.get_cookie('logged_in').value))
            if val != '':
                self.logged_in = val

            if self.logged_in is not None:
                global LOGGED_IN_SESSIONS
                LOGGED_IN_SESSIONS[self.logged_in] = self
Example #30
0
 def on_open(self, info):
     try:
         value = info.cookies['user'].value
     except (KeyError, AttributeError):
         self.close()
     else:
         user = decode_signed_value(
             self.application.settings['cookie_secret'], 'user', value)
         if user:
             self.subscribe()
         else:
             self.close()
Example #31
0
File: base.py Project: hrl/Protoend
    def get_current_user(self):
        uid = self.request.headers.get('Authorization', None)
        if uid:
            uid = \
                decode_signed_value(self.application.settings["cookie_secret"],
                                    'uid', uid)
        try:
            current_user = self.session.query(models.User).get(uid.decode('utf8'))
        except Exception:
            current_user = None

        return current_user
Example #32
0
def decode_signed_string(strg, max_age_days):
    try:
        result = decode_signed_value(conf.get("secretKey"),
                                     "data",
                                     zlib.decompress(
                                         b64decode(strg, altchars=b'_-')),
                                     max_age_days=max_age_days)
    except (binascii.Error, zlib.error) as exc:
        return None
    if result is None:
        return None
    else:
        return result.decode('utf-8')
    def test_cookie_credentials(self):
        fetch_arguments = build_fetch_arguments("/foobar")
        credentials = CookieCredentials(
            cookie_name="auth", cookie_value="token", cookie_secret="foobar")
        credentials(fetch_arguments)
        self.assertTrue("Cookie" in fetch_arguments.headers)

        cookie = SimpleCookie()
        cookie.load(fetch_arguments.headers["Cookie"])
        self.assertTrue("auth" in cookie)
        cookie_value = cookie["auth"].value
        expected_value = decode_signed_value("foobar", "auth", cookie_value)
        self.assertEqual("token", expected_value.decode("utf-8"))
Example #34
0
    def get_current_user(self):
        uid = self.request.headers.get('Authorization', None)
        if uid:
            uid = \
                decode_signed_value(self.application.settings["cookie_secret"],
                                    'uid', uid)
        try:
            current_user = self.session.query(models.User).get(
                uid.decode('utf8'))
        except Exception:
            current_user = None

        return current_user
Example #35
0
 def on_open(self, info):
     try:
         value = info.cookies['user'].value
     except (KeyError, AttributeError):
         self.close()
     else:
         user = decode_signed_value(
             self.application.settings['cookie_secret'], 'user', value
         )
         if user:
             self.subscribe()
         else:
             self.close()
Example #36
0
 def get_cookie(self, name, default=None, max_age_days=31, min_version=None):
     """ Gets the value of the cookie with the given name, else default.
     Note that cookies only really work for web apps.
     """
     from tornado.web import decode_signed_value
     if name in self._cookies:
         value = self._cookies[name].value
         value = decode_signed_value(config.cookie_secret,
                                    name, value, max_age_days=max_age_days,
                                    min_version=min_version)
         return value.decode()
     else:
         return default
Example #37
0
def decode_cookies(response):
    '''Takes an HTTPResponse as the response.'''
    chunks = []
    for chunk in response.headers['Set-Cookie'].split(','):
        chunks.extend(chunk.split(';'))

    result = {}
    for chunk in chunks:
        s = chunk.split('=', 1)
        if len(s) < 2: continue
        name = s[0]
        value = s[1]
        result[name] = decode_signed_value(settings.COOKIE_SECRET, name, value.strip('"'))
    return result
    def test_cookie_credentials(self):
        fetch_arguments = build_fetch_arguments("/foobar")
        credentials = CookieCredentials(cookie_name="auth",
                                        cookie_value="token",
                                        cookie_secret="foobar")
        credentials(fetch_arguments)
        self.assertTrue("Cookie" in fetch_arguments.headers)

        cookie = SimpleCookie()
        cookie.load(fetch_arguments.headers["Cookie"])
        self.assertTrue("auth" in cookie)
        cookie_value = cookie["auth"].value
        expected_value = decode_signed_value("foobar", "auth", cookie_value)
        self.assertEqual("token", expected_value.decode("utf-8"))
Example #39
0
def decode_cookies(response):
    '''Takes an HTTPResponse as the response.'''
    chunks = []
    for chunk in response.headers['Set-Cookie'].split(','):
        chunks.extend(chunk.split(';'))

    result = {}
    for chunk in chunks:
        s = chunk.split('=', 1)
        if len(s) < 2: continue
        name = s[0]
        value = s[1]
        result[name] = decode_signed_value(settings.COOKIE_SECRET, name,
                                           value.strip('"'))
    return result
 def get_session(self):
     """ Decrypt, deserialze session object, check the timestamp too """
     try:
         if self.session_data is not None:
             session = json.loads(decode_signed_value(
                 secret=self.application.settings["cookie_secret"],
                 name="session",
                 value=self.session_data))
             if time.time() <= session['expires']:
                 return session
         else:
             logging.debug("Unauthenticated, no session data")
     except:
         logging.exception("Failed to deserialze session data")
     return None
Example #41
0
 def user_info(self):
     from ..config import config
     id_token = self.cookies.get('id_token')
     if id_token is None or config.cookie_secret is None:
         return None
     id_token = decode_signed_value(config.cookie_secret, 'id_token', id_token)
     if self.encryption is None:
         id_token = id_token
     else:
         id_token = self.encryption.decrypt(id_token)
     if b"." in id_token:
         signing_input, _ = id_token.rsplit(b".", 1)
         _, payload_segment = signing_input.split(b".", 1)
     else:
         payload_segment = id_token
     return json.loads(base64url_decode(payload_segment).decode('utf-8'))
 def get_session(self):
     ''' Decrypt, deserialze session object, check the timestamp too '''
     try:
         data = self.request.headers.get('X-ALL-IS-DUST', None)
         if data is not None:
             session = json.loads(decode_signed_value(
                 secret=self.application.settings["cookie_secret"],
                 name="session",
                 value=data))
             if time.time() <= session['expires']:
                 return session
         else:
             logging.debug("Unauthenticated, no session data")
     except:
         logging.exception("Failed to deserialze session data")
     return None
 def get_session(self):
     """ Decrypt, deserialze session object, check the timestamp too """
     try:
         if self.session_data is not None:
             session = json.loads(
                 decode_signed_value(
                     secret=self.application.settings["cookie_secret"],
                     name="session",
                     value=self.session_data))
             if time.time() <= session['expires']:
                 return session
         else:
             logging.debug("Unauthenticated, no session data")
     except:
         logging.exception("Failed to deserialze session data")
     return None
Example #44
0
 def get_session(self):
     """ Deserialze session object, check the timestamp too """
     try:
         data = self.request.headers.get('X-XSS-HUNTER', None)
         if data is not None:
             session = json.loads(
                 decode_signed_value(
                     secret=self.application.settings["cookie_secret"],
                     name="session",
                     value=data))
             if int(time.time()) <= session['expires']:
                 return session
         else:
             logging.debug("Unauthenticated, no session data")
     except:
         logging.exception("Failed to deserialze session data")
     return None
    def current_user_id(self):
        if CONFIG.COOKIE_SECRET:
            user_id = self.get_secure_cookie('user_id', min_version=2)
            if user_id:
                return user_id

            # user_id = self.get_secure_cookie("user_id")  # user_id
            # fixed no cookie value in User-Agent for Shockwave Flash and for lua upload
            if not user_id:
                secure_code = self.get_argument(
                    'code', '')  # code = self.get_cookie('user_id')
                if secure_code:
                    secure_user_id = unquote(secure_code)
                    user_id = decode_signed_value(
                        self.application.settings["cookie_secret"], 'user_id',
                        secure_user_id)
                    return user_id
Example #46
0
 def _update_cookies(self, headers):
     try:
         raw = headers['Set-Cookie']
         # remove expires + path
         raw = re.sub(r"; expires=[^;]+;", "", raw)
         raw = re.sub(r";? Path=[^,]+,", ";", raw)
         # last path
         raw = re.sub(r";? Path=[^,]$", "", raw)
         for cookie in raw.split(";"):
             (key, value) = cookie.split("=", 1)
             if key == "_xsrf":
                 self._xsrf = value
             elif key == "REMOTE_SESSION":
                 tmp = decode_signed_value('TecloigJink4', 'REMOTE_SESSION', value)
                 self.session_id = tmp.decode('ascii') if tmp else None
         self.__cookies = raw
     except KeyError:
         return
Example #47
0
    def on_message(self, message):
        """
        The only method supported at moment - auth - used to
        authorize websocket connection.
        """
        try:
            data = json_decode(message)
        except ValueError:
            self.close()
            return

        try:
            method = data["method"]
            params = data["params"]
        except (TypeError, KeyError):
            self.close()
            return

        if method == "auth":
            try:
                token = params["token"]
            except (KeyError, TypeError):
                self.close()
                return
            else:
                user = decode_signed_value(
                    self.application.settings['cookie_secret'], 'token', token
                )
                if user:
                    self.subscribe()
                    self.send(json_encode({
                        "method": "auth",
                        "body": True
                    }))
                else:
                    self.send(json_encode({
                        "method": "auth",
                        "body": False
                    }))
                    self.close()
                    return
        else:
            self.close()
            return
Example #48
0
    def on_message(self, message):
        """
        A message is sent by the client after creating the connection. The method verifies the user
        secret cookie and appends the connection to the opensockets dictionary.

        :param str message: The received message
        """
        user_id = decode_signed_value(settings["cookie_secret"], 'user', json.loads(message).get("register", "")).decode('utf-8')
        
        """
        If the user_id is other than None the verification has succeded, and the connection is appended to the 
        rest of the websockets related to the user.
        """
        if user_id is not None:
            if opensockets.get(user_id) is None:
                opensockets[user_id] = []
            opensockets[user_id].append(self)
        else:
            logging.debug("The user could not be found")
Example #49
0
    def login(self, username, password, sid):
        """
        implement login service
        """


        db = couch.AsyncCouch(os.environ["D_and_D_DATABASE"])

        # use login/get_creds mapview
        res = yield db.view('login','get_creds',key=username)

        # found a row with that username
        if len(res['rows']) == 1:

            # check password
            if res['rows'][0]['value'] == password:

                # setup session for sid

                sid = decode_signed_value(
                    'swipe',
                    'sid', 
                    sid, 
                    max_age_days=31,
                    min_version=None)

                # open session
                sessions = yield db.get_doc('sessions')

                # save user id in session
                sessions[sid] = res['rows'][0]['id']

                # save session
                yield db.save_doc(sessions)

                # may want to use base64
                self.conn.send("callback::login-%s-%s-%s::%s"%(username, password, sid, 'success'))

            else:
                self.conn.send("callback::login-%s-%s-%s::%s"%(username, password, sid, 'wrong password'))

        else:
            self.conn.send("callback::login-%s-%s-%s::%s"%(username, password, sid, 'account does not exist'))
Example #50
0
 def _VerifyAdminAuthResponse(self, exp_code, exp_has_admin_otp_cookie, response):
   """Deconstructs the admin otp cookie and verifies that test-user
   and timestamp are correct (timestamp within an epsilon of current
   time). Calls self.stop() on completion.
   """
   try:
     self.assertEqual(response.code, exp_code)
     set_cookie = response.headers.get('Set-Cookie', '')
     match = re.compile('admin_otp="(.*)"').match(set_cookie)
     if exp_has_admin_otp_cookie:
       self.assertTrue(match, 'Expecting admin_otp cookie, but none found.')
       cookie = match.group(1)
       decoded_cookie = web.decode_signed_value(self._tester._secret, basic_auth.COOKIE_NAME, cookie)
       admin, expires = json.loads(decoded_cookie)
       self.assertEqual(admin, 'test-user')
     else:
       self.assertFalse(match, 'Expecting no admin_otp cookie, but found one.')
   finally:
     self.stop()
Example #51
0
    def auth(*args, **kwargs):

        # get sid, which is alway the last paramiter
        sid = args[-1]

        # decode sid
        sid = decode_signed_value(
            config['cookie_secret'],
            'sid', 
            sid, 
            max_age_days=31,
            min_version=None)

        # open sessions
        db = couch.BlockingCouch(os.environ["D_and_D_DATABASE"])
        sessions = db.get_doc('sessions')

        # check if sid in in sessions
        if sessions.get(sid):
            func(*args, **kwargs)

        # session not found
        else:
            raise Exception('redirect to login')
Example #52
0
 def decode_signed_value(self, name, value):
     from tornado.web import decode_signed_value
     return decode_signed_value(self.application.settings["cookie_secret"],
                                name, value, max_age_days=31)
Example #53
0
    def on_message(self, message):
        message_json = message#.decode('utf-8')

        try:
            message_dict = json.loads(message_json)
        except ValueError as v:
            return
        
        if message_dict.get("register", None) is not None:
            user_id = decode_signed_value(settings["cookie_secret"], 'user', message_dict["register"]).decode('utf-8')
            
            if not user_id is None:
                if opensockets.get(user_id) is None:
                    opensockets[user_id] = []
                opensockets[user_id].append(self)
            else:
                pass

        elif message_dict.get("command", None) is not None:
            user_id = decode_signed_value(settings["cookie_secret"], 'user', message_dict.get("user_id", ""))
            
            if user_id is not None:
                user_id = user_id.decode('utf-8')
                user_pwd = pwd.getpwnam(user_id)
                try:
                    command = message_dict["command"]
                    p = ProcessReactor(user_pwd, user_pwd.pw_dir, io_loop, ip, opensockets, split(command), shell=True)
                    if processes.get(user_id, None) is None:
                        processes[user_id] = set()
                    processes[user_id].add(p)
                except Exception as e:
                    logging.warning(e)

        elif message_dict.get("remove", None) is not None:
            logging.debug("remove")
            user_id = decode_signed_value(settings["cookie_secret"], 'user', message_dict.get("user_id", ""))
            if user_id is not None:
                identifier = message_dict.get("remove", None)
                if identifier is not None:
                    print("identifier", identifier)
                    process = next((x for x in processes.get(user_id, set()) if x.identifier == identifier), None)
                    if process is not None:
                        process.stop()
                        processes[user_id].remove(process)

        elif message_dict.get("removeshell", None) is not None:
            logging.debug("removeshell")
            user_id = decode_signed_value(settings["cookie_secret"], 'user', message_dict.get("user_id", ""))
            if user_id is not None:
                identifiers = message_dict.get("removeshell", None)
                if identifiers is not None:
                    try:
                        identifiers_dict = message_dict["removeshell"]
                        for identifier in identifiers:
                            logging.debug(identifier)
                            logging.debug(processes.get(user_id, set()))
                            process = next((x for x in processes.get(user_id, set()) if x.identifier == identifier), None)
                            if process is not None:
                                logging.debug("Killing")
                                process.stop()
                                processes[user_id].remove(process)
                    except ValueError as v:
                        logging.warning(v)
                    except KeyError as k:
                        logging.warning(k)
Example #54
0
def untokenize_value(key, token):
    try:
        return decode_signed_value(key, "0", base64.b64decode(token)[_TOKENIZE_RANDOM_PADDING:])
    except (TypeError, ValueError):
        return None
Example #55
0
 def get_user_from_cookies(self):
     return decode_signed_value(secret=settings['cookie_secret'], name="user", value=self._user_login)
Example #56
0
 def get_user_id(self, sid_cookie):
     sid = decode_signed_value(settings.TORNADO_APP['cookie_secret'],
                               settings.SID_COOKIE, sid_cookie)
     session = Session(sid)
     session.load()
     return session['user']
Example #57
0
 def _decode_user_token(self, value, max_age_days=31, min_version=None):
     return decode_signed_value(self.application.settings['cookie_secret'],
                                'token', value, max_age_days=max_age_days,
                                min_version=min_version)