Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Including CWE information #613

Merged
merged 22 commits into from
Jan 30, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
84 changes: 77 additions & 7 deletions bandit/core/issue.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,71 @@
from bandit.core import constants


class Cwe(object):
ericwb marked this conversation as resolved.
Show resolved Hide resolved
UNDEF = 0
IMPROPER_INPUT_VALIDATION = 20
OS_COMMAND_INJECTION = 78
BASIC_XSS = 80
SQL_INJECTION = 89
CODE_INJECTION = 94
IMPROPER_WILDCARD_NEUTRALIZATION = 155
HARD_CODED_PASSWORD = 259
IMPROPER_CERT_VALIDATION = 295
INADEQUATE_ENCRYPTION_STRENGH = 326
julianthome marked this conversation as resolved.
Show resolved Hide resolved
BROKEN_CRYPTO = 327
INSECURE_TEMP_FILE = 377
MULTIPLE_BINDS = 605
IMPROPER_CHECK_OF_EXEPT_COND = 703
julianthome marked this conversation as resolved.
Show resolved Hide resolved
INCORRECT_PERMISSION_ASSIGNMENT = 732

MITRE_URL_PATTERN = "https://cwe.mitre.org/data/definitions/%s.html"

def __init__(self, id=UNDEF):
self.id = id

def link(self):
if self.id == Cwe.UNDEF:
return ""

return Cwe.MITRE_URL_PATTERN % str(self.id)

def __str__(self):
if self.id == Cwe.UNDEF:
return ""

return "CWE-%i (%s)" % (self.id, self.link())

def as_dict(self):
return {
"id": self.id,
"link": self.link()
} if self.id != Cwe.UNDEF else {}

def as_jsons(self):
return str(self.as_dict())

def from_dict(self, data):
if 'id' in data:
self.id = int(data['id'])
ericwb marked this conversation as resolved.
Show resolved Hide resolved
else:
self.id = Cwe.UNDEF

def __eq__(self, other):
return self.id == other.id

def __ne__(self, other):
return self.id != other.id

def __hash__(self):
return id(self)


class Issue(object):
def __init__(self, severity, confidence=constants.CONFIDENCE_DEFAULT,
def __init__(self, severity, cwe=0,
confidence=constants.CONFIDENCE_DEFAULT,
text="", ident=None, lineno=None, test_id=""):
self.severity = severity
self.cwe = Cwe(cwe)
self.confidence = confidence
if isinstance(text, bytes):
text = text.decode('utf-8')
Expand All @@ -30,16 +91,17 @@ def __init__(self, severity, confidence=constants.CONFIDENCE_DEFAULT,
self.linerange = []

def __str__(self):
return ("Issue: '%s' from %s:%s: Severity: %s Confidence: "
return ("Issue: '%s' from %s:%s: CWE: %s, Severity: %s Confidence: "
"%s at %s:%i") % (self.text, self.test_id,
(self.ident or self.test), self.severity,
self.confidence, self.fname, self.lineno)
(self.ident or self.test), str(self.cwe),
self.severity, self.confidence, self.fname,
self.lineno)

def __eq__(self, other):
# if the issue text, severity, confidence, and filename match, it's
# the same issue from our perspective
match_types = ['text', 'severity', 'confidence', 'fname', 'test',
'test_id']
match_types = ['text', 'severity', 'cwe', 'confidence', 'fname',
'test', 'test_id']
return all(getattr(self, field) == getattr(other, field)
for field in match_types)

Expand Down Expand Up @@ -101,11 +163,12 @@ def as_dict(self, with_code=True):
'test_name': self.test,
'test_id': self.test_id,
'issue_severity': self.severity,
'issue_cwe': self.cwe.as_dict(),
'issue_confidence': self.confidence,
'issue_text': self.text.encode('utf-8').decode('utf-8'),
'line_number': self.lineno,
'line_range': self.linerange,
}
}

if with_code:
out['code'] = self.get_code()
Expand All @@ -115,6 +178,7 @@ def from_dict(self, data, with_code=True):
self.code = data["code"]
self.fname = data["filename"]
self.severity = data["issue_severity"]
self.cwe = cwe_from_dict(data["issue_cwe"])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this why bandit 1.7.3 fails to load baseline data from JSON created by older bandit releases?

[manager] WARNING Failed to load baseline data: 'issue_cwe'

self.confidence = data["issue_confidence"]
self.text = data["issue_text"]
self.test = data["test_name"]
Expand All @@ -123,6 +187,12 @@ def from_dict(self, data, with_code=True):
self.linerange = data["line_range"]


def cwe_from_dict(data):
cwe = Cwe()
cwe.from_dict(data)
return cwe


def issue_from_dict(data):
i = Issue(severity=data["issue_severity"])
i.from_dict(data)
Expand Down
2 changes: 2 additions & 0 deletions bandit/formatters/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
'test_name',
'test_id',
'issue_severity',
'issue_cwe',
'issue_confidence',
'issue_text',
'line_number',
Expand All @@ -67,6 +68,7 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
writer.writeheader()
for result in results:
r = result.as_dict(with_code=False)
r['issue_cwe'] = r['issue_cwe']['link']
r['more_info'] = docs_utils.get_url(r['test_id'])
writer.writerow(r)

Expand Down
2 changes: 2 additions & 0 deletions bandit/formatters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
<b>{test_name}: </b> {test_text}<br>
<b>Test ID:</b> {test_id}<br>
<b>Severity: </b>{severity}<br>
<b>CWE: </b>{cwe}<br>
<b>Confidence: </b>{confidence}<br>
<b>File: </b><a href="{path}" target="_blank">{path}</a> <br>
<b>More info: </b><a href="{url}" target="_blank">{url}</a><br>
Expand Down Expand Up @@ -360,6 +361,7 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
test_id=issue.test_id,
test_text=issue.text,
severity=issue.severity,
cwe=issue.cwe,
confidence=issue.confidence,
path=issue.fname, code=code,
candidates=candidates,
Expand Down
8 changes: 5 additions & 3 deletions bandit/formatters/screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,12 @@ def _output_issue_str(issue, indent, show_lineno=True, show_code=True,
# returns a list of lines that should be added to the existing lines list
bits = []
bits.append("%s%s>> Issue: [%s:%s] %s" % (
indent, COLOR[issue.severity], issue.test_id, issue.test, issue.text))
indent, COLOR[issue.severity], issue.test_id, issue.test,
issue.text))

bits.append("%s Severity: %s Confidence: %s" % (
indent, issue.severity.capitalize(), issue.confidence.capitalize()))
bits.append("%s Severity: %s CWE: %s Confidence: %s" % (
indent, issue.severity.capitalize(), str(issue.cwe),
issue.confidence.capitalize()))

