Project

General

Profile

Download (6.26 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / test / haketilo_test / unit / test_policy_enforcing.py @ aacacbb8

1
# SPDX-License-Identifier: CC0-1.0
2

    
3
"""
4
Haketilo unit tests - enforcing script blocking policy from content script
5
"""
6

    
7
# This file is part of Haketilo
8
#
9
# Copyright (C) 2022 Wojtek Kosior <koszko@koszko.org>
10
#
11
# This program is free software: you can redistribute it and/or modify
12
# it under the terms of the CC0 1.0 Universal License as published by
13
# the Creative Commons Corporation.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# CC0 1.0 Universal License for more details.
19

    
20
import pytest
21
import json
22
import urllib.parse
23
from selenium.webdriver.support.ui import WebDriverWait
24

    
25
from ..script_loader import load_script
26
from .utils import are_scripts_allowed
27

    
28
# For simplicity, we'll use one nonce in all test cases.
29
nonce = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
30

    
31
allow_policy = {'allow': True}
32
block_policy = {
33
    'allow': False,
34
    'csp': f"prefetch-src 'none'; script-src-attr 'none'; script-src 'none'; script-src-elem 'none'; frame-src http://* https://*;"
35
}
36
payload_policy = {
37
    'mapping': 'somemapping',
38
    'payload': {'identifier': 'someresource'},
39
    'csp': f"prefetch-src 'none'; script-src-attr 'none'; script-src 'nonce-{nonce}'; script-src-elem 'nonce-{nonce}';"
40
}
41

    
42
content_script = load_script('content/policy_enforcing.js') + ''';{
43
const smuggled_what_to_do = /^[^#]*#?(.*)$/.exec(document.URL)[1];
44
const what_to_do = smuggled_what_to_do === "" ? {policy: {allow: true}} :
45
                   JSON.parse(decodeURIComponent(smuggled_what_to_do));
46

    
47
if (what_to_do.csp_off) {
48
    const orig_DOMParser = window.DOMParser;
49
    window.DOMParser = function() {
50
        const parser = new orig_DOMParser();
51
        this.parseFromString = () => parser.parseFromString('', 'text/html');
52
    }
53
}
54

    
55
enforce_blocking(what_to_do.policy);
56
}'''
57

    
58
def get(driver, page, what_to_do):
59
    driver.get(page + '#' + urllib.parse.quote(json.dumps(what_to_do)))
60
    driver.execute_script('window.before_reload = true; location.reload();')
61
    done = lambda _: not driver.execute_script('return window.before_reload;')
62
    WebDriverWait(driver, 10).until(done)
63

    
64
@pytest.mark.ext_data({'content_script': content_script})
65
@pytest.mark.usefixtures('webextension')
66
# Under Mozilla we use several mechanisms of script blocking. Some serve as
67
# fallbacks in case others break. CSP one of those mechanisms. Here we run the
68
# test once with CSP blocking on and once without it. This allows us to verify
69
# that the CSP-less blocking approaches by themselves also work. We don't do the
70
# reverse (CSP on and other mechanisms off) because CSP rules added through
71
# <meta> injection are not reliable enough - they do not always take effect
72
# immediately and there's nothing we can do to fix it.
73
@pytest.mark.parametrize('csp_off_setting', [{}, {'csp_off': True}])
74
def test_policy_enforcing_html(driver, execute_in_page, csp_off_setting):
75
    """
76
    A test case of sanitizing <script>s and intrinsic JavaScript in HTML pages.
77
    """
78
    def click_all():
79
        for i in range(1, 3):
80
            driver.find_element_by_id(f'clickme{i}').click()
81

    
82
    def assert_properly_blocked():
83
        click_all()
84

    
85
        assert set(driver.execute_script('return window.__run || [];')) == set()
86
        assert bool(csp_off_setting) == are_scripts_allowed(driver)
87

    
88
        for attr in ('onclick', 'href', 'src', 'data'):
89
            elem = driver.find_element_by_css_selector(f'[blocked-{attr}]')
90

    
91
            assert 'blocked' in elem.get_attribute(attr)
92
            assert '__run = [...(' in elem.get_attribute(f'blocked-{attr}')
93

    
94
        but1 = driver.find_element_by_id('clickme1')
95
        assert but1.get_attribute('blocked-blocked-onclick') == \
96
            "some useful data"
97

    
98
    # First, see if scripts run when not blocked.
99
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_1.html', {
100
        'policy': allow_policy,
101
        **csp_off_setting
102
    })
103

    
104
    click_all()
105

    
106
    assert set(driver.execute_script('return window.__run || [];')) == \
107
        {'inline', 'on', 'href', 'src', 'data'}
108
    assert are_scripts_allowed(driver)
109

    
110
    # Now, verify scripts don't run when blocked.
111
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_1.html', {
112
        'policy': block_policy,
113
        **csp_off_setting
114
    })
115

    
116
    assert_properly_blocked()
117

    
118
    # Now, verify only scripts with nonce can run when payload is injected.
119
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_1.html', {
120
        'policy': payload_policy,
121
        **csp_off_setting
122
    })
123

    
124
    assert_properly_blocked()
125
    assert are_scripts_allowed(driver, nonce)
126

    
127
# Test function analogous to that for HTML page.
128
@pytest.mark.ext_data({'content_script': content_script})
129
@pytest.mark.usefixtures('webextension')
130
@pytest.mark.parametrize('csp_off_setting', [{}, {'csp_off': True}])
131
def test_policy_enforcing_xml(driver, execute_in_page, csp_off_setting):
132
    """
133
    A test case of sanitizing <script>s and intrinsic JavaScript in XML
134
    documents.
135
    """
136
    def click_all():
137
        for name in ('idaret', 'nowamak', 'mango', 'annoying'):
138
            elem = driver.find_element_by_id(f'{name}_circle')
139
            try:
140
                elem.click()
141
            except:
142
                pass
143

    
144
    def assert_properly_blocked():
145
        click_all()
146

    
147
        assert set(driver.execute_script('return window.__run || [];')) == set()
148
        assert bool(csp_off_setting) == are_scripts_allowed(driver)
149

    
150
    # First, see if scripts run when not blocked.
151
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_2.xml', {
152
        'policy': allow_policy,
153
        **csp_off_setting
154
    })
155

    
156
    click_all()
157

    
158
    assert set(driver.execute_script('return window.__run || [];')) == \
159
        {'grape', 'raspberry', 'idaret', 'melon'}
160
    assert are_scripts_allowed(driver)
161

    
162
    # Now, verify scripts don't run when blocked.
163
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_2.xml', {
164
        'policy': block_policy,
165
        **csp_off_setting
166
    })
167

    
168
    assert_properly_blocked()
169

    
170
    # Now, verify only scripts with nonce can run when payload is injected.
171
    get(driver, 'https://gotmyowndoma.in/scripts_to_block_2.xml', {
172
        'policy': payload_policy,
173
        **csp_off_setting
174
    })
175

    
176
    assert_properly_blocked()
177
    assert are_scripts_allowed(driver, nonce)
(18-18/25)