python+selenium+Unittest: get website cookie/manipulate cookie/send back. Possible?



  • Details: For our test procedures, we want to read the cookies of a website, manipulate the cookie and read it again.

    We want to test if this is possible at all to avoid a security gap.

    We use for our test procedures:

    Selenium - latest version Python - Latest version And several other Python packages.

    Question: Can I use Selenium to read the cookies, write them back after manipulation?



  • Even though you can do it using seleniums built-in cookie manager I wouldn't recommend doing so if you're looking for security gaps. The WebDriver acts with much higher privileges than an actual attack scenario would (just look at seleniums switch_to which basically circumvents the same-origin policy, something a real attacker would have a really hard time to do) and as far as I recall it will also not respect httpOnly cookie settings.

    Using the javascript_executor and passing it JS to change the cookie value will probably yield more reliable results for your case.

    def change_cookie(cookie_name, new_value):
        script = """
        function manipulate_cookie(cookie_name, new_value){
            var key_value_pairs = document.cookie.split(";")
            var cookies = {}
            for(kv_pair of key_value_pairs){
                cookies[kv_pair.split("=")[0]] = kv_pair.split("=")[1]
            }
            if(cookies[cookie_name])
                cookies[cookie_name] = new_value
    
            var new_cookies = []
            for(cookie in cookies){
                new_cookies.push(`${cookie}=${cookies[cookie]}`)
            }
            return  new_cookies.join(";")
        }document.cookie = manipulate_cookie(arguments[0], arguments[1])
        """
        driver.execute_script(script, cookie_name, new_value)
    

    will change the cookie value using only browser accesible methods and a simple

    def get_cookie(cookie_name):
    script = """
        function get_cookie(cookie_name){
        var key_value_pairs = document.cookie.split(";")
        var cookies = {}
       for(kv_pair of key_value_pairs){
            cookies[kv_pair.split("=")[0].trim()] = kv_pair.split("=")[1]
        }
        return cookies[cookie_name]
    }return get_cookie(arguments[0])
    """
    return driver.execute_script(script, cookie_name) #Will return a string with the cookie value
    

    will retrieve the data using the same constraints a not webdriver driven browser will have to respect.

    The built-in methods for cookie manipulation are valuable if you need them to establish or pass sessions but they're not meant to test for actual browser behaviour because they are meant to allow for things you couldn't do natively.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2