├── .github └── workflows │ └── django.yml ├── .gitignore ├── LICENSE ├── README.md ├── pyproject.toml ├── pytest.ini ├── src └── django_xss_fuzzer │ ├── __init__.py │ └── pytest_plugin.py └── tests └── integration ├── conftest.py ├── sample_app ├── manage.py ├── sample │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── templates │ ├── basic_context.html │ └── home.html └── test1 │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views │ ├── __init__.py │ └── home.py └── test_basic.py /.github/workflows/django.yml: -------------------------------------------------------------------------------- 1 | name: Django CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | strategy: 14 | max-parallel: 4 15 | matrix: 16 | python-version: ["3.7", "3.8", "3.9", "3.10"] 17 | 18 | steps: 19 | - uses: actions/checkout@v3 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v4 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | - name: Install Dependencies 25 | run: | 26 | python -m pip install --upgrade pip flit 27 | flit install --deps develop 28 | - name: Run Tests 29 | run: | 30 | python -m pytest tests/integration --driver Chrome --driver-path $CHROMEWEBDRIVER/chromedriver 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | .venv/ 3 | .idea/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django XSS Fuzzer 2 | 3 | An XSS vulnerability fuzz tester for Django views. 4 | 5 | This tester will inject XSS patterns into the context data for a template before it is rendered, including: 6 | 7 | - Simple strings 8 | - Attributes of Django ORM objects in QuerySets 9 | 10 | The goal of this tool is to quickly find any XSS vulnerabilities in Django templates. 11 | 12 | Any successful injections will write a message to the browser JavaScript console. 13 | 14 | ## Installation 15 | 16 | Install via pip 17 | 18 | ```console 19 | $ pip install django-xss-fuzzer 20 | ``` 21 | 22 | Add `ViewFuzzerMiddleware` to your middleware list for a **test environment**. 23 | 24 | ```python 25 | MIDDLEWARE = [ 26 | ... 27 | 'django_xss_fuzzer.ViewFuzzerMiddleware' 28 | ] 29 | ``` 30 | 31 | **Do not deploy this to a production server!** 32 | 33 | ## Configuration 34 | 35 | Configure the middleware via the Django global settings. 36 | 37 | * `XSS_PATTERN` : An XSS patterns to try. See [XSS Cheatsheet](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet) for inspiration. 38 | * `XSS_INJECT_KWARGS` (Default False) : A switch to disable injecting XSS view function keyword arguments 39 | * `XSS_INJECT_CONTEXT_DATA` (Default True) : A switch to disable injecting XSS into class data 40 | 41 | ## Automated fuzzing with Pytest and Selenium 42 | 43 | This package comes with a Pytest extension to add a parametrized fixture, `xss_pattern`. 44 | 45 | Once you've restarted Django, it will replace anything "string-like" in the context data with a malicious string. 46 | By default it will try ``. 47 | 48 | The values that will be replaced : 49 | - Any string variables 50 | - Any attributes in a model instance that are strings 51 | - Any attributes in a QuerySet containing data models that are strings 52 | 53 |  54 | 55 | When you browse any of the pages on your site, you should see Django successfully protecting and escaping the strings. 56 | 57 |  58 | 59 | When you open the JavaScript console, if you see any `--SUCCESS[]--` messages this means your page is vulnerable, the name of the field that it replaced will be inside square brackets. 60 | 61 | To change the malicious string, set the `XSS_PATTERN` variable in your Django settings. 62 | 63 | It's designed to be paired with PyTest, PyTest-Django, and Selenium so that it will try a range of malicious strings until it finds a successful attack vector. 64 | 65 | The selenium integration is required so that each view will be rendered and then processed by Chrome. Once Chrome has loaded the page, the tool will inspect the JavaScript log for any occurrences of `--SUCCESS[field]--` 66 | and then fail the test if one is found. 67 | 68 | Here is an example test for the URLs `/` and `/home`: 69 | 70 | ```python 71 | import pytest 72 | 73 | 74 | paths = ( 75 | '/', 76 | '/home' 77 | ) 78 | 79 | 80 | @pytest.mark.django_db() 81 | @pytest.mark.parametrize('path', paths) 82 | def test_xss_patterns(selenium, live_server, settings, xss_pattern, path): 83 | setattr(settings, 'XSS_PATTERN', xss_pattern.string) 84 | selenium.get('%s%s' % (live_server.url, path), ) 85 | assert not xss_pattern.succeeded(selenium), xss_pattern.message 86 | ``` 87 | 88 | The test function `test_xss_patterns` is a parametrized test that will run a live server using `pytest-django` and open a browser for each test using `pytest-selenium`. 89 | To test more views, just add the URIs to `paths`. 90 | 91 | To setup selenium, add the following to your `conftest.py`: 92 | 93 | ```python 94 | import pytest 95 | 96 | 97 | @pytest.fixture(scope='session') 98 | def session_capabilities(session_capabilities): 99 | session_capabilities['goog:loggingPrefs'] = {'browser': 'ALL'} 100 | return session_capabilities 101 | 102 | 103 | @pytest.fixture 104 | def chrome_options(chrome_options): 105 | chrome_options.headless = True 106 | return chrome_options 107 | ``` 108 | 109 | This will configure Chrome as headless and enable logging to capture the XSS flaws. 110 | 111 | To run PyTest with this plugin, use the `--driver` flag as Chrome and `--driver-path` to point to a downloaded version of the Chrome Driver for the version of Chrome you have installed. 112 | 113 | ```console 114 | $ python -m pytest tests/ --driver Chrome --driver-path /path/to/chromedriver -rs -vv 115 | ``` 116 | 117 | Once this is running, you'll see something similar to the following output: 118 | 119 |  120 | 121 | For each failed test, inspect that particular view with the attack string and see where the potential vulnerability is. 122 | 123 | ## What about Django's builtin XSS protection? 124 | 125 | In 99% of cases, Django will sanitize the injection strings and they will be unsuccessful. 126 | 127 | However, there are some limitations, such as unquoted expressions of HTML tag attributes 128 | 129 | ```html 130 | 131 | ``` 132 | 133 | This extension would automatically replace `var` with `x onafterscriptexecute=console.log('found attribute-based xss in {0}')`. 134 | 135 | Django would render the following HTML: 136 | 137 | ```html 138 | 139 | ``` 140 | 141 | The JavaScript code within the onafterscriptexecute would be run by the browser, demonstrating the vulnerability. 142 | 143 | Other examples, would be the use of the `|safe` filter inside the Django template. This filter can be put into Django views without a full-understanding of the ramifications. 144 | 145 | For example, in a permanent XSS attack, the database, or memory state could contain a dangerous string. 146 | 147 | ## Running in CI/CD 148 | 149 | GitHub Actions has Chrome and Chromedriver preinstalled on the `ubuntu-latest` image. 150 | 151 | You can run the tests with the same flag with the environment variable: 152 | 153 | ```yaml 154 | - name: Run Security Tests 155 | run: | 156 | python -m pytest tests/your_security_tests --driver Chrome --driver-path $CHROMEWEBDRIVER/chromedriver 157 | ``` 158 | 159 | Azure Pipelines uses the same image, but has a different syntax. You can run using a script task like this: 160 | 161 | ```yaml 162 | - script: | 163 | pytest tests/your_security_tests --driver Chrome --driver-path $(CHROMEWEBDRIVER)/chromedriver 164 | displayName: 'Run Security tests' 165 | ``` 166 | 167 | Also use my [pytest-azurepipelines](https://github.com/tonybaloney/pytest-azurepipelines) extension to automate the publishing of test results to the pipelines UI. 168 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["flit_core >=2,<4", "Django >= 2.0"] 3 | build-backend = "flit_core.buildapi" 4 | 5 | [tool.flit.metadata] 6 | module = "django_xss_fuzzer" 7 | dist-name = "django-xss-fuzzer" 8 | keywords = "django,xss,security,testing" 9 | requires-python = ">=3.5" 10 | description-file = "README.md" 11 | author = "Anthony Shaw" 12 | author-email = "anthonyshaw@apache.org" 13 | home-page = "https://github.com/tonybaloney/django-xss-fuzzer" 14 | requires = ["Django >= 2.0"] 15 | classifiers = [ 16 | "License :: OSI Approved :: Apache Software License", 17 | "Framework :: Pytest"] 18 | 19 | [tool.flit.entrypoints."pytest11"] 20 | django_xss_fuzzer = "django_xss_fuzzer.pytest_plugin" 21 | 22 | [tool.flit.metadata.requires-extra] 23 | test = [ 24 | "pytest >= 5.0.0", 25 | "pytest-django", 26 | "selenium", 27 | "pytest-selenium", 28 | "pytest-pythonpath" 29 | ] -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | python_paths = tests/integration/sample_app src/ 3 | django_find_project = true 4 | DJANGO_SETTINGS_MODULE = sample.settings 5 | -------------------------------------------------------------------------------- /src/django_xss_fuzzer/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | django-xss-fuzzer: An XSS vulnerability fuzz tester for Django views. 3 | """ 4 | import os 5 | from collections import namedtuple 6 | 7 | from django.db.models import Model, QuerySet 8 | from django.conf import settings 9 | import logging 10 | 11 | 12 | logger = logging.getLogger(__name__) 13 | __version__ = '0.3.1' 14 | ENV_VAR_NAME = 'XSS_PATTERN' 15 | X_HEADER_NAME = "X-XSS-Pattern" 16 | _XssPattern = namedtuple('XssPattern', 'string description') 17 | 18 | 19 | class XssPattern(_XssPattern): 20 | def __str__(self): 21 | return self.string 22 | 23 | @property 24 | def message(self): 25 | if hasattr(self, '_message'): 26 | return self._message 27 | else: 28 | return None 29 | 30 | def succeeded(self, selenium): 31 | logs = list(selenium.get_log('browser')) 32 | success_ = list(filter(lambda entry: "--SUCCESS" in entry['message'] and entry['level'] == 'INFO', logs)) 33 | if success_: 34 | self._message = success_[0] 35 | return len(success_) > 0 36 | 37 | 38 | DEFAULT_PATTERNS = ( 39 | XssPattern('', "Script tag with onerror event"), 40 | XssPattern('x onafterscriptexecute="console.log(\'{0}\')"', "non-quoted attribute escape"), 41 | XssPattern('x onafterscriptexecute="console.log(`{0}`)"', "non-quoted attribute escape with backticks"), 42 | XssPattern('', "template strings"), 43 | XssPattern('x onafterprint="console.log(\'{0}\')"', "non-quoted attribute escape on load"), 44 | XssPattern('x onerror="console.log(\'{0}\')"', "non-quoted attribute escape on load"), 45 | XssPattern('x onafterprint="console.log(`{0}`)"', "non-quoted attribute escape on load with backticks"), 46 | XssPattern('+ADw-script+AD4-console.log(+ACc-{0}+ACc-)+ADw-/script+AD4-', "UTF-7 charset meta"), 47 | XssPattern('data:text/javascript;base64,Y29uc29sZS5sb2coJy0tU1VDQ0VTU1tdLS0nKQ==', "JS-encoded base64, payload is '--SUCCESS[]--'") 48 | ) 49 | 50 | 51 | class ViewFuzzerMiddleware: 52 | """ 53 | Attempts various XSS attacks against the view 54 | """ 55 | def __init__(self, get_response): 56 | self.index = 0 57 | self.get_response = get_response 58 | self.inject_kwargs = getattr(settings, 'XSS_INJECT_KWARGS', False) 59 | self.inject_context_data = getattr(settings, 'XSS_INJECT_CONTEXT_DATA', True) 60 | 61 | def __call__(self, request): 62 | response = self.get_response(request) 63 | return response 64 | 65 | def process_view(self, request, view_func, view_args, view_kwargs): 66 | if request.method not in ('GET',): # Just GET for now. 67 | return None 68 | 69 | # Inject (reflection attack) 70 | if self.inject_kwargs: 71 | if not view_kwargs: 72 | return None 73 | for key, value in view_kwargs.items(): 74 | if isinstance(value, str): 75 | view_kwargs[key] = self._inject_pattern(key) 76 | 77 | def _reflect_model(self, inst, name): 78 | for key, value in inst.__dict__.items(): 79 | if isinstance(value, str): 80 | setattr(inst, key, self._inject_pattern('{0}.{1}'.format(name, key))) 81 | 82 | def process_template_response(self, request, response): 83 | if not self.inject_context_data: 84 | return response 85 | if not response.context_data: 86 | return response 87 | for key, value in response.context_data.items(): 88 | if key == 'view': # ignore this field 89 | continue 90 | if isinstance(value, str): 91 | response.context_data[key] = self._inject_pattern(key) 92 | elif isinstance(value, Model): 93 | self._reflect_model(value, key) 94 | elif isinstance(value, QuerySet): 95 | # Exhaust lazy query sets so we can hack the attributes 96 | _exhausted = list(value) 97 | for i in _exhausted: 98 | self._reflect_model(i, key) 99 | response.context_data[key] = _exhausted 100 | # TODO: inject into other types. 101 | 102 | return response 103 | 104 | def _inject_pattern(self, key): 105 | """ 106 | Inject the value as a XSS-attack string with the name of the field inside 107 | """ 108 | if ENV_VAR_NAME in os.environ: 109 | pattern = os.environ[ENV_VAR_NAME] 110 | else: 111 | pattern = getattr(settings, 'XSS_PATTERN', DEFAULT_PATTERNS[self.index].string) 112 | 113 | logger.debug('XSS fuzzer swapping {0} value with {1}'.format(key, pattern)) 114 | return pattern.format('--SUCCESS[{0}]--'.format(key)) # nosec 115 | -------------------------------------------------------------------------------- /src/django_xss_fuzzer/pytest_plugin.py: -------------------------------------------------------------------------------- 1 | from django_xss_fuzzer import DEFAULT_PATTERNS 2 | 3 | 4 | def pytest_generate_tests(metafunc): 5 | if "xss_pattern" in metafunc.fixturenames: 6 | metafunc.parametrize("xss_pattern", DEFAULT_PATTERNS) 7 | 8 | 9 | def pytest_make_parametrize_id(config, val, argname): 10 | if argname == "xss_pattern": 11 | return val.description 12 | -------------------------------------------------------------------------------- /tests/integration/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture(scope='session') 5 | def session_capabilities(session_capabilities): 6 | session_capabilities['loggingPrefs'] = {'browser': 'ALL'} 7 | session_capabilities['goog:loggingPrefs'] = {'browser': 'ALL'} 8 | 9 | return session_capabilities 10 | 11 | 12 | @pytest.fixture 13 | def chrome_options(chrome_options): 14 | chrome_options.headless = True 15 | return chrome_options 16 | -------------------------------------------------------------------------------- /tests/integration/sample_app/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /tests/integration/sample_app/sample/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/django-xss-fuzzer/b6ef5e550e80964dbcb54020c3dfd37bd0478eb7/tests/integration/sample_app/sample/__init__.py -------------------------------------------------------------------------------- /tests/integration/sample_app/sample/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for sample project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /tests/integration/sample_app/sample/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for sample project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.8. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'gg83(rmo96y!fun^dri93=jr_xz-wn2ldfrkjtj3a77#y2p6e!' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | 51 | # Test XSS fuzzer middlewares.. 52 | 'django_xss_fuzzer.ViewFuzzerMiddleware' 53 | ] 54 | 55 | ROOT_URLCONF = 'sample.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [BASE_DIR + '/templates'], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'sample.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_L10N = True 116 | 117 | USE_TZ = True 118 | 119 | 120 | # Static files (CSS, JavaScript, Images) 121 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 122 | 123 | STATIC_URL = '/static/' 124 | -------------------------------------------------------------------------------- /tests/integration/sample_app/sample/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, include 2 | 3 | urlpatterns = [ 4 | path('', include('test1.urls')), 5 | ] 6 | -------------------------------------------------------------------------------- /tests/integration/sample_app/sample/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for sample project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tests/integration/sample_app/templates/basic_context.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |