def run(self): policy = DefaultCookiePolicy() req = Request('https://example.com/anybad') if policy.path_return_ok('/any', req): self.exit_vulnerable() else: self.exit_fixed()
def run(self): policy = DefaultCookiePolicy() req = Request('https://xxxfoo.co.jp/') if policy.domain_return_ok('foo.co.jp', req): self.exit_vulnerable() else: self.exit_fixed()
def cookiejar(self, policy): def_policy = DefaultCookiePolicy(**policy) self.cookieJar = CookieJar(def_policy) handler = HTTPCookieProcessor(self.cookieJar) return handler
def setUp(self): """Launch app using webtest with test settings""" self.appconf = get_app(test_ini) self.app = TestApp(self.appconf) #All auth via BasicAuth - never return the session cookie. self.app.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[])) # This sets global var "engine" - in the case of SQLite this is a fresh RAM # DB each time. If we only did this on class instantiation the database would # be dirty and one test could influence another. # TODO - add a test that tests this. server.choose_engine("SQLite") # Punch in new user account with direct server call # This will implicitly generate the tables. user_id = self.create_user("testuser") #Here is what the user should look like when inspected self.user_json = { "name" : "testuser testuser", "handle" : "*****@*****.**", "id" : 1, "credits" : 0, "username": "******"} #print("user_id is %s" % str(user_id)) #print("user_from_db_is %s" % server.get_user_id_from_name("testuser")) server.touch_to_add_password(user_id, "asdf") # And log in as this user for all tests (via BasicAuth) # FIXME - switch to token auth to speed up the tests. self.app.authorization = ('Basic', ('testuser', 'asdf'))
def set_ok(self, cookie, request): if not DefaultCookiePolicy.set_ok(self, cookie, request): return False try: new_cookie_length = (self.cookie_length(cookie.domain) + len(cookie.path) + len(cookie.name) + len(cookie.value or '')) except TypeError: # cookiejar is not infallible #220 _logger.debug('Cookie handling error', exc_info=1) return False if new_cookie_length >= 4100: return False if self.count_cookies(cookie.domain) >= 50: cookies = self.cookie_jar._cookies try: cookies[cookie.domain][cookie.path][cookie.name] except KeyError: return False if not wpull.util.is_ascii(str(cookie)): return False return True
def cookiejar(self, policy): def_policy = DefaultCookiePolicy(**policy) self.mozillaCookieJar = MozillaCookieJar(self.filename, def_policy) if exists(self.filename): self.mozillaCookieJar.load(self.filename) handler = HTTPCookieProcessor(self.mozillaCookieJar) return handler
def setUp(self): """Launch pserve/waitress using webtest with test settings. Fresh for every test, though it shouldn't matter. """ self.myapp = get_app(test_ini) self.testapp = TestApp(self.myapp) #No auth, no cookies self.testapp.authorization = None self.testapp.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[]))
def __init__(self, base_url): self._base_url = base_url self.headers = {} self.__response = None policy = DefaultCookiePolicy( rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict) self._opener = build_opener(HTTPCookieProcessor(CookieJar(policy))) self._response = None
def create_cookie_jar(policy_type=None): cookie, policy = (CookieJar(), DefaultCookiePolicy()) if policy_type == "reject_all": policy.set_ok = lambda cookie, request: False elif policy_type == "allow_all": policy.set_ok = lambda cookie, request: True elif policy_type == "allow_if_needed": policy.set_ok = lambda cookie, request: (cookie.domain in allowed_cookies) cookie.set_policy(policy) return cookie
def set_ok(self, cookie, request): if not DefaultCookiePolicy.set_ok(self, cookie, request): return False if len(repr(cookie)) > 4100: return False if self.count_cookies(cookie.domain) >= 50: cookies = self.cookie_jar._cookies try: cookies[cookie.domain][cookie.path][cookie.name] except KeyError: return False return True
def __init__(self, policy=None): if policy is None: policy = DefaultCookiePolicy() self._policy = policy self._policy._now = self._now = int(time.time()) self._cookies_lock = _threading.RLock() self._cookies = {} self._new_cookies=[] #由于cookies要存到数据库,所以需要记录哪些cookie是新添加的,哪些cookie是被更新了 self._renewed_cookies=[] if sys.platform == 'win32': #平台判断,不同的平台cookie存放的位置不同 self.cookie_path = os.environ['LOCALAPPDATA'] + '/Google/Chrome/User Data/Default/cookies' elif sys.platform == 'darwin': self.cookie_path = 'Users/' + os.environ['USER'] + '/Library/Application Support/Google/Chrome/Default/Cookies' else: raise BaseException('Unknown Platform')
def _get_test_app(self): # This is tested in the test below, and also convenient for other tests where # we just want a working agent log-in. app = TestApp(get_app(test_ini)) #Re-read the .ini to find out the secret. settings = get_appsettings(test_ini) #This should not be the same as what's in secret-file.txt. #Actually, I already tested this above, no matter. # self.assertNotEqual(settings['agent.secret'], 'testsharedsecret') app.authorization = ('Basic', ('agent', settings['agent.secret'])) #And we need this, or else the second call will fail with # KeyError: 'No such user'. Really we should either suppress HAP returning # a login token to agents or else allow it to validate the token successfully. app.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[])) return app
def set_ok(self, cookie, request): if not DefaultCookiePolicy.set_ok(self, cookie, request): return False cookie_string = repr(cookie) if len(cookie_string) > 4100: return False if self.count_cookies(cookie.domain) >= 50: cookies = self.cookie_jar._cookies try: cookies[cookie.domain][cookie.path][cookie.name] except KeyError: return False if not wpull.util.is_ascii(cookie_string): return False return True
def setUp(self): """Launch pserve using webtest with test settings""" self.appconf = get_app(test_ini) self.app = TestApp(self.appconf) #This seems to be how we suppress cookies being remembered. #All auth via BasicAuth - never return the session cookie. self.app.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[])) # This sets global var "engine" - in the case of SQLite this is a fresh RAM # DB each time. If we only did this on class instantiation the database would # be dirty and one test could influence another. # TODO - add a test that tests this. server.choose_engine("SQLite") # Punch in new administrator account with direct server call # This will implicitly generate the tables. user_id = server.create_user("administrators", "administrator", "administrator", "administrator") #server.touch_to_add_user_group("administrator", "administrators") server.touch_to_add_password(user_id, "adminpass") self.app.authorization = ('Basic', ('administrator', 'adminpass'))
ssl_options |= ssl.OP_NO_RENEGOTIATION # Default verify flags for SSL contexts ssl_verify_flags = (ssl.VERIFY_X509_STRICT | ssl.VERIFY_X509_TRUSTED_FIRST | ssl.VERIFY_DEFAULT) # CA bundle for server certificate validation cafile = f"{data}/ca-bundle.crt" # CA certs path for server certificate validation capath = os.path.dirname(cafile) # Load "cookies_required.json" as dict with open(f"{data}/cookies_required.json", mode="r") as cookies_required: content = cookies_required.read() allowed_cookies = json.loads(content) # Default policy for cookies: allow all allow_all_cookies = DefaultCookiePolicy() allow_all_cookies.set_ok = lambda cookie, request: True # Default policy for cookies: deny all deny_all_cookies = DefaultCookiePolicy() deny_all_cookies.set_ok = lambda cookie, request: False # Default policy for cookies: allow if needed allow_cookies_if_needed = DefaultCookiePolicy() allow_cookies_if_needed.set_ok = lambda cookie, request: (cookie.domain in allowed_cookies)
# location of the cookies file): # import os, http.cookiejar, urllib.request cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt")) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") # # The next example illustrates the use of DefaultCookiePolicy. Turn on RFC 2965 cookies, be more strict about domains when setting # and returning Netscape cookies, and block some domains from setting cookies or having them returned: # import urllib.request from http.cookiejar import CookieJar, DefaultCookiePolicy policy = DefaultCookiePolicy(rfc2965=True, strict_ns_domain=Policy.DomainStrict, blocked_domains=["ads.net", ".ads.net"]) cj = CookieJar(policy) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/")
Serializable( type_=CaseInsensitiveDict, encoder=lambda obj: cast(Dict[str, object], obj._store), decoder=lambda obj: {"_store": obj}, ), Cookie.__name__: Serializable( type_=Cookie, encoder=lambda obj: cast(Dict[str, object], obj.__dict__), decoder=lambda obj: obj, ), RequestsCookieJar.__name__: Serializable( type_=RequestsCookieJar, encoder=lambda obj: dict(obj.__getstate__(), _policy=None), decoder=lambda obj: dict(obj, _policy=DefaultCookiePolicy()), ), PreparedRequest.__name__: Serializable( type_=PreparedRequest, encoder=lambda obj: dict(obj.__dict__, hooks=None), decoder=lambda obj: dict(obj, hooks=cast( Callable[[], Mapping[str, Sequence[Any]]], default_hooks)()), ), Response.__name__: Serializable( type_=Response, encoder=lambda obj: dict(obj.__getstate__(), history=None), decoder=lambda obj: dict(obj, history=None),
if not resp.ok: print('Cannot find my IP.', file=sys.stderr) sys.exit(1) try: new_ip = IP(resp.text.strip()) except ValueError as e: print('Bad IP fetched:', repr(new_ip), file=sys.stderr) sys.exit(1) print('New IP:', new_ip) try: client = None session = Session() session.cookies.set_policy(policy=DefaultCookiePolicy(rfc2965=True)) client = Client('https://partner.r01.ru:1443/partner_api.khtml?wsdl', transport=Transport(session=session)) if not client: print('No services', file=sys.stderr) sys.exit(1) print('client=', client) login = client.service.logIn(config['user'], config['password']) if login.code != 1: print('Cannot log in:', login.message, file=sys.stderr) sys.exit(1) print('login:'******'Coockie': 'SOAPClient = ' + login.message}) doms = client.service.getDomainsAllSimple()
def set_ok(self, cookie, request): if cookie.name in self.accepted_cookies: return DefaultCookiePolicy.set_ok(self, cookie, request) else: return False
def __init__(self, accepted_cookies): self.accepted_cookies = accepted_cookies DefaultCookiePolicy.__init__(self)
def __init__(self, *args, **kwargs): self.cookie_jar = kwargs.pop("cookie_jar") DefaultCookiePolicy.__init__(self, *args, **kwargs)
def __init__(self, policy=None, check_expired_frequency=10000): self.policy = policy or DefaultCookiePolicy() self.jar = _CookieJar(self.policy) self.jar._cookies_lock = _DummyLock() self.check_expired_frequency = check_expired_frequency self.processed = 0
def __init__(self, *args, **kwargs): self.cookie_jar = kwargs.pop('cookie_jar') DefaultCookiePolicy.__init__(self, *args, **kwargs)