bits.append("%s Location: %s:%s" % (
indent, issue.fname,
Expand Down
5 changes: 3 additions & 2 deletions bandit/formatters/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ def _output_issue_str(issue, indent, show_lineno=True, show_code=True,
bits.append("%s>> Issue: [%s:%s] %s" % (
indent, issue.test_id, issue.test, issue.text))

bits.append("%s Severity: %s Confidence: %s" % (
indent, issue.severity.capitalize(), issue.confidence.capitalize()))
bits.append("%s Severity: %s CWE: %s Confidence: %s" % (
indent, issue.severity.capitalize(), str(issue.cwe),
issue.confidence.capitalize()))

bits.append("%s Location: %s:%s" % (
indent, issue.fname, issue.lineno if show_lineno else ""))
Expand Down
8 changes: 5 additions & 3 deletions bandit/formatters/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,11 @@ def report(manager, fileobj, sev_level, conf_level, lines=-1):
testcase = ET.SubElement(root, 'testcase',
classname=issue.fname, name=test)

text = 'Test ID: %s Severity: %s Confidence: %s\n%s\nLocation %s:%s'
text = text % (issue.test_id, issue.severity, issue.confidence,
issue.text, issue.fname, issue.lineno)
text = 'Test ID: %s Severity: %s CWE: %s ' \
'Confidence: %s\n%s\nLocation %s:%s'
text = text % (issue.test_id, issue.severity, issue.cwe,
issue.confidence, issue.text, issue.fname,
issue.lineno)
ET.SubElement(testcase, 'error',
more_info=docs_utils.get_url(issue.test_id),
type=issue.severity,
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/app_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -51,6 +52,7 @@ def flask_debug_true(context):
if context.check_call_arg_value('debug', 'True'):
return bandit.Issue(
severity=bandit.HIGH,
cwe=Cwe.CODE_INJECTION,
confidence=bandit.MEDIUM,
text="A Flask app appears to be run with debug=True, "
"which exposes the Werkzeug debugger and allows "
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/asserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -49,6 +50,7 @@
def assert_used(context):
return bandit.Issue(
severity=bandit.LOW,
cwe=Cwe.IMPROPER_CHECK_OF_EXEPT_COND,
confidence=bandit.HIGH,
text=("Use of assert detected. The enclosed code "
"will be removed when compiling to optimised byte code.")
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/crypto_request_no_cert_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -54,6 +55,7 @@ def request_with_no_cert_validation(context):
if context.check_call_arg_value('verify', 'False'):
issue = bandit.Issue(
severity=bandit.HIGH,
cwe=Cwe.IMPROPER_CERT_VALIDATION,
confidence=bandit.HIGH,
text="Requests call with verify=False disabling SSL "
"certificate checks, security issue.",
Expand Down
3 changes: 3 additions & 0 deletions bandit/plugins/django_sql_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import ast

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand Down Expand Up @@ -77,6 +78,7 @@ def django_extra_used(context):
if insecure:
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.SQL_INJECTION,
confidence=bandit.MEDIUM,
text=description
)
Expand All @@ -102,6 +104,7 @@ def django_rawsql_used(context):
if not isinstance(sql, ast.Str):
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.SQL_INJECTION,
confidence=bandit.MEDIUM,
text=description
)
2 changes: 2 additions & 0 deletions bandit/plugins/django_xss.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import six

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand Down Expand Up @@ -250,6 +251,7 @@ def check_risk(node):
if not secure:
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.BASIC_XSS,
confidence=bandit.HIGH,
text=description
ericwb marked this conversation as resolved.
Show resolved Hide resolved
)
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@
import six

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


def exec_issue():
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.OS_COMMAND_INJECTION,
confidence=bandit.HIGH,
text="Use of exec detected."
)
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/general_bad_file_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import stat

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -73,6 +74,7 @@ def set_bad_file_permissions(context):
filename = 'NOT PARSED'
return bandit.Issue(
severity=sev_level,
cwe=Cwe.INCORRECT_PERMISSION_ASSIGNMENT,
confidence=bandit.HIGH,
text="Chmod setting a permissive mask %s on file (%s)." %
(oct(mode), filename)
Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/general_bind_all_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -43,6 +44,7 @@ def hardcoded_bind_all_interfaces(context):
if context.string_val == '0.0.0.0':
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.MULTIPLE_BINDS,
confidence=bandit.MEDIUM,
text="Possible binding to all interfaces."
)
2 changes: 2 additions & 0 deletions bandit/plugins/general_hardcoded_password.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import sys

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -22,6 +23,7 @@
def _report(value):
return bandit.Issue(
severity=bandit.LOW,
cwe=Cwe.HARD_CODED_PASSWORD,
confidence=bandit.MEDIUM,
text=("Possible hardcoded password: '%s'" % value))

Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/general_hardcoded_tmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -71,6 +72,7 @@ def hardcoded_tmp_directory(context, config):
if any(context.string_val.startswith(s) for s in tmp_dirs):
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.INSECURE_TEMP_FILE,
confidence=bandit.MEDIUM,
text="Probable insecure usage of temp file/directory."
)
2 changes: 2 additions & 0 deletions bandit/plugins/hashlib_new_insecure_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"""

import bandit
from bandit.core.issue import Cwe as Cwe
from bandit.core import test_properties as test


Expand All @@ -48,6 +49,7 @@ def hashlib_new(context):
name.lower() in ('md4', 'md5', 'sha', 'sha1')):
return bandit.Issue(
severity=bandit.MEDIUM,
cwe=Cwe.BROKEN_CRYPTO,
confidence=bandit.HIGH,
text="Use of insecure MD4 or MD5 hash function.",
lineno=context.node.lineno,
Expand Down