def cookieFromFile(cookiefile): jar = FileCookieJar('cookiefile') jar.load(ignore_expires=True) #set expiration time to avoid errors for cookie in jar: cookie.expires = time.time() + 14 * 24 * 3600 assert (len(jar) > 0) return jar
def cookieFromFile(cookiefile): """ reads authentication cookie from file @params: cookiefile - File containing the cookies. """ jar = FileCookieJar('cookiefile') jar.load(ignore_expires=True) # set expiration time to avoid errors for cookie in jar: cookie.expires = time.time() + 14 * 24 * 3600 assert(len(jar) > 0) return jar
def web_bruter(self): while not self.password_q.empty() and not self.found: brute = self.password_q.get().rstrip() jar = FileCookieJar("cookies") opener = build_opener(HTTPCookieProcessor(jar)) response = opener.open(target_url) page = response.read() print("Trying: %s : %s (%d left)" % (self.username, brute, self.password_q.qsize())) # read hidden fields <input type="hidden"> parser = BruteParser() parser.feed(page) post_tags = parser.tag_results # add username and password fields post_tags[username_field] = self.username post_tags[password_field] = brute login_data = urlencode(post_tags) login_response = opener.open(target_post, login_data) login_result = login_response.read() if success_check in login_result: self.found = True print("[*] Bruteforce successful!!!") print("[*] Username: %s" % username) print("[*] Password: %s" % brute) print("[*] Waiting for other threads to exit...")
def login(self, acct): cj = FileCookieJar() opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(cj)) post = {'mail': acct['mail'], 'pass': acct['pass']} data = urllib.parse.urlencode(post).encode('utf-8') res = opener.open(Radiko.LOGIN_URL, data) return opener, cj
def __init__(self, ca_certs=None, verify_ssl=True, keyjar=None, client_cert=None): """ A base class for OAuth2 clients and servers :param ca_certs: the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param verify_ssl: If True then the server SSL certificate is not verfied :param keyjar: A place to keep keys for signing/encrypting messages :param client_cert: local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both file's path """ self.keyjar = keyjar or KeyJar(verify_ssl=verify_ssl) self.request_args = {"allow_redirects": False} self.cookiejar = FileCookieJar() self.ca_certs = ca_certs if ca_certs: if verify_ssl is False: raise ValueError( 'conflict: ca_certs defined, but verify_ssl is False') # Instruct requests to verify certificate against the CA cert # bundle located at the path given by `ca_certs`. self.request_args["verify"] = ca_certs elif verify_ssl: # Instruct requests to verify server certificates against the # default CA bundle provided by 'certifi'. See # http://docs.python-requests.org/en/master/user/advanced/#ca # -certificates self.request_args["verify"] = True else: # Instruct requests to not perform server cert verification. self.request_args["verify"] = False self.events = None self.req_callback = None if client_cert: self.request_args['cert'] = client_cert
def __init__(self, httpc_params=None): """ A base class for OAuth2 clients and servers :param httpc_params: Default arguments to be used for HTTP requests """ self.request_args = {"allow_redirects": False} if httpc_params: self.request_args.update(httpc_params) self.cookiejar = FileCookieJar() self.events = None self.req_callback = None
def test_set_cookie(): cookiejar = FileCookieJar() _cookie = {"value_0": "v_0", "value_1": "v_1", "value_2": "v_2"} c = SimpleCookie(_cookie) domain_0 = ".test_domain" domain_1 = "test_domain" max_age = "09 Feb 1994 22:23:32 GMT" expires = http2time(max_age) path = "test/path" c["value_0"]["max-age"] = max_age c["value_0"]["domain"] = domain_0 c["value_0"]["path"] = path c["value_1"]["domain"] = domain_1 util.set_cookie(cookiejar, c) cookies = cookiejar._cookies c_0 = cookies[domain_0][path]["value_0"] c_1 = cookies[domain_1][""]["value_1"] c_2 = cookies[""][""]["value_2"] assert not (c_2.domain_specified and c_2.path_specified) assert c_1.domain_specified and not c_1.domain_initial_dot and not \ c_1.path_specified assert c_0.domain_specified and c_0.domain_initial_dot and \ c_0.path_specified assert c_0.expires == expires assert c_0.domain == domain_0 assert c_0.name == "value_0" assert c_0.path == path assert c_0.value == "v_0" assert not c_1.expires assert c_1.domain == domain_1 assert c_1.name == "value_1" assert c_1.path == "" assert c_1.value == "v_1" assert not c_2.expires assert c_2.domain == "" assert c_2.name == "value_2" assert c_2.path == "" assert c_2.value == "v_2"
def web_bruter(self): """ Attempts password attempts until a password is successful or password list is exhausted. :return: None """ while not self.password_q.empty() and not self.found: # Get next password to try brute = self.password_q.get().strip() # Setup cookie jar to store the cookies in the cookie file. jar = FileCookieJar("cookies") opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(jar)) # Make target request to retrieve the login form elements. response = opener.open(target_url) page = response.read().decode('utf-8') print("Trying: {} : {} ({} left)".format(self.username, brute, self.password_q.qsize())) # Parse out the hidden fields parser = BruteParser() parser.feed(page) post_tags = parser.tag_results # Replace the username and password fields with our content. post_tags[username_field] = self.username post_tags[password_field] = brute # URL encode the POST variables and pass them in our subsequent HTTP request. login_data = urllib.parse.urlencode(post_tags) login_response = opener.open(target_post, login_data.encode('utf-8')) # Retrieve the results of the authentication attempt. login_result = login_response.read().decode('utf-8') # Test if the authentication attempt was successful or not. if success_check in login_result: self.found = True print("[*] Bruteforce successful.") print("[*] Username: {}".format(username)) print("[*] Password: {}".format(brute)) print("[*] Waiting for other threads to exit...")
class HTTPLib(object): def __init__(self, ca_certs=None, verify_ssl=True, keyjar=None, client_cert=None): """ A base class for OAuth2 clients and servers :param ca_certs: the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param verify_ssl: If True then the server SSL certificate is not verfied :param keyjar: A place to keep keys for signing/encrypting messages :param client_cert: local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both file's path """ self.keyjar = keyjar or KeyJar(verify_ssl=verify_ssl) self.request_args = {"allow_redirects": False} self.cookiejar = FileCookieJar() self.ca_certs = ca_certs if ca_certs: if verify_ssl is False: raise ValueError( 'conflict: ca_certs defined, but verify_ssl is False') # Instruct requests to verify certificate against the CA cert # bundle located at the path given by `ca_certs`. self.request_args["verify"] = ca_certs elif verify_ssl: # Instruct requests to verify server certificates against the # default CA bundle provided by 'certifi'. See # http://docs.python-requests.org/en/master/user/advanced/#ca # -certificates self.request_args["verify"] = True else: # Instruct requests to not perform server cert verification. self.request_args["verify"] = False self.events = None self.req_callback = None if client_cert: self.request_args['cert'] = client_cert def _cookies(self): """ Return a dictionary of all the cookies I have keyed on cookie name :return: Dictionary """ cookie_dict = {} for _, a in list(self.cookiejar._cookies.items()): for _, b in list(a.items()): for cookie in list(b.values()): cookie_dict[cookie.name] = cookie.value return cookie_dict def __call__(self, url, method="GET", **kwargs): """ Send a HTTP request to a URL using a specified method :param url: The URL to access :param method: The method to use (GET, POST, ..) :param kwargs: extra HTTP request parameters :return: A Response """ # copy the default set before starting to modify it. _kwargs = copy.copy(self.request_args) if kwargs: _kwargs.update(kwargs) # If I have cookies add them all to the request if self.cookiejar: _kwargs["cookies"] = self._cookies() logger.debug("SENT {} COOKIES".format(len(_kwargs["cookies"]))) # If I want to modify the request arguments based on URL, method # and current arguments I can use this call back function. if self.req_callback is not None: _kwargs = self.req_callback(method, url, **_kwargs) try: # Do the request r = requests.request(method, url, **_kwargs) except Exception as err: logger.error( "http_request failed: %s, url: %s, htargs: %s, method: %s" % ( err, url, sanitize(_kwargs), method)) raise if self.events is not None: self.events.store('HTTP response', r, ref=url) try: _cookie = r.headers["set-cookie"] logger.debug("RECEIVED COOKIE") try: # add received cookies to the cookie jar set_cookie(self.cookiejar, SimpleCookie(_cookie)) except CookieError as err: logger.error(err) raise NonFatalException(r, "{}".format(err)) except (AttributeError, KeyError) as err: pass # return the response return r def send(self, url, method="GET", **kwargs): """ Another name for the send method :param url: URL :param method: HTTP method :param kwargs: HTTP request argument :return: Request response """ return self(url, method, **kwargs) def load_cookies_from_file(self, filename, ignore_discard=False, ignore_expires=False): self.cookiejar.load(filename, ignore_discard, ignore_expires) def save_cookies_to_file(self, filename, ignore_discard=False, ignore_expires=False): self.cookiejar.save(filename, ignore_discard, ignore_expires)
def __init__(self, filename=None, delayload=False, policy=None): MSIEBase.__init__(self) FileCookieJar.__init__(self, filename, delayload, policy)