From 25df4501283d419a6281cc2e6241a4539d803850 Mon Sep 17 00:00:00 2001 From: Nguyen Dinh Bien <44922242+biennd279@users.noreply.github.com> Date: Thu, 1 Feb 2024 03:20:03 +0700 Subject: [PATCH] Add parser for Sonarqube JSON result. (#9366) * init parser * fix filename * add testcase * Update docs * strip severity beforce compare * rebase from upstream/dev * remove not need newline * fix flake8 * Update docs * update recommend version * add recommend version in parser description --------- Co-authored-by: biennd4 --- .../en/integrations/parsers/file/sonarqube.md | 11 +- dojo/tools/sonarqube/parser.py | 90 +++++++++-- .../scans/sonarqube/sonar-6-findings.json | 139 ++++++++++++++++ .../scans/sonarqube/sonar-no-finding.json | 63 ++++++++ .../scans/sonarqube/sonar-single-finding.json | 79 ++++++++++ unittests/scans/sonarqube/sonar.json | 139 ++++++++++++++++ unittests/tools/test_sonarqube_parser.py | 148 ++++++++++++------ 7 files changed, 608 insertions(+), 61 deletions(-) create mode 100644 unittests/scans/sonarqube/sonar-6-findings.json create mode 100644 unittests/scans/sonarqube/sonar-no-finding.json create mode 100644 unittests/scans/sonarqube/sonar-single-finding.json create mode 100644 unittests/scans/sonarqube/sonar.json diff --git a/docs/content/en/integrations/parsers/file/sonarqube.md b/docs/content/en/integrations/parsers/file/sonarqube.md index 9e4da8c6f99..4f5e90ed128 100644 --- a/docs/content/en/integrations/parsers/file/sonarqube.md +++ b/docs/content/en/integrations/parsers/file/sonarqube.md @@ -4,21 +4,24 @@ toc_hide: true --- ## SonarQube Scan (Aggregates findings per cwe, title, description, file\_path.) -SonarQube output file can be imported in HTML format. +SonarQube output file can be imported in HTML format or JSON format. JSON format generated by options `--save-report-json` and have same behavior with HTML format. To generate the report, see Version: \>= 1.1.0 +Recommend version for both format \>= 3.1.2 ## SonarQube Scan Detailed (Import all findings from SonarQube html report.) -SonarQube output file can be imported in HTML format. +SonarQube output file can be imported in HTML format or JSON format. JSON format generated by options `--save-report-json` and have same behavior with HTML format. To generate the report, see -Version: \>= 1.1.0 +Version: \>= 1.1.0. +Recommend version for both format \>= 3.1.2 + ### Sample Scan Data -Sample SonarQube scans can be found [here](https://github.com/DefectDojo/django-DefectDojo/tree/master/unittests/scans/sonarqube). \ No newline at end of file +Sample SonarQube scans can be found [here](https://github.com/DefectDojo/django-DefectDojo/tree/master/unittests/scans/sonarqube). diff --git a/dojo/tools/sonarqube/parser.py b/dojo/tools/sonarqube/parser.py index b8026fc453f..e7a04c545d7 100644 --- a/dojo/tools/sonarqube/parser.py +++ b/dojo/tools/sonarqube/parser.py @@ -3,6 +3,7 @@ from django.utils.html import strip_tags from lxml import etree +import json from dojo.models import Finding @@ -23,21 +24,88 @@ def get_label_for_scan_types(self, scan_type): def get_description_for_scan_types(self, scan_type): if scan_type == "SonarQube Scan": - return "Aggregates findings per cwe, title, description, file_path. SonarQube output file can be imported in HTML format. Generate with https://github.com/soprasteria/sonar-report version >= 1.1.0" + return "Aggregates findings per cwe, title, description, file_path. SonarQube output file can be imported in HTML format or JSON format. Generate with https://github.com/soprasteria/sonar-report version >= 1.1.0, recommend version >= 3.1.2" else: - return "Import all findings from sonarqube html report. SonarQube output file can be imported in HTML format. Generate with https://github.com/soprasteria/sonar-report version >= 1.1.0" + return "Import all findings from sonarqube html report or JSON format. SonarQube output file can be imported in HTML format or JSON format. Generate with https://github.com/soprasteria/sonar-report version >= 1.1.0, recommend version >= 3.1.2" def get_findings(self, filename, test): - parser = etree.HTMLParser() - tree = etree.parse(filename, parser) - if self.mode not in [None, "detailed"]: - raise ValueError( - "Internal error: Invalid mode " - + self.mode - + ". Expected: one of None, 'detailed'" - ) + if filename.name.strip().lower().endswith(".json"): + json_content = json.load(filename) + return self.get_json_items(json_content, test, self.mode) + else: + parser = etree.HTMLParser() + tree = etree.parse(filename, parser) + if self.mode not in [None, "detailed"]: + raise ValueError( + "Internal error: Invalid mode " + + self.mode + + ". Expected: one of None, 'detailed'" + ) + + return self.get_items(tree, test, self.mode) - return self.get_items(tree, test, self.mode) + def get_json_items(self, json_content, test, mode): + dupes = dict() + rules = json_content["rules"] + issues = json_content["issues"] + for issue in issues: + key = issue["key"] + line = str(issue["line"]) + mitigation = issue["message"] + title = issue["description"] + file_path = issue["component"] + severity = self.convert_sonar_severity(issue["severity"]) + rule_id = issue["rule"] + + if title is None or mitigation is None: + raise ValueError( + "Parser ValueError: can't find a title or a mitigation for vulnerability of name " + + rule_id + ) + + try: + issue_detail = rules[rule_id] + parser = etree.HTMLParser() + html_desc_as_e_tree = etree.fromstring(issue_detail["htmlDesc"], parser) + issue_description = self.get_description(html_desc_as_e_tree) + logger.debug(issue_description) + issue_references = self.get_references( + rule_id, html_desc_as_e_tree + ) + issue_cwe = self.get_cwe(issue_references) + except KeyError: + issue_description = "No description provided" + issue_references = "" + issue_cwe = 0 + + if mode is None: + self.process_result_file_name_aggregated( + test, + dupes, + title, + issue_cwe, + issue_description, + file_path, + line, + severity, + mitigation, + issue_references, + ) + else: + self.process_result_detailed( + test, + dupes, + title, + issue_cwe, + issue_description, + file_path, + line, + severity, + mitigation, + issue_references, + key, + ) + return list(dupes.values()) def get_items(self, tree, test, mode): # Check that there is at least one vulnerability (the vulnerabilities diff --git a/unittests/scans/sonarqube/sonar-6-findings.json b/unittests/scans/sonarqube/sonar-6-findings.json new file mode 100644 index 00000000000..63512fc09d2 --- /dev/null +++ b/unittests/scans/sonarqube/sonar-6-findings.json @@ -0,0 +1,139 @@ +{ + "date": "Thursday, Jan 18, 2024", + "projectName": "vulnerable-flask-app", + "inNewCodePeriod": false, + "allBugs": false, + "fixMissingRule": false, + "noSecurityHotspot": false, + "noRulesInReport": false, + "onlyDetectedRules": true, + "vulnerabilityPhrase": "Vulnerability", + "noCoverage": true, + "vulnerabilityPluralPhrase": "Vulnerabilities", + "sonarBaseURL": "https://sonar.192-168-38-31.nip.io", + "sonarComponent": "vulnerable-flask-app", + "rules": { + "python:S4502": { + "name": "Disabling CSRF protections is security-sensitive", + "htmlDesc": "

A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive\nactions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the\napplication.

\n

The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a\nhidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.

\n

Ask Yourself Whether

\n
    \n
  • The web application uses cookies to authenticate users.
  • \n
  • There exist sensitive operations in the web application that can be performed when the user is authenticated.
  • \n
  • The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example.
  • \n
\n

There is a risk if you answered yes to any of those questions.

\n

Recommended Secure Coding Practices

\n
    \n
  • Protection against CSRF attacks is strongly recommended:\n
      \n
    • to be activated by default for all unsafe HTTP\n methods.
    • \n
    • implemented, for example, with an unguessable CSRF token
    • \n
  • \n
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be\n used only for information retrieval.
  • \n
\n

Sensitive Code Example

\n

For a Django application, the code is sensitive when,

\n
    \n
  • django.middleware.csrf.CsrfViewMiddleware is not used in the Django settings:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n] # Sensitive: django.middleware.csrf.CsrfViewMiddleware is missing\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\n@csrf_exempt # Sensitive\ndef example(request):\n    return HttpResponse(\"default\")\n
\n

For a Flask application, the code is sensitive when,

\n
    \n
  • the WTF_CSRF_ENABLED setting is set to false:
  • \n
\n
\napp = Flask(__name__)\napp.config['WTF_CSRF_ENABLED'] = False # Sensitive\n
\n
    \n
  • the application doesn’t use the CSRFProtect module:
  • \n
\n
\napp = Flask(__name__) # Sensitive: CSRFProtect is missing\n\n@app.route('/')\ndef hello_world():\n    return 'Hello, World!'\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app)\n\n@app.route('/example/', methods=['POST'])\n@csrf.exempt # Sensitive\ndef example():\n    return 'example '\n
\n
    \n
  • the CSRF protection is disabled on a form:
  • \n
\n
\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = False # Sensitive\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

Compliant Solution

\n

For a Django application,

\n
    \n
  • it is recommended to protect all the views with django.middleware.csrf.CsrfViewMiddleware:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware', # Compliant\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n
\n
    \n
  • and to not disable the CSRF protection on specific views:
  • \n
\n
\ndef example(request): # Compliant\n    return HttpResponse(\"default\")\n
\n

For a Flask application,

\n
    \n
  • the CSRFProtect module should be used (and not disabled further with WTF_CSRF_ENABLED set to false):\n
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app) # Compliant\n
\n
    \n
  • and it is recommended to not disable the CSRF protection on specific views or forms:
  • \n
\n
\n@app.route('/example/', methods=['POST']) # Compliant\ndef example():\n    return 'example '\n\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = True # Compliant\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

See

\n", + "severity": "CRITICAL" + }, + "python:S4792": { + "name": "Configuring loggers is security-sensitive", + "htmlDesc": "

Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities:

\n\n

Logs are useful before, during and after a security incident.

\n
    \n
  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it\n is the first step to prevent an attack from ever happening.
  • \n
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.
  • \n
\n

Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information\nlogged and how they are logged.

\n

This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews.

\n

Ask Yourself Whether

\n
    \n
  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives\n access to them.
  • \n
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • \n
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the\n user can perform the action as many times as he/she wants.
  • \n
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error)\n might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • \n
  • the logs are only stored locally instead of being backuped or replicated.
  • \n
\n

There is a risk if you answered yes to any of those questions.

\n

Recommended Secure Coding Practices

\n
    \n
  • Check that your production deployment doesn’t have its loggers in \"debug\" mode as it might write sensitive information in logs.
  • \n
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • \n
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the\n hostname.
  • \n
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the\n impact is known and limited.
  • \n
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the\n service are secure too.
  • \n
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control\n the logged information. An attacker could just repeat a logged action many times.
  • \n
\n

Remember that configuring loggers properly doesn’t make them bullet-proof. Here is a list of recommendations explaining on how to use your\nlogs:

\n
    \n
  • Don’t log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user\n names, locations, etc…​ Usually any information which is protected by law is good candidate for removal.
  • \n
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc…​ As for any user\n input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example\n use all your storage space or compromise your log indexing service.
  • \n
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as\n failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • \n
  • Monitor the logs for any suspicious activity.
  • \n
\n

Sensitive Code Example

\n
\nimport logging\nfrom logging import Logger, Handler, Filter\nfrom logging.config import fileConfig, dictConfig\n\nlogging.basicConfig()  # Sensitive\n\nlogging.disable()  # Sensitive\n\n\ndef update_logging(logger_class):\n    logging.setLoggerClass(logger_class)  # Sensitive\n\n\ndef set_last_resort(last_resort):\n    logging.lastResort = last_resort  # Sensitive\n\n\nclass CustomLogger(Logger):  # Sensitive\n    pass\n\n\nclass CustomHandler(Handler):  # Sensitive\n    pass\n\n\nclass CustomFilter(Filter):  # Sensitive\n    pass\n\n\ndef update_config(path, config):\n    fileConfig(path)  # Sensitive\n    dictConfig(config)  # Sensitive\n
\n

See

\n", + "severity": "CRITICAL" + } + }, + "issues": [ + { + "rule": "python:S4502", + "severity": "CRITICAL", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 8, + "description": "Disabling CSRF protections is security-sensitive", + "message": "Make sure disabling CSRF protection is safe here.", + "key": "AYvNd32RyD1npIoQXyT1" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 24, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT2" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 49, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT3" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 81, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT6" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 108, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32SyD1npIoQXyT9" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 185, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32SyD1npIoQXyUB" + } + ], + "hotspotKeys": [ + "AYvNd32RyD1npIoQXyT1", + "AYvNd32RyD1npIoQXyT2", + "AYvNd32RyD1npIoQXyT3", + "AYvNd32RyD1npIoQXyT6", + "AYvNd32SyD1npIoQXyT9", + "AYvNd32SyD1npIoQXyUB" + ], + "deltaAnalysis": "No", + "qualityGateStatusPeriodDate": "2023-11-15", + "qualityGateStatus": { + "projectStatus": { + "status": "OK", + "conditions": [ + { + "status": "OK", + "metricKey": "new reliability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new security rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new maintainability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + } + ], + "ignoredConditions": false, + "period": { + "mode": "PREVIOUS_VERSION", + "date": "2023-11-15T07:40:39+0000" + }, + "caycStatus": "compliant" + } + }, + "summary": { + "blocker": 0, + "critical": 1, + "major": 0, + "minor": 5 + } +} \ No newline at end of file diff --git a/unittests/scans/sonarqube/sonar-no-finding.json b/unittests/scans/sonarqube/sonar-no-finding.json new file mode 100644 index 00000000000..9d80f1dbb65 --- /dev/null +++ b/unittests/scans/sonarqube/sonar-no-finding.json @@ -0,0 +1,63 @@ +{ + "date": "Thursday, Jan 18, 2024", + "projectName": "vulnerable-flask-app", + "inNewCodePeriod": false, + "allBugs": false, + "fixMissingRule": false, + "noSecurityHotspot": false, + "noRulesInReport": false, + "onlyDetectedRules": true, + "vulnerabilityPhrase": "Vulnerability", + "noCoverage": true, + "vulnerabilityPluralPhrase": "Vulnerabilities", + "sonarBaseURL": "https://sonar.192-168-38-31.nip.io", + "sonarComponent": "vulnerable-flask-app", + "rules": { + }, + "issues": [ + ], + "hotspotKeys": [ + ], + "deltaAnalysis": "No", + "qualityGateStatusPeriodDate": "2023-11-15", + "qualityGateStatus": { + "projectStatus": { + "status": "OK", + "conditions": [ + { + "status": "OK", + "metricKey": "new reliability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new security rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new maintainability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + } + ], + "ignoredConditions": false, + "period": { + "mode": "PREVIOUS_VERSION", + "date": "2023-11-15T07:40:39+0000" + }, + "caycStatus": "compliant" + } + }, + "summary": { + "blocker": 0, + "critical": 1, + "major": 0, + "minor": 5 + } +} \ No newline at end of file diff --git a/unittests/scans/sonarqube/sonar-single-finding.json b/unittests/scans/sonarqube/sonar-single-finding.json new file mode 100644 index 00000000000..ecc8e52f57f --- /dev/null +++ b/unittests/scans/sonarqube/sonar-single-finding.json @@ -0,0 +1,79 @@ +{ + "date": "Thursday, Jan 18, 2024", + "projectName": "vulnerable-flask-app", + "inNewCodePeriod": false, + "allBugs": false, + "fixMissingRule": false, + "noSecurityHotspot": false, + "noRulesInReport": false, + "onlyDetectedRules": true, + "vulnerabilityPhrase": "Vulnerability", + "noCoverage": true, + "vulnerabilityPluralPhrase": "Vulnerabilities", + "sonarBaseURL": "https://sonar.192-168-38-31.nip.io", + "sonarComponent": "vulnerable-flask-app", + "rules": { + "python:S4502": { + "name": "Disabling CSRF protections is security-sensitive", + "htmlDesc": "

A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive\nactions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the\napplication.

\n

The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a\nhidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.

\n

Ask Yourself Whether

\n
    \n
  • The web application uses cookies to authenticate users.
  • \n
  • There exist sensitive operations in the web application that can be performed when the user is authenticated.
  • \n
  • The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example.
  • \n
\n

There is a risk if you answered yes to any of those questions.

\n

Recommended Secure Coding Practices

\n
    \n
  • Protection against CSRF attacks is strongly recommended:\n
      \n
    • to be activated by default for all unsafe HTTP\n methods.
    • \n
    • implemented, for example, with an unguessable CSRF token
    • \n
  • \n
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be\n used only for information retrieval.
  • \n
\n

Sensitive Code Example

\n

For a Django application, the code is sensitive when,

\n
    \n
  • django.middleware.csrf.CsrfViewMiddleware is not used in the Django settings:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n] # Sensitive: django.middleware.csrf.CsrfViewMiddleware is missing\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\n@csrf_exempt # Sensitive\ndef example(request):\n    return HttpResponse(\"default\")\n
\n

For a Flask application, the code is sensitive when,

\n
    \n
  • the WTF_CSRF_ENABLED setting is set to false:
  • \n
\n
\napp = Flask(__name__)\napp.config['WTF_CSRF_ENABLED'] = False # Sensitive\n
\n
    \n
  • the application doesn’t use the CSRFProtect module:
  • \n
\n
\napp = Flask(__name__) # Sensitive: CSRFProtect is missing\n\n@app.route('/')\ndef hello_world():\n    return 'Hello, World!'\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app)\n\n@app.route('/example/', methods=['POST'])\n@csrf.exempt # Sensitive\ndef example():\n    return 'example '\n
\n
    \n
  • the CSRF protection is disabled on a form:
  • \n
\n
\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = False # Sensitive\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

Compliant Solution

\n

For a Django application,

\n
    \n
  • it is recommended to protect all the views with django.middleware.csrf.CsrfViewMiddleware:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware', # Compliant\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n
\n
    \n
  • and to not disable the CSRF protection on specific views:
  • \n
\n
\ndef example(request): # Compliant\n    return HttpResponse(\"default\")\n
\n

For a Flask application,

\n
    \n
  • the CSRFProtect module should be used (and not disabled further with WTF_CSRF_ENABLED set to false):\n
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app) # Compliant\n
\n
    \n
  • and it is recommended to not disable the CSRF protection on specific views or forms:
  • \n
\n
\n@app.route('/example/', methods=['POST']) # Compliant\ndef example():\n    return 'example '\n\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = True # Compliant\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

See

\n", + "severity": "CRITICAL" + } + }, + "issues": [ + { + "rule": "python:S4502", + "severity": "CRITICAL", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 8, + "description": "Disabling CSRF protections is security-sensitive", + "message": "Make sure disabling CSRF protection is safe here.", + "key": "AYvNd32RyD1npIoQXyT1" + } + ], + "hotspotKeys": [ + "AYvNd32RyD1npIoQXyT1" + ], + "deltaAnalysis": "No", + "qualityGateStatusPeriodDate": "2023-11-15", + "qualityGateStatus": { + "projectStatus": { + "status": "OK", + "conditions": [ + { + "status": "OK", + "metricKey": "new reliability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new security rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new maintainability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + } + ], + "ignoredConditions": false, + "period": { + "mode": "PREVIOUS_VERSION", + "date": "2023-11-15T07:40:39+0000" + }, + "caycStatus": "compliant" + } + }, + "summary": { + "blocker": 0, + "critical": 1, + "major": 0, + "minor": 5 + } +} \ No newline at end of file diff --git a/unittests/scans/sonarqube/sonar.json b/unittests/scans/sonarqube/sonar.json new file mode 100644 index 00000000000..63512fc09d2 --- /dev/null +++ b/unittests/scans/sonarqube/sonar.json @@ -0,0 +1,139 @@ +{ + "date": "Thursday, Jan 18, 2024", + "projectName": "vulnerable-flask-app", + "inNewCodePeriod": false, + "allBugs": false, + "fixMissingRule": false, + "noSecurityHotspot": false, + "noRulesInReport": false, + "onlyDetectedRules": true, + "vulnerabilityPhrase": "Vulnerability", + "noCoverage": true, + "vulnerabilityPluralPhrase": "Vulnerabilities", + "sonarBaseURL": "https://sonar.192-168-38-31.nip.io", + "sonarComponent": "vulnerable-flask-app", + "rules": { + "python:S4502": { + "name": "Disabling CSRF protections is security-sensitive", + "htmlDesc": "

A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive\nactions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the\napplication.

\n

The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a\nhidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.

\n

Ask Yourself Whether

\n
    \n
  • The web application uses cookies to authenticate users.
  • \n
  • There exist sensitive operations in the web application that can be performed when the user is authenticated.
  • \n
  • The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example.
  • \n
\n

There is a risk if you answered yes to any of those questions.

\n

Recommended Secure Coding Practices

\n
    \n
  • Protection against CSRF attacks is strongly recommended:\n
      \n
    • to be activated by default for all unsafe HTTP\n methods.
    • \n
    • implemented, for example, with an unguessable CSRF token
    • \n
  • \n
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be\n used only for information retrieval.
  • \n
\n

Sensitive Code Example

\n

For a Django application, the code is sensitive when,

\n
    \n
  • django.middleware.csrf.CsrfViewMiddleware is not used in the Django settings:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n] # Sensitive: django.middleware.csrf.CsrfViewMiddleware is missing\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\n@csrf_exempt # Sensitive\ndef example(request):\n    return HttpResponse(\"default\")\n
\n

For a Flask application, the code is sensitive when,

\n
    \n
  • the WTF_CSRF_ENABLED setting is set to false:
  • \n
\n
\napp = Flask(__name__)\napp.config['WTF_CSRF_ENABLED'] = False # Sensitive\n
\n
    \n
  • the application doesn’t use the CSRFProtect module:
  • \n
\n
\napp = Flask(__name__) # Sensitive: CSRFProtect is missing\n\n@app.route('/')\ndef hello_world():\n    return 'Hello, World!'\n
\n
    \n
  • the CSRF protection is disabled on a view:
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app)\n\n@app.route('/example/', methods=['POST'])\n@csrf.exempt # Sensitive\ndef example():\n    return 'example '\n
\n
    \n
  • the CSRF protection is disabled on a form:
  • \n
\n
\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = False # Sensitive\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

Compliant Solution

\n

For a Django application,

\n
    \n
  • it is recommended to protect all the views with django.middleware.csrf.CsrfViewMiddleware:
  • \n
\n
\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware', # Compliant\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n
\n
    \n
  • and to not disable the CSRF protection on specific views:
  • \n
\n
\ndef example(request): # Compliant\n    return HttpResponse(\"default\")\n
\n

For a Flask application,

\n
    \n
  • the CSRFProtect module should be used (and not disabled further with WTF_CSRF_ENABLED set to false):\n
  • \n
\n
\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(app) # Compliant\n
\n
    \n
  • and it is recommended to not disable the CSRF protection on specific views or forms:
  • \n
\n
\n@app.route('/example/', methods=['POST']) # Compliant\ndef example():\n    return 'example '\n\nclass unprotectedForm(FlaskForm):\n    class Meta:\n        csrf = True # Compliant\n\n    name = TextField('name')\n    submit = SubmitField('submit')\n
\n

See

\n", + "severity": "CRITICAL" + }, + "python:S4792": { + "name": "Configuring loggers is security-sensitive", + "htmlDesc": "

Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities:

\n\n

Logs are useful before, during and after a security incident.

\n
    \n
  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it\n is the first step to prevent an attack from ever happening.
  • \n
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.
  • \n
\n

Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information\nlogged and how they are logged.

\n

This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews.

\n

Ask Yourself Whether

\n
    \n
  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives\n access to them.
  • \n
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • \n
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the\n user can perform the action as many times as he/she wants.
  • \n
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error)\n might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • \n
  • the logs are only stored locally instead of being backuped or replicated.
  • \n
