def load_cookie(self): if "Cookie" in self.headers: print("Cookie") self.cookie = cookies.SimpleCookie(self.headers["Cookie"]) else: self.cookie = cookies.SimpleCookie()
from http import cookies import datetime def show_cookie(c): print(c) for key, morsel in c.items(): print() print('key =', morsel.key) print(' value =', morsel.value) print(' coded_value =', morsel.coded_value) for name in morsel.keys(): if morsel[name]: print(' {} = {}'.format(name, morsel[name])) c = cookies.SimpleCookie() # A cookie with a value that has to be encoded # to fit into the header c['encoded_value_cookie'] = '"cookie,value;"' c['encoded_value_cookie']['comment'] = 'Has escaped punctuation' # A cookie that only applies to part of a site c['restricted_cookie'] = 'cookie_value' c['restricted_cookie']['path'] = '/sub/path' c['restricted_cookie']['domain'] = 'PyMOTW' c['restricted_cookie']['secure'] = True # A cookie that expires in 5 minutes c['with_max_age'] = 'expires in 5 minutes' c['with_max_age']['max-age'] = 300 # seconds
def create_session(): session_id = db.create_session() cookies_object = cookies.SimpleCookie() cookies_object["session_id"] = session_id print(cookies_object.output()) #upisivanje cookie-a u header return session_id
def test_illegal_chars(self): rawdata = "a=b; c,d=e" C = cookies.SimpleCookie() with self.assertRaises(cookies.CookieError): C.load(rawdata)
def build_request(self): request = '#method# #uri##version#%s#headers#%s#data#' % \ (self.CRLF, self.CRLF) request = request.replace('#method#', self.request_object.method) # We add a space after here to account for HEAD requests with no url request = request.replace('#uri#', self.request_object.uri + ' ') request = request.replace('#version#', self.request_object.version) available_cookies = self.find_cookie() # If the user has requested a tracked cookie and we have one set it if available_cookies: cookie_value = '' if 'cookie' in list(self.request_object.headers.keys()): # Create a SimpleCookie out of our provided cookie try: provided_cookie = cookies.SimpleCookie() provided_cookie.load(self.request_object.headers['cookie']) except cookies.CookieError as err: raise errors.TestError( 'Error processing the existing cookie into a ' 'SimpleCookie', { 'msg': str(err), 'set_cookie': str(self.request_object.headers['cookie']), 'function': 'http.HttpResponse.build_request' }) result_cookie = {} for cookie_key, cookie_morsal in list(provided_cookie.items()): result_cookie[cookie_key] = \ provided_cookie[cookie_key].value for cookie in available_cookies: for cookie_key, cookie_morsal in cookie: if cookie_key in list(result_cookie.keys()): # we don't overwrite a user specified # cookie with a saved one pass else: result_cookie[cookie_key] = \ cookie[cookie_key].value for key, value in list(result_cookie.items()): cookie_value += (str(key) + '=' + str(value) + '; ') # Remove the trailing semicolon cookie_value = cookie_value[:-2] self.request_object.headers['cookie'] = cookie_value else: for cookie in available_cookies: for cookie_key, cookie_morsal in list(cookie.items()): cookie_value += (str(cookie_key) + '=' + str(cookie_morsal.coded_value) + '; ') # Remove the trailing semicolon cookie_value = cookie_value[:-2] self.request_object.headers['cookie'] = cookie_value # Expand out our headers into a string headers = '' if self.request_object.headers != {}: for hname, hvalue in self.request_object.headers.items(): headers += str(hname) + ': ' + \ str(hvalue) + self.CRLF request = request.replace('#headers#', headers) # If we have data append it if self.request_object.data != '': # Before we do that see if that is a charset encoding = 'utf-8' # Check to see if we have a content type and magic is # off (otherwise UTF-8) if 'Content-Type' in list(self.request_object.headers.keys()) and \ self.request_object.stop_magic is False: pattern = re.compile(r'\;\s{0,1}?charset\=(.*?)(?:$|\;|\s)') m = re.search(pattern, self.request_object.headers['Content-Type']) if m: possible_choices = \ list(set(encodings.aliases.aliases.keys())) + \ list(set(encodings.aliases.aliases.values())) choice = m.group(1) # Python will allow these aliases but doesn't list them choice = choice.replace('-', '_') choice = choice.lower() if choice in possible_choices: encoding = choice try: data_bytes = \ self.request_object.data.encode(encoding, 'strict') except UnicodeError as err: raise errors.TestError( 'Error encoding the data with the charset specified', { 'msg': str(err), 'Content-Type': str(self.request_object.headers['Content-Type']), 'data': str(self.request_object.data), 'function': 'http.HttpResponse.build_request' }) data = util.ensure_str(data_bytes) else: data = '' request = request.replace('#data#', data).encode('utf-8', 'strict') # If we have a Raw Request we should use that instead if self.request_object.raw_request is not None: if self.request_object.encoded_request is not None: raise errors.TestError( 'Cannot specify both raw and encoded modes', {'function': 'http.HttpUA.build_request'}) request = self.request_object.raw_request.encode('utf-8', 'strict') # We do this regardless of magic if you want to send a literal # '\' 'r' or 'n' use encoded request. request = request.decode('unicode_escape') if self.request_object.encoded_request is not None: request = base64.b64decode(self.request_object.encoded_request) # Use the request created self.request = util.ensure_binary(request)
def createCookie(): cookie = cookies.SimpleCookie() token = secrets.token_hex(15) cookie["session"] = token print(cookie) return token
def test_secure_httponly_false_if_not_present(self): C = cookies.SimpleCookie() C.load('eggs=scrambled; Path=/bacon') self.assertFalse(C['eggs']['httponly']) self.assertFalse(C['eggs']['secure'])
def loadCookie(self): if "Cookie" in self.headers: self.cookie = cookies.SimpleCookie(self.headers["Cookie"]) else: self.cookie = cookies.SimpleCookie()
username = form.getvalue("username") password = form.getvalue("password") form_validate = False if username == secret.username and password == secret.password: form_validate = True # Q5 # # ----------------------------------------- # if cookie sent via http headers # instantiate a SimpleCookie object and store cookie sent # check against form values # # setting a cookie from: http://cgi.tutorial.codepoint.net/set-the-cookie # instantiate and retrieve cookie from: http://cgi.tutorial.codepoint.net/retrieve-the-cookie # ----------------------------------------- cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE')) cookie_username = None cookie_password = None validated = False # print(cookie) if cookie.get("username"): cookie_username = cookie.get("username").value if cookie.get("password"): cookie_password = cookie.get("password").value if cookie_username == secret.username and cookie_password == secret.password: validated = True if validated: username = cookie_username
def test_extra_spaces(self): C = cookies.SimpleCookie() C.load('eggs = scrambled ; secure ; path = bar ; foo=foo ') self.assertEqual(C.output(), 'Set-Cookie: eggs=scrambled; Path=bar; Secure\r\nSet-Cookie: foo=foo')
def test_set_cookie_already_exists(self): self.rh._new_cookie = Cookie.SimpleCookie() self.rh._new_cookie["name"] = "value" self.rh.set_cookie("name", "value")
def test_set_secure_httponly_attrs(self): C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['secure'] = True C['Customer']['httponly'] = True self.assertEqual(C.output(), 'Set-Cookie: Customer="WILE_E_COYOTE"; HttpOnly; Secure')
def generic_upstream_cookies_verify_test(ar, headers, path, cookies_to_send=None, assert_cookies_present=None, assert_cookies_absent=None): """Test if cookies that are passed to the upstream by AR are correct Helper function meant to simplify writing multiple tests testing the same thing for different endpoints. Arguments: ar: Admin Router object, an instance of runner.(ee|open).Nginx headers (dict): headers dict that contains DC/OS authentication token and cookies. The auth data it contains must be valid. path (str): path for which request should be made cookies_to_send (dict): dictionary containing all the cookies that should be send in the request assert_cookies_present (dict): cookies to test where key is the asserted cookie name and value is expected value of the cookie assert_cookies_absent (list or set): cookies that *MUST NOT* be present in the upstream request """ url = ar.make_url_from_path(path) resp = requests.get(url, cookies=cookies_to_send, allow_redirects=False, headers=headers) assert resp.status_code == 200 req_data = resp.json() # Let's make sure that we got not more than one 'Cookie' header: # https://tools.ietf.org/html/rfc6265#section-5.4 cookie_headers = [] for header in req_data['headers']: if header[0] == 'Cookie': cookie_headers.append(header) assert len(cookie_headers) <= 1 if len(cookie_headers) == 1: jar = cookies.SimpleCookie() # It is a list containing a single tuple (`header name`, `header value`), # we need the second element of it - the value of the header: jar.load(cookie_headers[0][1]) else: jar = {} if assert_cookies_present is not None: jar_cookies_dict = { x: jar[x].value for x in jar if x in assert_cookies_present } # We only want to check the keys present in cookies_present_dict assert jar_cookies_dict == assert_cookies_present if assert_cookies_absent is not None: jar_cookies_set = set(jar.keys()) cookies_absent_set = set(assert_cookies_absent) assert jar_cookies_set.intersection(cookies_absent_set) == set()
def test_bad_attrs(self): # issue 16611: make sure we don't break backward compatibility. C = cookies.SimpleCookie() C.load('cookie=with; invalid; version; second=cookie;') self.assertEqual(C.output(), 'Set-Cookie: cookie=with\r\nSet-Cookie: second=cookie')
def set_cookie(self, name, value, expires=None, max_age=None, domain=None, path=None, secure=None, http_only=True): """Set a response cookie. Note: This method can be called multiple times to add one or more cookies to the response. See Also: To learn more about setting cookies, see :ref:`Setting Cookies <setting-cookies>`. The parameters listed below correspond to those defined in `RFC 6265`_. Args: name (str): Cookie name value (str): Cookie value Keyword Args: expires (datetime): Specifies when the cookie should expire. By default, cookies expire when the user agent exits. (See also: RFC 6265, Section 4.1.2.1) max_age (int): Defines the lifetime of the cookie in seconds. By default, cookies expire when the user agent exits. If both `max_age` and `expires` are set, the latter is ignored by the user agent. Note: Coercion to ``int`` is attempted if provided with ``float`` or ``str``. (See also: RFC 6265, Section 4.1.2.2) domain (str): Restricts the cookie to a specific domain and any subdomains of that domain. By default, the user agent will return the cookie only to the origin server. When overriding this default behavior, the specified domain must include the origin server. Otherwise, the user agent will reject the cookie. (See also: RFC 6265, Section 4.1.2.3) path (str): Scopes the cookie to the given path plus any subdirectories under that path (the "/" character is interpreted as a directory separator). If the cookie does not specify a path, the user agent defaults to the path component of the requested URI. Warning: User agent interfaces do not always isolate cookies by path, and so this should not be considered an effective security measure. (See also: RFC 6265, Section 4.1.2.4) secure (bool): Direct the client to only return the cookie in subsequent requests if they are made over HTTPS (default: ``True``). This prevents attackers from reading sensitive cookie data. Note: The default value for this argument is normally ``True``, but can be modified by setting :py:attr:`~.ResponseOptions.secure_cookies_by_default` via :any:`API.resp_options`. Warning: For the `secure` cookie attribute to be effective, your application will need to enforce HTTPS. (See also: RFC 6265, Section 4.1.2.5) http_only (bool): Direct the client to only transfer the cookie with unscripted HTTP requests (default: ``True``). This is intended to mitigate some forms of cross-site scripting. (See also: RFC 6265, Section 4.1.2.6) Raises: KeyError: `name` is not a valid cookie name. ValueError: `value` is not a valid cookie value. .. _RFC 6265: http://tools.ietf.org/html/rfc6265 """ if not is_ascii_encodable(name): raise KeyError('"name" is not ascii encodable') if not is_ascii_encodable(value): raise ValueError('"value" is not ascii encodable') value = str(value) if self._cookies is None: self._cookies = http_cookies.SimpleCookie() try: self._cookies[name] = value except http_cookies.CookieError as e: # pragma: no cover # NOTE(tbug): we raise a KeyError here, to avoid leaking # the CookieError to the user. SimpleCookie (well, BaseCookie) # only throws CookieError on issues with the cookie key raise KeyError(str(e)) if expires: # set Expires on cookie. Format is Wdy, DD Mon YYYY HH:MM:SS GMT # NOTE(tbug): we never actually need to # know that GMT is named GMT when formatting cookies. # It is a function call less to just write "GMT" in the fmt string: fmt = '%a, %d %b %Y %H:%M:%S GMT' if expires.tzinfo is None: # naive self._cookies[name]['expires'] = expires.strftime(fmt) else: # aware gmt_expires = expires.astimezone(GMT_TIMEZONE) self._cookies[name]['expires'] = gmt_expires.strftime(fmt) if max_age: # RFC 6265 section 5.2.2 says about the max-age value: # "If the remainder of attribute-value contains a non-DIGIT # character, ignore the cookie-av." # That is, RFC-compliant response parsers will ignore the max-age # attribute if the value contains a dot, as in floating point # numbers. Therefore, attempt to convert the value to an integer. self._cookies[name]['max-age'] = int(max_age) if domain: self._cookies[name]['domain'] = domain if path: self._cookies[name]['path'] = path if secure is None: is_secure = self.options.secure_cookies_by_default else: is_secure = secure if is_secure: self._cookies[name]['secure'] = True if http_only: self._cookies[name]['httponly'] = http_only
def get_session_id(): http_cookies_str = os.environ.get('HTTP_COOKIE', '') get_all_cookies_object = cookies.SimpleCookie(http_cookies_str) session_id = get_all_cookies_object.get("session_id").value if get_all_cookies_object.get("session_id") else None return session_id
def _get_handler(self): nonlocal counter nonlocal sucuri_reqs_1 nonlocal sucuri_reqs_2 nonlocal sucuri_reqs_3 try: self.validate_headers() except Exception: self.send_response(500) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Headers failed validation!") raise if self.path == "/": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Root OK?") elif self.path == "/favicon.ico": self.send_response(404) self.end_headers() elif self.path == "/raw-txt": self.send_response(200) self.send_header('Content-type', "text/plain") self.end_headers() self.wfile.write(b"Root OK?") elif self.path == "/html-decode": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Root OK?") elif self.path == "/html/real": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><body>Root OK?</body></html>") elif self.path == "/compressed/deflate": self.send_response(200) self.send_header('Content-Encoding', 'deflate') self.send_header('Content-type', "text/html") self.end_headers() inb = b"Root OK?" cobj = zlib.compressobj(wbits=-zlib.MAX_WBITS) t1 = cobj.compress(inb) + cobj.flush() self.wfile.write(t1) elif self.path == "/compressed/gzip": self.send_response(200) self.send_header('Content-Encoding', 'gzip') self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(gzip.compress(b"Root OK?")) elif self.path == "/json/invalid": self.send_response(200) self.send_header('Content-type', "application/json") self.end_headers() self.wfile.write(b"LOLWAT") elif self.path == "/json/valid": self.send_response(200) self.send_header('Content-type', "application/json") self.end_headers() self.wfile.write(b'{"oh" : "hai"}') elif self.path == "/json/no-coding": self.send_response(200) self.end_headers() self.wfile.write(b'{"oh" : "hai"}') elif self.path == "/filename/path-only.txt": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename/path-only-trailing-slash/": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename/content-disposition": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=lolercoaster.txt") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/path-only.txt": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=lolercoaster.txt") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition-html-suffix": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=lolercoaster.html") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition-quotes-1": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename='lolercoaster.html'") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition-quotes-2": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=\'lolercoaster.html\'") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition-quotes-spaces-1": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename='loler coaster.html'") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/content-disposition-quotes-spaces-2": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=\"loler coaster.html\"") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/filename_mime/explicit-html-mime": self.send_response(200) self.send_header('Content-type', "application/x-binary") self.send_header('Content-Disposition', "filename=lolercoaster.html") self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"LOLWAT?\x00\xff\xaa\x55!") elif self.path == "/redirect/bad-1": self.send_response(302) self.end_headers() elif self.path == "/redirect/bad-2": self.send_response(302) self.send_header('location', "bad-2") self.end_headers() elif self.path == "/redirect/bad-3": self.send_response(302) self.send_header('location', "gopher://www.google.com") self.end_headers() elif self.path == "/redirect/from-1": self.send_response(302) self.send_header('location', "to-1") self.end_headers() elif self.path == "/redirect/to-1": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Redirect-To-1") # I'm not completely sure this is completely a valid way to do redirects? elif self.path == "/redirect/from-2": self.send_response(302) self.send_header('uri', "to-2") self.end_headers() elif self.path == "/redirect/to-2": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Redirect-To-2") elif self.path == "/redirect/from-3": self.send_response(302) newurl = "http://{}:{}/redirect/to-3".format(self.server.server_address[0], self.server.server_address[1]) self.send_header('location', newurl) self.end_headers() elif self.path == "/redirect/to-3": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Redirect-To-3") elif self.path == "/redirect/from-4": self.send_response(302) self.send_header('Content-type', "text/html") self.end_headers() body = "<html><body><script>window.location.href='/redirect/to-4'</script></body></html>" self.wfile.write(body.encode("utf-8")) elif self.path == "/redirect/to-4": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Redirect-To-4") # This looks like a cross-domain request elif self.path == "/redirect/from-5": self.send_response(302) newurl = "http://{}:{}/".format(self.server.server_address[0], self.server.server_address[1]) self.send_header('location', newurl) self.end_headers() ################################################################################################################################## # Multiple redirects ################################################################################################################################## elif self.path == "/redirect_mult/from-1": self.send_response(302) self.send_header('location', "from-2") self.end_headers() elif self.path == "/redirect_mult/from-2": self.send_response(302) self.send_header('location', "from-3") self.end_headers() elif self.path == "/redirect_mult/from-3": self.send_response(302) self.send_header('location', "from-4") self.end_headers() elif self.path == "/redirect_mult/from-4": self.send_response(302) self.send_header('location', "to-5") self.end_headers() elif self.path == "/redirect_mult/to-5": self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Multi-Redirect-end-5") elif self.path == '/redirect_slow/from-1': self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b'<html><head><title>Still at title?</title></head><body>Slow Redirect</body><script type="text/JavaScript">setTimeout("location.href = \'/redirect_slow/to-1\';", 1500);</script></html>') elif self.path == '/redirect_slow/to-1': self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"Slow-Redirect-end-1") ################################################################################################################################## # ################################################################################################################################## elif self.path == "/password/expect": # print("Password") # print(self.headers) self.send_response(200) self.end_headers() if not 'Authorization' in self.headers: self.wfile.write(b"Password not sent!!") return val = self.headers['Authorization'] passval = val.split(" ")[-1] passstr = base64.b64decode(passval) if passstr == b'lol:wat': self.wfile.write(b"Password Ok?") else: self.wfile.write(b"Password Bad!") elif self.path == "/content/have-title": self.send_response(200) self.end_headers() self.wfile.write(b"<html><head><title>I can haz title?</title></head><body>This page has a title!</body></html>") elif self.path == "/content/no-title": self.send_response(200) self.end_headers() self.wfile.write(b"<html><head></head><body>This page has no title. Sadface.jpg</body></html>") elif self.path == "/binary_ctnt": self.send_response(200) self.send_header('Content-type', "image/jpeg") self.end_headers() self.wfile.write(b"Binary!\x00\x01\x02\x03") elif self.path == "/binary_ctnt": self.send_response(200) self.send_header('Content-type', "image/jpeg") self.end_headers() self.wfile.write(b"Binary!\x00\x01\x02\x03") ################################################################################################################################## # Cookie stuff ################################################################################################################################## elif self.path == '/cookie_test': cook = cookies.SimpleCookie() cook['cookie_test_key'] = cookie_key cook['cookie_test_key']['path'] = "/" cook['cookie_test_key']['domain'] = "" expiration = datetime.datetime.now() + datetime.timedelta(days=30) cook['cookie_test_key']["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST") self.send_response(200) self.send_header('Content-type', "text/html") self.send_header('Set-Cookie', cook['cookie_test_key'].OutputString()) self.end_headers() self.wfile.write(b"<html><body>CF Cookie Test</body></html>") elif self.path == '/cookie_require': if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'cookie_test_key' and cook_value == cookie_key: self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><body>Cookie forwarded properly!</body></html>") return self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><body>Cookie is missing</body></html>") ################################################################################################################################## # Sucuri validation ################################################################################################################################## elif self.path == '/sucuri_shit_3': # I'd like to get this down to just 2 requests (cookie bounce, and fetch). # Doing that requires pulling html content out of chromium, though. # Annoying. sucuri_reqs_3 += 1 if sucuri_reqs_3 > 3: raise RuntimeError("Too many requests to sucuri_shit_3 (%s)!" % sucuri_reqs_3) if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'sucuri_cloudproxy_uuid_6293e0004' and cook_value == '04cbb56494ebedbcd19a61b2d728c478': # if cook[''] self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><head><title>At target preemptive Sucuri page!</title></head><body>Preemptive waf circumvented OK (p3)?</body></html>") return container_dir = os.path.dirname(__file__) fpath = os.path.join(container_dir, "waf_garbage", 'sucuri_garbage.html') with open(fpath, "rb") as fp: plain_contents = fp.read() self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(plain_contents) elif self.path == '/sucuri_shit_2': # This particular path is the one we should already have a cookie for. # As such, we expect one request only sucuri_reqs_2 += 1 if sucuri_reqs_2 > 1: raise RuntimeError("Too many requests to sucuri_shit_2 (%s)!" % sucuri_reqs_2) if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'sucuri_cloudproxy_uuid_6293e0004' and cook_value == '04cbb56494ebedbcd19a61b2d728c478': # if cook[''] self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><head><title>At target preemptive Sucuri page!</title></head><body>Preemptive waf circumvented OK (p2)?</body></html>") return container_dir = os.path.dirname(__file__) fpath = os.path.join(container_dir, "waf_garbage", 'sucuri_garbage.html') with open(fpath, "rb") as fp: plain_contents = fp.read() self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(plain_contents) elif self.path == '/sucuri_shit': sucuri_reqs_1 += 1 if sucuri_reqs_1 > 4: raise RuntimeError("Too many requests to sucuri_shit (%s)!" % sucuri_reqs_1) # print("Fetch for ", self.path) # print("Cookies:", self.headers.get_all('Cookie', failobj=[])) if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'sucuri_cloudproxy_uuid_6293e0004' and cook_value == '04cbb56494ebedbcd19a61b2d728c478': # if cook[''] self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><head><title>At target Sucuri page!</title></head><body>Sucuri Redirected OK?</body></html>") return container_dir = os.path.dirname(__file__) fpath = os.path.join(container_dir, "waf_garbage", 'sucuri_garbage.html') with open(fpath, "rb") as fp: plain_contents = fp.read() self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(plain_contents) ################################################################################################################################## # Cloudflare validation ################################################################################################################################## elif self.path == '/cloudflare_under_attack_shit_2': if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'cloudflare_validate_key' and cook_value == cookie_key: # if cook[''] self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><head><title>At target CF page!</title></head><body>CF Redirected OK?</body></html>") return container_dir = os.path.dirname(__file__) fpath = os.path.join(container_dir, "waf_garbage", 'cloudflare_bullshit.html') with open(fpath, "rb") as fp: plain_contents = fp.read() self.send_response(503) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(plain_contents) elif self.path == '/cloudflare_under_attack_shit': if self.headers.get_all('Cookie', failobj=[]): cook = self.headers.get_all('Cookie', failobj=[])[0] cook_key, cook_value = cook.split("=", 1) if cook_key == 'cloudflare_validate_key' and cook_value == cookie_key: # if cook[''] self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b"<html><head><title>At target CF page!</title></head><body>CF Redirected OK?</body></html>") return container_dir = os.path.dirname(__file__) fpath = os.path.join(container_dir, "waf_garbage", 'cloudflare_bullshit.html') with open(fpath, "rb") as fp: plain_contents = fp.read() self.send_response(503) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(plain_contents) elif (self.path == '/cdn-cgi/l/chk_jschl?jschl_vc=b10392d4929902df66c5d69ff703fde7&pass=1516685611.828-z5pqL%2FrL34&jschl_answer=3161' or self.path == '/cdn-cgi/l/chk_jschl?jschl_vc=b10392d4929902df66c5d69ff703fde7&pass=1516685611.828-z5pqL%2FrL34&jschl_answer=3160'): cook = cookies.SimpleCookie() cook['cloudflare_validate_key'] = cookie_key cook['cloudflare_validate_key']['path'] = "/" cook['cloudflare_validate_key']['domain'] = "" expiration = datetime.datetime.now() + datetime.timedelta(days=30) cook['cloudflare_validate_key']["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST") self.send_response(200) self.send_header('Content-type', "text/html") self.send_header('Set-Cookie', cook['cloudflare_validate_key'].OutputString()) self.end_headers() body = "<html><body>Setting cookies.<script>window.location.href='/cloudflare_under_attack_shit'</script></body></html>" self.wfile.write(body.encode("utf-8")) ################################################################################################################################## # Handle requests for an unknown path ################################################################################################################################## else: test_context.assertEqual(self.path, "This shouldn't happen!")
def application(environ, start_response): if environ["PATH_INFO"] == "/": # http-statuscode response_status = "200 OK" # Inhalt der Antwort response_body_text = "hello" response_body = response_body_text.encode("utf-8") # HTTP-Header response_headers = get_response_headers_for_plain_text(response_body) start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"] == "/time": response_status = "200 OK" response_body_text = str(datetime.datetime.now()) response_body = response_body_text.encode("utf-8") response_headers = get_response_headers_for_plain_text(response_body) start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"] == "/now": response_status = "308 Parmanent Redirect" response_headers = [("Location", "/time"), ("Content-Length", "0")] response_body = b"" start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"] == "/weather-form": response_status = "200 OK" response_body_text = """ <html> <body> <form method="post" action="/weather-form/submit"> <input name="city"> <button>get weather</button> </form> </body> </html> """ response_body = response_body_text.encode("utf-8") response_headers = get_response_headers_for_html_text(response_body) start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"] == "/weather-form/submit": response_status = "200 OK" # city-Parameter "holen" request_body_size = int(environ.get("CONTENT_LENGTH", 0)) request_body = environ["wsgi.input"].read(request_body_size).decode( "utf-8") parameters = parse_qs(request_body) city = parameters.get("city")[0] weather = get_weather(city) response_body_text = weather response_body = response_body_text.encode("utf-8") response_headers = [ ("Content-Lenght", str(len(response_body))), ("Content-Type", "text/plain; charset=utf-8"), ] start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"].startswith("/weather"): location = "Nuremberg" if len(environ["PATH_INFO"]) > len("/weather"): location = environ["PATH_INFO"][9:] response_status = "200 OK" weather_description = get_weather(location) response_body = weather_description.encode("utf-8") response_headers = get_response_headers_for_plain_text(response_body) start_response(response_status, response_headers) return [response_body] elif environ["PATH_INFO"].startswith("/cookies-demo"): response_status = "200 OK" # sind überhaupt cookies gesetzt? if "HTTP_COOKIE" in environ: # frage den cookie-string ab current_cookies_str = environ["HTTP_COOKIE"] # cookies über ein SimpleCookie-Objekt parsen current_cookies = cookies.SimpleCookie() current_cookies.load(current_cookies_str) # ist das visitcount-cookie gesetzt? if "visitcount" in current_cookies: # erhöhe den wert von visitcount um 1 print(current_cookies["visitcount"].value) visitcount = int(current_cookies["visitcount"].value) visitcount += 1 if visitcount >= 5: response_body = b"please register" response_headers = get_response_headers_for_plain_text( response_body) start_response(response_status, response_headers) return [response_body] else: # das visitcount-cookie ist noch nicht gesetzt # -> erster besuch visitcount = 1 else: # es sind noch keine cookies gesetzt # -> erster besuch visitcount = 1 # response_body = b"cookie-seite" # response_body = "cookie-seite".encode("utf-8") response_body = b"cookies" response_headers = get_response_headers_for_plain_text(response_body) response_headers.append( ("Set-Cookie", f"visitcount={visitcount}; Max-Age=300")) start_response(response_status, response_headers) return [response_body] else: response_status = "404 Not Found" response_body_text = "Could not find page" response_body = response_body_text.encode("utf-8") # HTTP-Header response_headers = get_response_headers_for_plain_text(response_body) start_response(response_status, response_headers) return [response_body]
def printBody(ptitle, control, db): #control for direct accessing if "HTTP_COOKIE" in os.environ: cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) #control for direct accessing if "session" in cookie.keys(): #connection into the db conn = sqlite3.connect("{}".format(db)) c = conn.cursor() #find the user according to sessionid c.execute("SELECT * FROM USER WHERE sessionid = ?", (cookie["session"].value, )) row = c.fetchone() #if the user if row != None: print("<div><p>{}<p>".format(row[0])) print("<h1>{}</h1><form action='{}' method='POST'>".format( ptitle, control)) print( "Title <input type='text' name='title' required/><br/><br/>" ) print( "Description <input type='text' name='description' required/><br/><br/>" ) #take the categor informations c.execute("SELECT * FROM CATEGORY") categories = c.fetchall() #print all categories as option print("Category <select name='categories' id='category'>") if categories != None: for i in range(0, len(categories)): print("<option value='{}'>{}</option>".format( categories[i][1], categories[i][1])) print("</select>") print("<input type='submit' value='Submit'><br/>") print("<input type='reset' value='Clear'/>") print("</form>") print( "<button type='back' onclick='goOperationPage()'> Back </button>" ) print("</div>") else: print("<h2>Login required!!</h2>") print( "<br/><br/><button class='back' onClick='goLogin()' type='button'> Login </button>" ) conn.commit() conn.close() else: print("<h2>Login required!!</h2>") print( "<br/><br/><button class='back' onClick='goLogin()' type='button'> Login </button>" ) else: print("<h2>Login required!!</h2>") print( "<br/><br/><button class='back' onClick='goLogin()' type='button'> Login </button>" )
if "username" in auth_keys and "password" in auth_keys: if auth["username"] == secret.username and auth[ "password"] == secret.password: # send cookies if and only if username and password are valid print( f"Set-Cookie: auth=username={auth['username']}&password={auth['password']}" ) print("Content-Type: text/html\r\n") print(templates.secret_page(auth["username"], auth["password"])) else: print("Content-Type: text/html\r\n") print(templates.after_login_incorrect()) else: # get cookies first cookies = ck.SimpleCookie(os.environ.get("HTTP_COOKIE")) if cookies: cookies_keys = cookies.keys() if "username" in cookies_keys and "password" in cookies_keys: # this means cookies exists, also must mean the username and password are valid print("Content-Type: text/html\r\n") print( templates.secret_page(cookies["username"].value, cookies["password"].value)) else: # get username and password from POST request then posted_bytes = os.environ.get("CONTENT_LENGTH", 0) if posted_bytes: posted = sys.stdin.read(int(posted_bytes)) for line in posted.splitlines(): for each in line.split("&"):
def test_secure_httponly_true_if_present(self): # Issue 16611 C = cookies.SimpleCookie() C.load('eggs=scrambled; httponly; secure; Path=/bacon') self.assertTrue(C['eggs']['httponly']) self.assertTrue(C['eggs']['secure'])
def cookies(self): """Cookies in dict""" c = Cookie.SimpleCookie(self.getheader('set-cookie')) sc = [(i.key, i.value) for i in c.values()] return dict(sc)
def process_response(self): """ Parses an HTTP response after an HTTP request is sent """ split_response = self.response.split(self.CRLF) response_line = util.ensure_str(split_response[0]) response_headers = {} response_data = None data_line = None for line_num in range(1, len(split_response[1:])): # CRLF represents the start of data if not split_response[line_num]: data_line = line_num + 1 break else: # Headers are all split by ':' header = split_response[line_num].split(b':', 1) if len(header) != 2: raise errors.TestError( 'Did not receive a response with valid headers', { 'header_rcvd': str(header), 'function': 'http.HttpResponse.process_response' }) header = util.ensure_str(header[0]), util.ensure_str(header[1]) response_headers[header[0].lower()] = header[1].lstrip() if 'set-cookie' in list(response_headers.keys()): try: cookie = cookies.SimpleCookie() cookie.load(response_headers['set-cookie']) except cookies.CookieError as err: raise errors.TestError( 'Error processing the cookie content into a SimpleCookie', { 'msg': str(err), 'set_cookie': str(response_headers['set-cookie']), 'function': 'http.HttpResponse.process_response' }) # if the check_for_cookie is invalid then we don't save it if self.check_for_cookie(cookie) is False: raise errors.TestError( 'An invalid cookie was specified', { 'set_cookie': str(response_headers['set-cookie']), 'function': 'http.HttpResponse.process_response' }) else: self.cookiejar.append((cookie, self.dest_addr)) if data_line is not None and data_line < len(split_response): response_data = self.CRLF.join(split_response[data_line:]) # if the output headers say there is encoding if 'content-encoding' in list(response_headers.keys()): response_data = self.parse_content_encoding( response_headers, response_data) if len(response_line.split(' ', 2)) != 3: raise errors.TestError( 'The HTTP response line returned the wrong args', { 'response_line': str(response_line), 'function': 'http.HttpResponse.process_response' }) try: self.status = int(response_line.split(' ', 2)[1]) except ValueError: raise errors.TestError( 'The status num of the response line isn\'t convertable', { 'msg': 'This may be an HTTP 1.0 \'Simple Req\\Res\', it \ doesn\'t have HTTP headers and FTW will not parse these', 'response_line': str(response_line), 'function': 'http.HttpResponse.process_response' }) self.status_msg = response_line.split(' ', 2)[2] self.version = response_line.split(' ', 2)[0] self.response_line = response_line self.headers = response_headers self.data = response_data
def cookiestring(self, value): """"Cookie string setter""" c = Cookie.SimpleCookie(value) sc = [(i.key, i.value) for i in c.values()] self.cookies = dict(sc)
weapons = json.load(open("../data/armor.json", "r")) weapons.append({ "id": form["id"].value, "cost": form["cost"].value, "acmod": str(form["hands"].value), "weight": int(form["weight"].value) }) json.dump(weapons, open("../data/armor.json", "r+")) print(open("itemAddSuccess.html", "r").read()) if "HTTP_COOKIE" not in os.environ: os.environ["HTTP_COOKIE"] = "" if "login" in os.environ["HTTP_COOKIE"]: cookie = cookies.SimpleCookie(os.environ["HTTP_COOKIE"]) uname = cookie["username"].value psswd = cookie["password"].value cnn = connectUsers() cnnc = cnn.cursor() cnnc.execute("SELECT * FROM Users WHERE username = ?", (uname, )) result = cnnc.fetchall() cnn.close() try: item = result[0] if item[2] == psswd: print("Content-Type:text/html") print("") success(item) else: assert False
#!C:\Users\nikol\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe import cgi import _html import db import os from datetime import datetime from http import cookies http_cookies_str = os.environ.get('HTTP_COOKIE', '') get_all_cookies_object = cookies.SimpleCookie(http_cookies_str) params = cgi.FieldStorage() request_type = os.environ.get('REQUEST_METHOD', '') img = params.getvalue("image") img_id = params.getvalue("id_img") image = db.get_image_by_path(img) image_id = img_id cookies_object = cookies.SimpleCookie() cookies_object["image_id"] = image_id cookies_object["last_visited"] = datetime.now() cookies_object["image_id"]['expires'] = 12 * 30 * 24 * 60 * 60 db.visit_image(image[0]) print(cookies_object.output()) last_time = get_all_cookies_object.get("last_visited") if (request_type == "POST"): img_id = params.getvalue("id_img") success = db.delete_image(img_id) if success:
def destroy_session_id(): cookies_object = cookies.SimpleCookie() cookies_object["session_id"] = "" cookies_object["session_id"]["expires"] = 'Thu, 01 Jan 1970 00:00:00 GMT' print(cookies_object.output()) #upisivanje cookie-a u header
def build_cookie_with_str(cookie_str): simple_cookie = cookies.SimpleCookie(cookie_str) # Parse Cookie from str cookie = {key: morsel.value for key, morsel in simple_cookie.items()} return cookie
def test_basic(self): cases = [ { 'data': 'chips=ahoy; vienna=finger', 'dict': { 'chips': 'ahoy', 'vienna': 'finger' }, 'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>", 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger' }, { 'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"', 'dict': { 'keebler': 'E=mc2; L="Loves"; fudge=\012;' }, 'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''', 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"' }, # Check illegal cookies that have an '=' char in an unquoted value { 'data': 'keebler=E=mc2', 'dict': { 'keebler': 'E=mc2' }, 'repr': "<SimpleCookie: keebler='E=mc2'>", 'output': 'Set-Cookie: keebler=E=mc2' }, # Cookies with ':' character in their name. Though not mentioned in # RFC, servers / browsers allow it. { 'data': 'key:term=value:term', 'dict': { 'key:term': 'value:term' }, 'repr': "<SimpleCookie: key:term='value:term'>", 'output': 'Set-Cookie: key:term=value:term' }, # issue22931 - Adding '[' and ']' as valid characters in cookie # values as defined in RFC 6265 { 'data': 'a=b; c=[; d=r; f=h', 'dict': { 'a': 'b', 'c': '[', 'd': 'r', 'f': 'h' }, 'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>", 'output': '\n'.join(('Set-Cookie: a=b', 'Set-Cookie: c=[', 'Set-Cookie: d=r', 'Set-Cookie: f=h')) } ] for case in cases: C = cookies.SimpleCookie() C.load(case['data']) self.assertEqual(repr(C), case['repr']) self.assertEqual(C.output(sep='\n'), case['output']) for k, v in sorted(case['dict'].items()): self.assertEqual(C[k].value, v)
def http_handler(self, conn, request, response): host = request.headers.get('host', conn.serverip) url = host + request.uri pretty_url = url # separate URL-encoded data from the location if '?' in request.uri: uri_location, uri_data = request.uri.split('?', 1) pretty_url = host + uri_location else: uri_location, uri_data = request.uri, "" # Check if the URL matches a user-defined filter if self.urlfilter and not self.urlfilter.search(pretty_url): return if self.maxurilen > 0 and len(uri_location) > self.maxurilen: uri_location = "{}[truncated]".format( uri_location[:self.maxurilen]) pretty_url = host + uri_location # Set the first line of the alert to show some basic metadata if response == None: msg = ["{} (NO RESPONSE) {}".format(request.method, pretty_url)] else: msg = [ "{} ({}) {} ({})".format( request.method, response.status, pretty_url, response.headers.get("content-type", "[no content-type]")) ] # Determine if there is any POST data from the client and parse if request and request.method == "POST": try: post_params = parse_qs(request.body.decode("utf-8"), keep_blank_values=True) # If parse_qs only returns a single element with a null # value, it's probably an eroneous evaluation. Most likely # base64 encoded payload ending in an '=' character. if len(post_params) == 1 and list( post_params.values()) == [["\x00"]]: post_params = request.body except UnicodeDecodeError: post_params = request.body else: post_params = {} # Get some additional useful data url_params = parse_qs(uri_data, keep_blank_values=True) referer = request.headers.get("referer", None) client_cookie = cookies.SimpleCookie(request.headers.get("cookie", "")) server_cookie = cookies.SimpleCookie(response.headers.get( "cookie", "")) # Piece together the alert message if referer: msg.append("Referer: {}".format(referer)) if client_cookie: msg.append("Client Transmitted Cookies:") for k, v in client_cookie.items(): msg.append("\t{} -> {}".format(k, v.value)) if server_cookie: msg.append("Server Set Cookies:") for k, v in server_cookie.items(): msg.append("\t{} -> {}".format(k, v.value)) if url_params: msg.append("URL Parameters:") for k, v in url_params.items(): msg.append("\t{} -> {}".format(k, v)) if post_params: if isinstance(post_params, dict): msg.append("POST Parameters:") for k, v in post_params.items(): msg.append("\t{} -> {}".format(k, v)) else: msg.append("POST Data:") msg.append(dshell.util.printable_text(str(post_params))) elif request.body: msg.append("POST Body:") request_body = dshell.util.printable_text(request_body) if self.maxpost > 0 and len(request.body) > self.maxpost: msg.append("{}[truncated]".format(request_body[:self.maxpost])) else: msg.append(request_body) if self.showcontent or self.showhtml: if self.showhtml and 'html' not in response.headers.get( 'content-type', ''): return if 'gzip' in response.headers.get('content-encoding', ''): # TODO gunzipping content = '(gzip encoded)\n{}'.format(response.body) else: content = response.body content = dshell.util.printable_text(content) if self.maxcontent and len(content) > self.maxcontent: content = "{}[truncated]".format(content[:self.maxcontent]) msg.append("Body Content:") msg.append(content) # Display the start and end times based on Blob instead of Connection kwargs = conn.info() if request: kwargs['starttime'] = request.blob.starttime kwargs['clientbytes'] = len(request.blob.data) else: kwargs['starttime'] = None kwargs['clientbytes'] = 0 if response: kwargs['endtime'] = response.blob.endtime kwargs['serverbytes'] = len(response.blob.data) else: kwargs['endtime'] = None kwargs['serverbytes'] = 0 self.write('\n'.join(msg), **kwargs) return conn, request, response