Package: django-xss-fuzzer
Django XSS FuzzerAn XSS vulnerability fuzz tester for Django views.This tester will inject XSS patterns into the context data for a template before it is rendered, including:Simple stringsAttributes of Django ORM objects in QuerySetsThe goal of this tool is to quickly find any XSS vulnerabilities in Django templates.Any successful injections will write a message to the browser JavaScript console.InstallationInstall via pip$pipinstalldjango-xss-fuzzerAddViewFuzzerMiddlewareto your middleware list for atest environment.MIDDLEWARE=[...'django_xss_fuzzer.ViewFuzzerMiddleware']Do not deploy this to a production server!ConfigurationConfigure the middleware via the Django global settings.XSS_PATTERN: An XSS patterns to try. SeeXSS Cheatsheetfor inspiration.XSS_INJECT_KWARGS(Default False) : A switch to disable injecting XSS view function keyword argumentsXSS_INJECT_CONTEXT_DATA(Default True) : A switch to disable injecting XSS into class dataAutomated fuzzing with Pytest and SeleniumThis package comes with a Pytest extension to add a parametrized fixture,xss_pattern.Once you've restarted Django, it will replace anything "string-like" in the context data with a malicious string.
By default it will try<script>throw onerror=eval,\'=console.log\x28\\\'{0}\\\'\x29\'</script>.The values that will be replaced :Any string variablesAny attributes in a model instance that are stringsAny attributes in a QuerySet containing data models that are stringsWhen you browse any of the pages on your site, you should see Django successfully protecting and escaping the strings.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.To change the malicious string, set theXSS_PATTERNvariable in your Django settings.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.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 occurences of--SUCCESS[field]--and then fail the test if one is found.Here is an example test for the URLs/and/home:importpytestpaths=('/','/home')@pytest.mark.django_db()@pytest.mark.parametrize('path',paths)deftest_xss_patterns(selenium,live_server,settings,xss_pattern,path):setattr(settings,'XSS_PATTERN',xss_pattern.string)selenium.get('%s%s'%(live_server.url,path),)assertnotxss_pattern.succeeded(selenium),xss_pattern.messageThe test functiontest_xss_patternsis a parametrized test that will run a live server usingpytest-djangoand open a browser for each test usingpytest-selenium.
To test more views, just add the URIs topaths.To setup selenium, add the following to yourconftest.py:importpytest@pytest.fixture(scope='session')defsession_capabilities(session_capabilities):session_capabilities['goog:loggingPrefs']={'browser':'ALL'}returnsession_capabilities@pytest.fixturedefchrome_options(chrome_options):chrome_options.headless=Truereturnchrome_optionsThis will configure Chrome as headless and enable logging to capture the XSS flaws.To run PyTest with this plugin, use the--driverflag as Chrome and--driver-pathto point to a downloaded version of the Chrome Driver for the version of Chrome you have installed.$python-mpytesttests/--driverChrome--driver-path/path/to/chromedriver-rs-vvOnce this is running, you'll see something similar to the following output:For each failed test, inspect that particular view with the attack string and see where the potential vulnerability is.What about Django's builtin XSS protection?In 99% of cases, Django will sanitize the injection strings and they will be unsuccessful.However, there are some limitations, such as unquoted expressions of HTML tag attributes<styleclass={{var}}>...</style>This extension would automatically replacevarwithx onafterscriptexecute=console.log('found attribute-based xss in {0}').Django would render the following HTML:<styleclass=xonafterscriptexecute=console.log('foundattribute-basedxssin{0}')>...</style>The JavaScript code within the onafterscriptexecute would be run by the browser, demonstrating the vulnerability.Other examples, would be the use of the|safefilter inside the Django template. This filter can be put into Django views without a full-understanding of the ramifications.For example, in a permanent XSS attack, the database, or memory state could contain a dangerous string.Running in CI/CDGitHub Actions has Chrome and Chromedriver preinstalled on theubuntu-latestimage.You can run the tests with the same flag with the environment variable:-name:Run Security Testsrun:|python -m pytest tests/your_security_tests --driver Chrome --driver-path $CHROMEWEBDRIVER/chromedriverAzure Pipelines uses the same image, but has a different syntax. You can run using a script task like this:-script:|pytest tests/your_security_tests --driver Chrome --driver-path $(CHROMEWEBDRIVER)/chromedriverdisplayName:'RunSecuritytests'Also use mypytest-azurepipelinesextension to automate the publishing of test results to the pipelines UI.