\n

There is a risk if you answered yes to any of those questions.

\n

Recommended Secure Coding Practices

\n
    \n
  • Check that your production deployment doesn’t have its loggers in \"debug\" mode as it might write sensitive information in logs.
  • \n
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • \n
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the\n hostname.
  • \n
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the\n impact is known and limited.
  • \n
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the\n service are secure too.
  • \n
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control\n the logged information. An attacker could just repeat a logged action many times.
  • \n
\n

Remember that configuring loggers properly doesn’t make them bullet-proof. Here is a list of recommendations explaining on how to use your\nlogs:

\n
    \n
  • Don’t log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user\n names, locations, etc…​ Usually any information which is protected by law is good candidate for removal.
  • \n
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc…​ As for any user\n input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example\n use all your storage space or compromise your log indexing service.
  • \n
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as\n failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • \n
  • Monitor the logs for any suspicious activity.
  • \n
\n

Sensitive Code Example

\n
\nimport logging\nfrom logging import Logger, Handler, Filter\nfrom logging.config import fileConfig, dictConfig\n\nlogging.basicConfig()  # Sensitive\n\nlogging.disable()  # Sensitive\n\n\ndef update_logging(logger_class):\n    logging.setLoggerClass(logger_class)  # Sensitive\n\n\ndef set_last_resort(last_resort):\n    logging.lastResort = last_resort  # Sensitive\n\n\nclass CustomLogger(Logger):  # Sensitive\n    pass\n\n\nclass CustomHandler(Handler):  # Sensitive\n    pass\n\n\nclass CustomFilter(Filter):  # Sensitive\n    pass\n\n\ndef update_config(path, config):\n    fileConfig(path)  # Sensitive\n    dictConfig(config)  # Sensitive\n
\n

See

\n", + "severity": "CRITICAL" + } + }, + "issues": [ + { + "rule": "python:S4502", + "severity": "CRITICAL", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 8, + "description": "Disabling CSRF protections is security-sensitive", + "message": "Make sure disabling CSRF protection is safe here.", + "key": "AYvNd32RyD1npIoQXyT1" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 24, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT2" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 49, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT3" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 81, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32RyD1npIoQXyT6" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 108, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32SyD1npIoQXyT9" + }, + { + "rule": "python:S4792", + "severity": "MINOR", + "status": "TO_REVIEW", + "component": "vulnerable-flask-app.py", + "line": 185, + "description": "Configuring loggers is security-sensitive", + "message": "Make sure that this logger's configuration is safe.", + "key": "AYvNd32SyD1npIoQXyUB" + } + ], + "hotspotKeys": [ + "AYvNd32RyD1npIoQXyT1", + "AYvNd32RyD1npIoQXyT2", + "AYvNd32RyD1npIoQXyT3", + "AYvNd32RyD1npIoQXyT6", + "AYvNd32SyD1npIoQXyT9", + "AYvNd32SyD1npIoQXyUB" + ], + "deltaAnalysis": "No", + "qualityGateStatusPeriodDate": "2023-11-15", + "qualityGateStatus": { + "projectStatus": { + "status": "OK", + "conditions": [ + { + "status": "OK", + "metricKey": "new reliability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new security rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + }, + { + "status": "OK", + "metricKey": "new maintainability rating", + "comparator": "GT", + "errorThreshold": "A", + "actualValue": "A" + } + ], + "ignoredConditions": false, + "period": { + "mode": "PREVIOUS_VERSION", + "date": "2023-11-15T07:40:39+0000" + }, + "caycStatus": "compliant" + } + }, + "summary": { + "blocker": 0, + "critical": 1, + "major": 0, + "minor": 5 + } +} \ No newline at end of file diff --git a/unittests/tools/test_sonarqube_parser.py b/unittests/tools/test_sonarqube_parser.py index b688afa73ee..9474760f2e6 100644 --- a/unittests/tools/test_sonarqube_parser.py +++ b/unittests/tools/test_sonarqube_parser.py @@ -19,7 +19,7 @@ def init(self, reportFilename): # SonarQube Scan - no finding def test_file_name_aggregated_parse_file_with_no_vulnerabilities_has_no_findings( - self, + self, ): my_file_handle, product, engagement, test = self.init( get_unit_tests_path() + "/scans/sonarqube/sonar-no-finding.html" @@ -40,7 +40,7 @@ def test_detailed_parse_file_with_no_vulnerabilities_has_no_findings(self): # SonarQube Scan - report with one vuln def test_file_name_aggregated_parse_file_with_single_vulnerability_has_single_finding( - self, + self, ): my_file_handle, product, engagement, test = self.init( get_unit_tests_path() + "/scans/sonarqube/sonar-single-finding.html" @@ -134,50 +134,8 @@ def test_detailed_parse_file_with_single_vulnerability_has_single_finding(self): self.assertEqual(str, type(item.unique_id_from_tool)) self.assertEqual("AWK40IMu-pl6AHs22MnV", item.unique_id_from_tool) - def check_parse_file_with_single_vulnerability_has_single_finding(self): - self.assertEqual(1, len(findings)) - - # check content - item = findings[0] - self.assertEqual(str, type(findings[0].title)) - self.assertEqual("Credentials should not be hard-coded", item.title) - self.assertEqual(int, type(item.cwe)) - # This is only the first CWE in the list! - self.assertEqual(798, item.cwe) - self.assertEqual(bool, type(item.active)) - self.assertEqual(False, item.active) - self.assertEqual(bool, type(item.verified)) - self.assertEqual(False, item.verified) - self.assertEqual(str, type(item.severity)) - self.assertEqual("Critical", item.severity) - self.assertEqual(str, type(item.mitigation)) - self.assertEqual( - "'PASSWORD' detected in this expression, review this potentially hardcoded credential.", - item.mitigation, - ) - self.assertEqual(str, type(item.references)) - self.assertMultiLineEqual( - "squid:S2068\n" - "OWASP Top 10 2017 Category A2\n" - "MITRE, CWE-798\n" - "MITRE, CWE-259\n" - "CERT, MSC03-J.\n" - "SANS Top 25\n" - "Hard Coded Password", - item.references, - ) - self.assertEqual(str, type(item.file_path)) - self.assertEqual( - "modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java", - item.file_path, - ) - self.assertEqual(bool, type(item.static_finding)) - self.assertEqual(True, item.static_finding) - self.assertEqual(bool, type(item.dynamic_finding)) - self.assertEqual(False, item.dynamic_finding) - def test_detailed_parse_file_with_multiple_vulnerabilities_has_multiple_findings( - self, + self, ): my_file_handle, product, engagement, test = self.init( get_unit_tests_path() + "/scans/sonarqube/sonar-6-findings.html" @@ -189,7 +147,7 @@ def test_detailed_parse_file_with_multiple_vulnerabilities_has_multiple_findings self.assertEqual(6, len(findings)) def test_file_name_aggregated_parse_file_with_multiple_vulnerabilities_has_multiple_findings( - self, + self, ): my_file_handle, product, engagement, test = self.init( get_unit_tests_path() + "/scans/sonarqube/sonar-6-findings.html" @@ -491,3 +449,101 @@ def test_detailed_parse_file_table_has_whitespace(self): self.assertEqual(True, item.static_finding) self.assertEqual(bool, type(item.dynamic_finding)) self.assertEqual(False, item.dynamic_finding) + + def test_detailed_parse_json_file_with_no_vulnerabilities_has_no_findings(self): + my_file_handle, product, engagement, test = self.init( + get_unit_tests_path() + "/scans/sonarqube/sonar-no-finding.json" + ) + parser = SonarQubeParser() + parser.set_mode('detailed') + findings = parser.get_findings(my_file_handle, test) + self.assertEqual(0, len(findings)) + + def test_detailed_parse_json_file_with_single_vulnerability_has_single_finding(self): + my_file_handle, product, engagement, test = self.init( + get_unit_tests_path() + "/scans/sonarqube/sonar-single-finding.json" + ) + parser = SonarQubeParser() + parser.set_mode('detailed') + findings = parser.get_findings(my_file_handle, test) + # common verifications + self.assertEqual(1, len(findings)) + # specific verifications + item = findings[0] + self.assertEqual(str, type(item.description)) + self.maxDiff = None + self.assertMultiLineEqual('A cross-site request forgery (CSRF) attack occurs when a trusted user of a web ' + 'application can be forced, by an attacker, to perform sensitive\nactions that he ' + 'didn’t intend, such as updating his profile or sending a message, more generally ' + 'anything that can change the state of the\napplication.\nThe attacker can trick ' + 'the user/victim to click on a link, corresponding to the privileged action, ' + 'or to visit a malicious web site that embeds a\nhidden web request and as web ' + 'browsers automatically include cookies, the actions can be authenticated and ' + 'sensitive.\n**Ask Yourself Whether**\n\n The web application uses cookies to ' + 'authenticate users. \n There exist sensitive operations in the web application ' + 'that can be performed when the user is authenticated. \n The state / resources ' + 'of the web application can be modified by doing HTTP POST or HTTP DELETE requests ' + 'for example. \n\nThere is a risk if you answered yes to any of those ' + 'questions.\n**Recommended Secure Coding Practices**\n\n Protection against CSRF ' + 'attacks is strongly recommended:\n \n to be activated by default for all ' + 'unsafe HTTP\n methods. \n implemented, for example, with an unguessable ' + 'CSRF token \n \n Of course all sensitive operations should not be performed ' + 'with safe HTTP methods like GET which are designed to be\n used only for ' + 'information retrieval. \n\n**Sensitive Code Example**\nFor a Django application, ' + 'the code is sensitive when,\n\n django.middleware.csrf.CsrfViewMiddleware is not ' + 'used in the Django settings: \n\n\nMIDDLEWARE = [\n ' + '\'django.middleware.security.SecurityMiddleware\',' + '\n \'django.contrib.sessions.middleware.SessionMiddleware\',' + '\n \'django.middleware.common.CommonMiddleware\',' + '\n \'django.contrib.auth.middleware.AuthenticationMiddleware\',' + '\n \'django.contrib.messages.middleware.MessageMiddleware\',' + '\n \'django.middleware.clickjacking.XFrameOptionsMiddleware\',\n] # Sensitive: ' + 'django.middleware.csrf.CsrfViewMiddleware is missing\n\n\n the CSRF protection ' + 'is disabled on a view: \n\n\n@csrf_exempt # Sensitive\ndef example(request):\n ' + 'return HttpResponse("default")\n\nFor a Flask application, the code is sensitive ' + 'when,\n\n the WTF_CSRF_ENABLED setting is set to false: \n\n\napp = Flask(' + '__name__)\napp.config[\'WTF_CSRF_ENABLED\'] = False # Sensitive\n\n\n the ' + 'application doesn’t use the CSRFProtect module: \n\n\napp = Flask(__name__) # ' + 'Sensitive: CSRFProtect is missing\n\n@app.route(\'/\')\ndef hello_world():\n ' + 'return \'Hello, World!\'\n\n\n the CSRF protection is disabled on a view: ' + '\n\n\napp = Flask(__name__)\ncsrf = CSRFProtect()\ncsrf.init_app(' + 'app)\n\n@app.route(\'/example/\', methods=[\'POST\'])\n@csrf.exempt # ' + 'Sensitive\ndef example():\n return \'example \'\n\n\n the CSRF protection is ' + 'disabled on a form: \n\n\nclass unprotectedForm(FlaskForm):\n class Meta:\n ' + ' csrf = False # Sensitive\n\n name = TextField(\'name\')\n submit = ' + 'SubmitField(\'submit\')\n\n**Compliant Solution**\nFor a Django application,' + '\n\n it is recommended to protect all the views with ' + 'django.middleware.csrf.CsrfViewMiddleware: \n\n\nMIDDLEWARE = [\n ' + '\'django.middleware.security.SecurityMiddleware\',' + '\n \'django.contrib.sessions.middleware.SessionMiddleware\',' + '\n \'django.middleware.common.CommonMiddleware\',' + '\n \'django.middleware.csrf.CsrfViewMiddleware\', # Compliant\n ' + '\'django.contrib.auth.middleware.AuthenticationMiddleware\',' + '\n \'django.contrib.messages.middleware.MessageMiddleware\',' + '\n \'django.middleware.clickjacking.XFrameOptionsMiddleware\',\n]\n\n\n and ' + 'to not disable the CSRF protection on specific views: \n\n\ndef example(request): ' + '# Compliant\n return HttpResponse("default")\n\nFor a Flask application,' + '\n\n the CSRFProtect module should be used (and not disabled further with ' + 'WTF_CSRF_ENABLED set to false):\n \n\n\napp = Flask(__name__)\ncsrf = ' + 'CSRFProtect()\ncsrf.init_app(app) # Compliant\n\n\n and it is recommended to not ' + 'disable the CSRF protection on specific views or forms: \n\n\n@app.route(' + '\'/example/\', methods=[\'POST\']) # Compliant\ndef example():\n return ' + '\'example \'\n\nclass unprotectedForm(FlaskForm):\n class Meta:\n csrf = ' + 'True # Compliant\n\n name = TextField(\'name\')\n submit = SubmitField(' + '\'submit\')\n\n'.strip(), + item.description) + self.assertEqual(str, type(item.line)) + self.assertEqual(8, 8) + self.assertEqual(str, type(item.unique_id_from_tool)) + self.assertEqual("AYvNd32RyD1npIoQXyT1", item.unique_id_from_tool) + + def test_detailed_parse_json_file_with_multiple_vulnerabilities_has_multiple_findings(self): + my_file_handle, product, engagement, test = self.init( + get_unit_tests_path() + "/scans/sonarqube/sonar-6-findings.json" + ) + parser = SonarQubeParser() + parser.set_mode('detailed') + findings = parser.get_findings(my_file_handle, test) + # common verifications + # (there is no aggregation to be done here) + self.assertEqual(6, len(findings))