code
stringlengths 12
2.05k
| label
int64 0
1
| programming_language
stringclasses 9
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
103
⌀ | description
stringlengths 36
1.23k
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
def test_change_to_invalid_due_date(self):
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
'due_datetime': '01/01/2009 00:00'
})
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
) | 1 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
"""
if not hasattr(self, "_xsrf_token"):
version, token, timestamp = self._get_raw_xsrf_token()
mask = os.urandom(4)
self._xsrf_token = b"|".join([
b"2",
binascii.b2a_hex(mask),
binascii.b2a_hex(_websocket_mask(mask, token)),
utf8(str(int(timestamp)))])
if version is None or version != 2:
expires_days = 30 if self.current_user else None
self.set_cookie("_xsrf", self._xsrf_token,
expires_days=expires_days)
return self._xsrf_token | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def testStringSplit(self):
data = ["123456"]
data_splits = [0, 1]
separator = "a" * 15
ngram_widths = []
pad_width = -5
left_pad = right_pad = ""
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Pad width should be >= 0"):
self.evaluate(gen_string_ops.string_n_grams(
data=data,
data_splits=data_splits,
separator=separator,
ngram_widths=ngram_widths,
left_pad=left_pad,
right_pad=right_pad,
pad_width=pad_width,
preserve_short_sequences=True)) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
def __init__(self, sydent):
self.sydent = sydent
# The default endpoint factory in Twisted 14.0.0 (which we require) uses the
# BrowserLikePolicyForHTTPS context factory which will do regular cert validation
# 'like a browser'
self.agent = Agent(
BlacklistingReactorWrapper(
reactor=self.sydent.reactor,
ip_whitelist=sydent.ip_whitelist,
ip_blacklist=sydent.ip_blacklist,
),
connectTimeout=15,
) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def useruid(s, login):
"""Connect to a LDAP and check the uid matching the given field data"""
uid = False
c = Connection(s, config.LDAPACC,
password=config.LDAPPASS, auto_bind=True)
if c.result["description"] != "success":
app.logger.error("Error connecting to the LDAP with the service account")
return False
# Look for the user entry.
if not c.search(config.LDAPBASE,
"(" + config.LDAPFIELD + "=" + login + ")") :
app.logger.error("Error: Connection to the LDAP with service account failed")
else:
if len(c.entries) >= 1 :
if len(c.entries) > 1 :
app.logger.error("Error: multiple entries with this login. "+ \
"Trying first entry...")
uid = c.entries[0].entry_dn
else:
app.logger.error("Error: Login not found")
c.unbind()
return uid | 0 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | vulnerable |
def test_28_catch_lnext_terminal_ctrl(self):
""" F25 | test ctrl-v ctrl-j then command, forbidden/security """
self.child = pexpect.spawn('%s/bin/lshell '
'--config %s/etc/lshell.conf '
% (TOPDIR, TOPDIR))
self.child.expect('%s:~\$' % self.user)
expected = u'*** forbidden syntax: echo\r'
self.child.send('echo')
self.child.sendcontrol('v')
self.child.sendcontrol('j')
self.child.sendline('bash')
self.child.expect('%s:~\$' % self.user)
result = self.child.before.decode('utf8').split('\n')
self.assertIn(expected, result) | 1 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
def get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
path = pathlib.PurePosixPath(path)
try:
location = storage.aws_location
except AttributeError:
location = storage.location
try:
f = storage.open(str(path.relative_to(location)))
f.name = path.name
yield f
except (OSError, ValueError):
logger.exception("File not found: %s", path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_received_control_line_finished_all_chunks_not_received(self):
buf = DummyBuffer()
inst = self._makeOne(buf)
result = inst.received(b"a;discard\r\n")
self.assertEqual(inst.control_line, b"")
self.assertEqual(inst.chunk_remainder, 10)
self.assertEqual(inst.all_chunks_received, False)
self.assertEqual(result, 11)
self.assertEqual(inst.completed, False) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def create_security_group(self, context, group_name, group_description):
if not re.match('^[a-zA-Z0-9_\- ]+$', str(group_name)):
# Some validation to ensure that values match API spec.
# - Alphanumeric characters, spaces, dashes, and underscores.
# TODO(Daviey): LP: #813685 extend beyond group_name checking, and
# probably create a param validator that can be used elsewhere.
err = _("Value (%s) for parameter GroupName is invalid."
" Content limited to Alphanumeric characters, "
"spaces, dashes, and underscores.") % group_name
# err not that of master ec2 implementation, as they fail to raise.
raise exception.InvalidParameterValue(err=err)
if len(str(group_name)) > 255:
err = _("Value (%s) for parameter GroupName is invalid."
" Length exceeds maximum of 255.") % group_name
raise exception.InvalidParameterValue(err=err)
LOG.audit(_("Create Security Group %s"), group_name, context=context)
self.compute_api.ensure_default_security_group(context)
if db.security_group_exists(context, context.project_id, group_name):
msg = _('group %s already exists')
raise exception.EC2APIError(msg % group_name)
if quota.allowed_security_groups(context, 1) < 1:
msg = _("Quota exceeded, too many security groups.")
raise exception.EC2APIError(msg)
group = {'user_id': context.user_id,
'project_id': context.project_id,
'name': group_name,
'description': group_description}
group_ref = db.security_group_create(context, group)
self.sgh.trigger_security_group_create_refresh(context, group)
return {'securityGroupSet': [self._format_security_group(context,
group_ref)]} | 1 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
def test_not_specifiying_wagtail_mount_point_does_not_prepend_allowed_paths_with_wagtail_mount_path(settings):
settings.WAGTAIL_MOUNT_PATH = ''
allowed_paths = VerifyUserMiddleware()._allowed_paths
for allowed_path in allowed_paths:
assert allowed_path.startswith('/cms') | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def check_both_ways(source):
ast.parse(source, type_comments=False)
with self.assertRaises(SyntaxError):
ast.parse(source, type_comments=True) | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def test_is_writable(self):
""" default_dir has to be writable """
path = catalog.default_dir()
name = os.path.join(path,'dummy_catalog')
test_file = open(name,'w')
try:
test_file.write('making sure default location is writable\n')
finally:
test_file.close()
os.remove(name) | 1 | Python | CWE-269 | Improper Privilege Management | The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
def test_get_mpi_implementation(self):
def test(output, expected, exit_code=0):
ret = (output, exit_code) if output is not None else None
env = {'VAR': 'val'}
with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m:
implementation = _get_mpi_implementation(env)
self.assertEqual(expected, implementation)
m.assert_called_once_with('mpirun --version', env)
test(("mpirun (Open MPI) 2.1.1\n"
"Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL)
test("OpenRTE", _OMPI_IMPL)
test("IBM Spectrum MPI", _SMPI_IMPL)
test(("HYDRA build details:\n"
" Version: 3.3a2\n"
" Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL)
test("Intel(R) MPI", _IMPI_IMPL)
test("Unknown MPI v1.00", _UNKNOWN_IMPL)
test("output", exit_code=1, expected=_MISSING_IMPL)
test(None, _MISSING_IMPL) | 0 | Python | CWE-668 | Exposure of Resource to Wrong Sphere | The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource. | https://cwe.mitre.org/data/definitions/668.html | vulnerable |
def test_29_catch_terminal_ctrl_k(self):
""" F29 | test ctrl-v ctrl-k then command, forbidden/security """
self.child = pexpect.spawn('%s/bin/lshell '
'--config %s/etc/lshell.conf '
% (TOPDIR, TOPDIR))
self.child.expect('%s:~\$' % self.user)
expected = u'*** forbidden control char: echo\x0b() bash && echo\r'
self.child.send('echo')
self.child.sendcontrol('v')
self.child.sendcontrol('k')
self.child.sendline('() bash && echo')
self.child.expect('%s:~\$' % self.user)
result = self.child.before.decode('utf8').split('\n')[1]
self.assertIn(expected, result) | 1 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
def testRaggedCountSparseOutputBadWeightsShape(self):
splits = [0, 4, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Weights and values must have the same shape"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 1 | Python | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
def test_http10_listlentwo(self):
body = string.ascii_letters
to_send = (
"GET /list_lentwo HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: %d\r\n\r\n" % len(body)
)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers.get("content-length"), None)
self.assertEqual(headers.get("connection"), "close")
self.assertEqual(response_body, tobytes(body))
# remote closed connection (despite keepalive header), because
# lists of length > 1 cannot have their content length divined
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def test_received_preq_error(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.completed = True
preq.error = True
inst.received(b"GET / HTTP/1.1\r\n\r\n")
self.assertEqual(inst.request, None)
self.assertEqual(len(inst.server.tasks), 1)
self.assertTrue(inst.requests) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def _hkey(s):
return s.title().replace('_', '-') | 0 | Python | CWE-93 | Improper Neutralization of CRLF Sequences ('CRLF Injection') | The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs. | https://cwe.mitre.org/data/definitions/93.html | vulnerable |
def _inject_metadata_into_fs(metadata, fs, execute=None):
metadata_path = os.path.join(fs, "meta.js")
metadata = dict([(m.key, m.value) for m in metadata])
utils.execute('tee', metadata_path,
process_input=jsonutils.dumps(metadata), run_as_root=True) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def __init__(self):
super(ManyCookies, self).__init__()
self.putChild(b'', HelloWorld())
self.putChild(b'login', self.SetMyCookie()) | 0 | Python | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
def config_basic(request):
form = BasicConfigForm(data=post_data(request))
if is_post(request) and form.is_valid():
form.save()
messages.info(request, _("Settings updated!"))
return redirect(request.GET.get("next", request.get_full_path()))
return render(
request=request,
template_name='spirit/admin/config_basic.html',
context={'form': form}) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def testRaggedCountSparseOutputBadSplitsStart(self):
splits = [1, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Splits must start with 0"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 1 | Python | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
def constructObject(data):
try:
m = import_module("messagetypes." + data[""])
classBase = getattr(m, data[""].title())
except (NameError, ImportError):
logger.error("Don't know how to handle message type: \"%s\"", data[""], exc_info=True)
return None
try:
returnObj = classBase()
returnObj.decode(data)
except KeyError as e:
logger.error("Missing mandatory key %s", e)
return None
except:
logger.error("classBase fail", exc_info=True)
return None
else:
return returnObj | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def testUnravelIndexIntegerOverflow(self):
with self.cached_session():
for dtype in [dtypes.int32, dtypes.int64]:
with self.assertRaisesRegex(
errors.InvalidArgumentError,
r"Input dims product is causing integer overflow"):
indices = constant_op.constant(-0x100000, dtype=dtype)
if dtype == dtypes.int32:
value = 0x10000000
else:
value = 0x7FFFFFFFFFFFFFFF
dims = constant_op.constant([value, value], dtype=dtype)
self.evaluate(array_ops.unravel_index(indices=indices, dims=dims)) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
def test_recursive_tf_function_call_each_other(self):
@def_function.function
def recursive_fn1(n):
if n <= 1:
return 1
return recursive_fn2(n - 1)
@def_function.function
def recursive_fn2(n):
if n <= 1:
return 2
return recursive_fn1(n - 1)
self.assertEqual(recursive_fn1(5).numpy(), 1)
self.assertEqual(recursive_fn1(6).numpy(), 2)
self.assertEqual(recursive_fn2(5).numpy(), 2)
self.assertEqual(recursive_fn2(6).numpy(), 1) | 1 | Python | CWE-667 | Improper Locking | The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors. | https://cwe.mitre.org/data/definitions/667.html | safe |
def testRaggedCountSparseOutputBadWeightsShape(self):
splits = [0, 4, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Weights and values must have the same shape"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 1 | Python | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
def test_modify_access_bad_role(self):
""" Test with an invalid action parameter. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'robot-not-a-roll',
'action': 'revoke',
})
self.assertEqual(response.status_code, 400) | 0 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
def prepare(self, reactor, clock, homeserver):
# make a second homeserver, configured to use the first one as a key notary
self.http_client2 = Mock()
config = default_config(name="keyclient")
config["trusted_key_servers"] = [
{
"server_name": self.hs.hostname,
"verify_keys": {
"ed25519:%s"
% (
self.hs_signing_key.version,
): signedjson.key.encode_verify_key_base64(
self.hs_signing_key.verify_key
)
},
}
]
self.hs2 = self.setup_test_homeserver(
federation_http_client=self.http_client2, config=config
)
# wire up outbound POST /key/v2/query requests from hs2 so that they
# will be forwarded to hs1
async def post_json(destination, path, data):
self.assertEqual(destination, self.hs.hostname)
self.assertEqual(
path, "/_matrix/key/v2/query",
)
channel = FakeChannel(self.site, self.reactor)
req = SynapseRequest(channel)
req.content = BytesIO(encode_canonical_json(data))
req.requestReceived(
b"POST", path.encode("utf-8"), b"1.1",
)
channel.await_result()
self.assertEqual(channel.code, 200)
resp = channel.json_body
return resp
self.http_client2.post_json.side_effect = post_json | 1 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | safe |
def _get_http_request(self, expected_host, expected_port):
clients = self.reactor.tcpClients
(host, port, factory, _timeout, _bindAddress) = clients[-1]
self.assertEqual(host, expected_host)
self.assertEqual(port, expected_port)
# complete the connection and wire it up to a fake transport
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol.makeConnection(transport)
return transport, protocol | 1 | Python | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
def _props_path(self):
"""Absolute path of the file storing the collection properties."""
return self._path + ".props" | 0 | Python | CWE-21 | DEPRECATED: Pathname Traversal and Equivalence Errors | This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706). | https://cwe.mitre.org/data/definitions/21.html | vulnerable |
def PUT(self, path, body, ensure_encoding=True, log_request_body=True, ignore_prefix=False):
return self._request('PUT', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body, ignore_prefix=ignore_prefix) | 1 | Python | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
"args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
"keywords=[]))], type_ignores=[])"
)
self.assertEqual(ast.dump(node, annotate_fields=False),
"Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
"Constant('and cheese')], []))], [])"
)
self.assertEqual(ast.dump(node, include_attributes=True),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
"lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
"args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
"end_lineno=1, end_col_offset=9), Constant(value='and cheese', "
"lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], "
"lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
"lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)], type_ignores=[])"
) | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def test_change_nonexistent_due_date(self):
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'student': self.user1.username,
'url': self.week3.location.to_deprecated_string(),
'due_datetime': '12/30/2013 00:00'
})
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week3, self.user1)
) | 1 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(
url,
payload=None,
method="GET",
headers={},
allow_truncated=False,
follow_redirects=True,
deadline=None,
):
return fetch(
url,
payload=payload,
method=method,
headers=headers,
allow_truncated=allow_truncated,
follow_redirects=follow_redirects,
deadline=deadline,
validate_certificate=validate_certificate,
)
return fixed_fetch | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
def create_service(self, context, OS_KSADM_service):
self.assert_admin(context)
service_id = uuid.uuid4().hex
service_ref = OS_KSADM_service.copy()
service_ref['id'] = service_id
new_service_ref = self.catalog_api.create_service(
context, service_id, service_ref)
return {'OS-KSADM:service': new_service_ref} | 1 | Python | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
def delete(self):
os.remove(self._path)
os.remove(self._props_path) | 0 | Python | CWE-21 | DEPRECATED: Pathname Traversal and Equivalence Errors | This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706). | https://cwe.mitre.org/data/definitions/21.html | vulnerable |
def extension_element_from_string(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _extension_element_from_element_tree(element_tree) | 0 | Python | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | vulnerable |
def is_valid_client_secret(client_secret):
"""Validate that a given string matches the client_secret regex defined by the spec
:param client_secret: The client_secret to validate
:type client_secret: str
:return: Whether the client_secret is valid
:rtype: bool
"""
return client_secret_regex.match(client_secret) is not None | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def render(self, name, value, attrs=None):
html = super(AdminURLFieldWidget, self).render(name, value, attrs)
if value:
value = force_text(self._format_value(value))
final_attrs = {'href': smart_urlquote(value)}
html = format_html(
'<p class="url">{0} <a{1}>{2}</a><br />{3} {4}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
return html | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def parse_func_type_input(source):
return ast.parse(source, "<unknown>", "func_type") | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def testBoostedTreesCalculateBestFeatureSplitV2Security(self):
node_id_range = [1, 2]
stats_summaries_list = [[[[[]]]]]
split_types = ['inequality']
candidate_feature_ids = [1, 2, 3, 4]
l1 = [1.0]
l2 = [1.0]
tree_complexity = [1.0]
min_node_weight = [1.17]
logits_dimension = 5
with self.assertRaises((errors.InvalidArgumentError, ValueError)):
gen_boosted_trees_ops.boosted_trees_calculate_best_feature_split_v2(
node_id_range=node_id_range,
stats_summaries_list=stats_summaries_list,
split_types=split_types,
candidate_feature_ids=candidate_feature_ids,
l1=l1,
l2=l2,
tree_complexity=tree_complexity,
min_node_weight=min_node_weight,
logits_dimension=logits_dimension) | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def test_basic_functionality(self):
self.create_test_files()
self.attic('init', self.repository_location)
self.attic('create', self.repository_location + '::test', 'input')
self.attic('create', self.repository_location + '::test.2', 'input')
with changedir('output'):
self.attic('extract', self.repository_location + '::test')
self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 11)
self.assert_dirs_equal('input', 'output/input')
info_output = self.attic('info', self.repository_location + '::test')
self.assert_in('Number of files: 4', info_output)
shutil.rmtree(self.cache_path)
with environment_variable(ATTIC_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='1'):
info_output2 = self.attic('info', self.repository_location + '::test')
# info_output2 starts with some "initializing cache" text but should
# end the same way as info_output
assert info_output2.endswith(info_output) | 1 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
def get(cls, uuid):
"""Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method.
"""
uuid = quote(str(uuid))
url = recurly.base_uri() + (cls.member_path % (uuid,))
resp, elem = cls.element_for_url(url)
return cls.from_element(elem) | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def _validate_untrusted_args(argv):
# NOTE: Do not use f-strings here, as this should run with older Python
# versions (so that a proper error can be displayed)
try:
untrusted_idx = argv.index('--untrusted-args')
except ValueError:
return
rest = argv[untrusted_idx + 1:]
if len(rest) > 1:
sys.exit(
"Found multiple arguments ({}) after --untrusted-args, "
"aborting.".format(' '.join(rest)))
for arg in rest:
if arg.startswith(('-', ':')):
sys.exit("Found {} after --untrusted-args, aborting.".format(arg)) | 1 | Python | CWE-641 | Improper Restriction of Names for Files and Other Resources | The application constructs the name of a file or other resource using input from an upstream component, but it does not restrict or incorrectly restricts the resulting name. | https://cwe.mitre.org/data/definitions/641.html | safe |
def parse(self, response):
yield {'response': response} | 0 | Python | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
def update(request, pk):
topic = Topic.objects.for_update_or_404(pk, request.user)
category_id = topic.category_id
form = TopicForm(
user=request.user,
data=post_data(request),
instance=topic)
if is_post(request) and form.is_valid():
topic = form.save()
if topic.category_id != category_id:
Comment.create_moderation_action(
user=request.user, topic=topic, action=Comment.MOVED)
return redirect(request.POST.get('next', topic.get_absolute_url()))
return render(
request=request,
template_name='spirit/topic/update.html',
context={'form': form}) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def test_ee_xxe():
xml = """<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
]>
<lolz>&lol1;</lolz>
"""
with raises(EntitiesForbidden):
saml2.extension_element_from_string(xml) | 1 | Python | CWE-611 | Improper Restriction of XML External Entity Reference | The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. | https://cwe.mitre.org/data/definitions/611.html | safe |
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# Ignores privilege escalation
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.jail)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr) | 0 | Python | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | vulnerable |
def get(self, request, name=None):
if name is None:
if request.user.is_staff:
return FormattedResponse(config.get_all())
return FormattedResponse(config.get_all_non_sensitive())
return FormattedResponse(config.get(name)) | 0 | Python | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
def test_basic_for_domain():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=4) as uri:
response, content = http.request(uri, "GET")
assert response.status == 401
http.add_credentials("joe", password, "example.org")
response, content = http.request(uri, "GET")
assert response.status == 401
domain = urllib.parse.urlparse(uri)[1]
http.add_credentials("joe", password, domain)
response, content = http.request(uri, "GET")
assert response.status == 200 | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
def test_device_delete_view_for_other_user_raises_error(self, user, verified_user, rf):
with override_settings(WAGTAIL_2FA_REQUIRED=True):
other_device = TOTPDevice.objects.create(name='Initial', user=user, confirmed=True)
device = TOTPDevice.objects.devices_for_user(verified_user, confirmed=True).first()
request = rf.get('foo')
request.user = verified_user
with pytest.raises(PermissionDenied):
response = DeviceDeleteView.as_view()(request, pk=other_device.id) | 1 | Python | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
def test_device_list_view_for_other_user_raises_error(self, user, verified_user, rf):
with override_settings(WAGTAIL_2FA_REQUIRED=True):
request = rf.get('foo')
request.user = verified_user
with pytest.raises(PermissionDenied):
response = DeviceListView.as_view()(request, user_id=user.id) | 1 | Python | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
def CreateID(self):
"""Create a packet ID. All RADIUS requests have a ID which is used to
identify a request. This is used to detect retries and replay attacks.
This function returns a suitable random number that can be used as ID.
:return: ID number
:rtype: integer
"""
return random_generator.randrange(0, 256) | 1 | Python | CWE-330 | Use of Insufficiently Random Values | The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers. | https://cwe.mitre.org/data/definitions/330.html | safe |
def DELETE(self, path, body=None, log_request_body=True, ignore_prefix=False):
return self._request('DELETE', path, body=body, log_request_body=log_request_body,
ignore_prefix=ignore_prefix) | 1 | Python | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
def add_security_headers(resp):
resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:"
if request.endpoint == "editbook.edit_book" or config.config_use_google_drive:
resp.headers['Content-Security-Policy'] += " *"
elif request.endpoint == "web.read_book":
resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';"
resp.headers['X-Content-Type-Options'] = 'nosniff'
resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
resp.headers['X-XSS-Protection'] = '1; mode=block'
resp.headers['Strict-Transport-Security'] = 'max-age=31536000;'
return resp | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def safe_markup(raw_html: str) -> jinja2.Markup:
"""
Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs.
Args
raw_html: Unsafe HTML.
Returns:
A Markup object ready to safely use in a Jinja template.
"""
return jinja2.Markup(
bleach.linkify(
bleach.clean(
raw_html,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRS,
# bleach master has this, but it isn't released yet
# protocols=ALLOWED_SCHEMES,
strip=True,
)
)
) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def needs_clamp(t, encoding):
if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
return False
if isinstance(t, (ByteArrayLike, DArrayType)):
if encoding == Encoding.JSON_ABI:
# don't have bytestring size bound from json, don't clamp
return False
return True
if isinstance(t, BaseType) and t.typ not in ("int256", "uint256", "bytes32"):
return True
if isinstance(t, SArrayType):
return needs_clamp(t.subtype, encoding)
if isinstance(t, TupleLike):
return any(needs_clamp(m, encoding) for m in t.tuple_members())
return False | 0 | Python | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
def sentences_victim(self, type, data = None, sRun = 1, column = 0):
if sRun == 2:
return self.sql_insert(self.prop_sentences_victim(type, data))
elif sRun == 3:
return self.sql_one_row(self.prop_sentences_victim(type, data), column)
else:
return self.sql_execute(self.prop_sentences_victim(type, data)) | 1 | Python | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
def test_received_get_no_headers(self):
data = b"HTTP/1.0 GET /foobar\r\n\r\n"
result = self.parser.received(data)
self.assertEqual(result, 24)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.headers, {}) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def test_conf_set_no_read(self):
orig_parser = memcache.ConfigParser
memcache.ConfigParser = ExcConfigParser
exc = None
try:
app = memcache.MemcacheMiddleware(
FakeApp(), {'memcache_servers': '1.2.3.4:5'})
except Exception, err:
exc = err
finally:
memcache.ConfigParser = orig_parser
self.assertEquals(exc, None) | 0 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | vulnerable |
def is_2fa_enabled(self):
return self.totp_status == TOTPStatus.ENABLED | 0 | Python | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
out_path = self._normalize_path(out_path, self.get_jail_path())
vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail)
self._copy_file(in_path, out_path) | 0 | Python | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | vulnerable |
def get_user_profile(access_token):
headers = {"Authorization": "OAuth {}".format(access_token)}
response = requests.get(
"https://www.googleapis.com/oauth2/v1/userinfo", headers=headers
)
if response.status_code == 401:
logger.warning("Failed getting user profile (response code 401).")
return None
return response.json() | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def test_get_addr_spec_multiple_domains(self):
with self.assertRaises(errors.HeaderParseError):
parser.get_addr_spec('[email protected]@example.com')
with self.assertRaises(errors.HeaderParseError):
parser.get_addr_spec('star@[email protected]')
with self.assertRaises(errors.HeaderParseError):
parser.get_addr_spec('[email protected]@example.com') | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def testValuesInVariable(self):
indices = constant_op.constant([[1]], dtype=dtypes.int64)
values = variables.Variable([1], trainable=False, dtype=dtypes.float32)
shape = constant_op.constant([1], dtype=dtypes.int64)
sp_input = sparse_tensor.SparseTensor(indices, values, shape)
sp_output = sparse_ops.sparse_add(sp_input, sp_input)
with test_util.force_cpu():
self.evaluate(variables.global_variables_initializer())
output = self.evaluate(sp_output)
self.assertAllEqual(output.values, [2]) | 0 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
def event_from_pdu_json(pdu_json, outlier=False):
"""Construct a FrozenEvent from an event json received over federation
Args:
pdu_json (object): pdu as received over federation
outlier (bool): True to mark this event as an outlier
Returns:
FrozenEvent
Raises:
SynapseError: if the pdu is missing required fields or is otherwise
not a valid matrix event
"""
# we could probably enforce a bunch of other fields here (room_id, sender,
# origin, etc etc)
assert_params_in_request(pdu_json, ('event_id', 'type', 'depth'))
depth = pdu_json['depth']
if not isinstance(depth, six.integer_types):
raise SynapseError(400, "Depth %r not an intger" % (depth, ),
Codes.BAD_JSON)
if depth < 0:
raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
elif depth > MAX_DEPTH:
raise SynapseError(400, "Depth too large", Codes.BAD_JSON)
event = FrozenEvent(
pdu_json
)
event.internal_metadata.outlier = outlier
return event | 1 | Python | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
def CreateID(self):
"""Create a packet ID. All RADIUS requests have a ID which is used to
identify a request. This is used to detect retries and replay attacks.
This function returns a suitable random number that can be used as ID.
:return: ID number
:rtype: integer
"""
return random_generator.randrange(0, 256) | 1 | Python | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
def testSparseCountSparseOutputBadIndicesShapeTooSmall(self):
indices = [1]
values = [[1]]
weights = []
dense_shape = [10]
with self.assertRaisesRegex(ValueError,
"Shape must be rank 2 but is rank 1 for"):
self.evaluate(
gen_count_ops.SparseCountSparseOutput(
indices=indices,
values=values,
dense_shape=dense_shape,
weights=weights,
binary_output=True)) | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def set(self, key, value, serialize=True, timeout=0):
"""
Set a key/value pair in memcache
:param key: key
:param value: value
:param serialize: if True, value is pickled before sending to memcache
:param timeout: ttl in memcache
"""
key = md5hash(key)
if timeout > 0:
timeout += time.time()
flags = 0
if serialize:
value = pickle.dumps(value, PICKLE_PROTOCOL)
flags |= PICKLE_FLAG
for (server, fp, sock) in self._get_conns(key):
try:
sock.sendall('set %s %d %d %s noreply\r\n%s\r\n' % \
(key, flags, timeout, len(value), value))
self._return_conn(server, fp, sock)
return
except Exception, e:
self._exception_occurred(server, e) | 0 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | vulnerable |
def test_request_body_too_large_with_wrong_cl_http11_connclose(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.1\r\nContent-Length: 5\r\nConnection: close\r\n\r\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
# server trusts the content-length header (5)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 1 | Python | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
def delete(request, pk, remove=True):
comment = get_object_or_404(Comment, pk=pk)
if is_post(request):
(Comment.objects
.filter(pk=pk)
.update(is_removed=remove))
return redirect(request.GET.get('next', comment.get_absolute_url()))
return render(
request=request,
template_name='spirit/comment/moderate.html',
context={'comment': comment}) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def visit_Call(self, node):
""" A couple function calls are supported: bson's ObjectId() and
datetime().
"""
if isinstance(node.func, ast.Name):
if node.func.id == 'ObjectId':
try:
self.current_value = ObjectId(node.args[0].s)
except:
pass
elif node.func.id == 'datetime':
values = []
for arg in node.args:
values.append(arg.n)
try:
self.current_value = datetime(*values)
except:
pass | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def make_homeserver(self, reactor, clock):
# we mock out the keyring so as to skip the authentication check on the
# federation API call.
mock_keyring = Mock(spec=["verify_json_for_server"])
mock_keyring.verify_json_for_server.return_value = defer.succeed(True)
# we mock out the federation client too
mock_federation_client = Mock(spec=["put_json"])
mock_federation_client.put_json.return_value = defer.succeed((200, "OK"))
# the tests assume that we are starting at unix time 1000
reactor.pump((1000,))
hs = self.setup_test_homeserver(
notifier=Mock(),
http_client=mock_federation_client,
keyring=mock_keyring,
replication_streams={},
)
return hs | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def connectionMade(self):
method = _ensureValidMethod(getattr(self.factory, 'method', b'GET'))
self.sendCommand(method, _ensureValidURI(self.factory.path))
if self.factory.scheme == b'http' and self.factory.port != 80:
host = self.factory.host + b':' + intToBytes(self.factory.port)
elif self.factory.scheme == b'https' and self.factory.port != 443:
host = self.factory.host + b':' + intToBytes(self.factory.port)
else:
host = self.factory.host
self.sendHeader(b'Host', self.factory.headers.get(b"host", host))
self.sendHeader(b'User-Agent', self.factory.agent)
data = getattr(self.factory, 'postdata', None)
if data is not None:
self.sendHeader(b"Content-Length", intToBytes(len(data)))
cookieData = []
for (key, value) in self.factory.headers.items():
if key.lower() not in self._specialHeaders:
# we calculated it on our own
self.sendHeader(key, value)
if key.lower() == b'cookie':
cookieData.append(value)
for cookie, cookval in self.factory.cookies.items():
cookieData.append(cookie + b'=' + cookval)
if cookieData:
self.sendHeader(b'Cookie', b'; '.join(cookieData))
self.endHeaders()
self.headers = {}
if data is not None:
self.transport.write(data) | 1 | Python | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
def test_unicode_encode_error(self, mocker):
url = QUrl('file:///tmp/foo')
req = QNetworkRequest(url)
err = UnicodeEncodeError('ascii', '', 0, 2, 'foo')
mocker.patch('os.path.isdir', side_effect=err)
reply = filescheme.handler(req)
assert reply is None | 0 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
def sql_insert(self, sentence):
self.cursor.execute(sentence)
self.conn.commit()
return True | 0 | Python | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
def stmt(self, stmt, msg=None):
mod = ast.Module([stmt])
self.mod(mod, msg) | 0 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
def test_visitor(self):
class CustomVisitor(self.asdl.VisitorBase):
def __init__(self):
super().__init__()
self.names_with_seq = []
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value)
def visitSum(self, sum):
for t in sum.types:
self.visit(t)
def visitConstructor(self, cons):
for f in cons.fields:
if f.seq:
self.names_with_seq.append(cons.name)
v = CustomVisitor()
v.visit(self.types['mod'])
self.assertEqual(v.names_with_seq,
['Module', 'Module', 'Interactive', 'FunctionType', 'Suite']) | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def test_template_render_with_noautoescape(self):
"""
Test if the autoescape value is getting passed to urlize_quoted_links filter.
"""
template = Template("{% load rest_framework %}"
"{% autoescape off %}{{ content|urlize_quoted_links }}"
"{% endautoescape %}")
rendered = template.render(Context({'content': '<b> "http://example.com" </b>'}))
assert rendered == '<b> "<a href="http://example.com" rel="nofollow">http://example.com</a>" </b>' | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_patch_bot_role(self) -> None:
self.login("desdemona")
email = "[email protected]"
user_profile = self.get_bot_user(email)
do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile)
req = dict(role=UserProfile.ROLE_GUEST)
result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req)
self.assert_json_success(result)
user_profile = self.get_bot_user(email)
self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST)
# Test for not allowing a non-owner user to make assign a bot an owner role
desdemona = self.example_user("desdemona")
do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)
req = dict(role=UserProfile.ROLE_REALM_OWNER)
result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req)
self.assert_json_error(result, "Must be an organization owner") | 0 | Python | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
def test_confirmation_expired(self) -> None:
email = self.nonreg_email("alice")
realm = get_realm("zulip")
inviter = self.example_user("iago")
prereg_user = PreregistrationUser.objects.create(
email=email, referred_by=inviter, realm=realm
)
date_sent = timezone_now() - datetime.timedelta(weeks=3)
with patch("confirmation.models.timezone_now", return_value=date_sent):
url = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION)
target_url = "/" + url.split("/", 3)[3]
result = self.client_get(target_url)
self.assertEqual(result.status_code, 404)
self.assert_in_response(
"Whoops. The confirmation link has expired or been deactivated.", result
) | 0 | Python | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
def _consumer(self, auth):
auth.process_response()
errors = auth.get_errors()
if not errors:
if auth.is_authenticated():
return True
else:
return False
else:
current_app.logger.error('Error processing %s' % (', '.join(errors)))
return False | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def init_app(app):
from redash.authentication import (
google_oauth,
saml_auth,
remote_user_auth,
ldap_auth,
)
login_manager.init_app(app)
login_manager.anonymous_user = models.AnonymousUser
login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION
@app.before_request
def extend_session():
session.permanent = True
app.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME)
from redash.security import csrf
for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]:
blueprint = auth.blueprint
csrf.exempt(blueprint)
app.register_blueprint(blueprint)
user_logged_in.connect(log_user_logged_in)
login_manager.request_loader(request_loader) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def _handle_carbon_received(self, msg):
self.xmpp.event('carbon_received', msg) | 0 | Python | CWE-346 | Origin Validation Error | The software does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | vulnerable |
def is_node(cls, path):
path = os.path.join(filesystem.FOLDER, path.replace("/", os.sep))
return os.path.isdir(path) and not os.path.exists(path + ".props") | 0 | Python | CWE-21 | DEPRECATED: Pathname Traversal and Equivalence Errors | This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706). | https://cwe.mitre.org/data/definitions/21.html | vulnerable |
def test_basic_auth_invalid_credentials(self):
with self.assertRaises(InvalidStatusCode) as raised:
self.start_client(user_info=("hello", "ihateyou"))
self.assertEqual(raised.exception.status_code, 401) | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def sql_one_row(self, sentence, column):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
return self.cursor.fetchone()[column] | 1 | Python | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
def encode_non_url_reserved_characters(url):
# safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2
return urlquote(url, safe=":/?#[]@!$&'()*+,;=") | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def _slices_from_text(self, text):
last_break = 0
for match in self._lang_vars.period_context_re().finditer(text):
context = match.group() + match.group("after_tok")
if self.text_contains_sentbreak(context):
yield slice(last_break, match.end())
if match.group("next_tok"):
# next sentence starts after whitespace
last_break = match.start("next_tok")
else:
# next sentence starts at following punctuation
last_break = match.end()
# The last sentence should not contain trailing whitespace.
yield slice(last_break, len(text.rstrip())) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
def _assert_not_matches(
self, condition: Dict[str, Any], content: Dict[str, Any], msg=None | 1 | Python | CWE-331 | Insufficient Entropy | The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async def on_GET(self, origin, content, query, context, user_id):
content = await self.handler.on_make_leave_request(origin, context, user_id)
return 200, content | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
def show_unit_extensions(request, course_id):
"""
Shows all of the students which have due date extensions for the given unit.
"""
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
unit = find_unit(course, request.POST.get('url'))
return JsonResponse(dump_module_extensions(course, unit)) | 1 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def testNestedRaggedMapWithFnOutputSignature(self):
ragged1d = ragged_tensor.RaggedTensorSpec([None], dtypes.int32)
ragged2d = ragged_tensor.RaggedTensorSpec([None, None], dtypes.int32)
x = ragged_factory_ops.constant([[1, 2, 3, 4], [1]])
# pylint: disable=g-long-lambda
y = map_fn_lib.map_fn(
lambda r: map_fn_lib.map_fn(
lambda y: r, r, fn_output_signature=ragged1d),
x,
fn_output_signature=ragged2d)
expected = [[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], [[1]]]
self.assertAllEqual(y, expected) | 1 | Python | CWE-681 | Incorrect Conversion between Numeric Types | When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur. | https://cwe.mitre.org/data/definitions/681.html | safe |
def to_html(self, data, options=None):
"""
Reserved for future usage.
The desire is to provide HTML output of a resource, making an API
available to a browser. This is on the TODO list but not currently
implemented.
"""
options = options or {}
return 'Sorry, not implemented yet. Please append "?format=json" to your URL.' | 1 | Python | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):
kwargs = {'course_id': unicode(self.course.id)}
kwargs.update(extra_instructor_api_kwargs)
url = reverse(instructor_api_endpoint, kwargs=kwargs)
success_status = "The {report_type} report is being created.".format(report_type=report_type)
if report_type == 'problem responses':
with patch(task_api_endpoint):
response = self.client.get(url, {'problem_location': ''})
self.assertIn(success_status, response.content)
else:
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
with patch(task_api_endpoint):
response = self.client.get(url, {})
self.assertIn(success_status, response.content) | 0 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
def create_code_for_user(cls, user, next=None):
if not user.is_active:
return None
code = cls.generate_code()
login_code = LoginCode(user=user, code=code)
if next is not None:
login_code.next = next
login_code.save()
return login_code | 0 | Python | CWE-312 | Cleartext Storage of Sensitive Information | The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere. | https://cwe.mitre.org/data/definitions/312.html | vulnerable |
def test_show_student_extensions(self):
self.test_change_due_date()
url = reverse('show_student_extensions',
kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'student': self.user1.username})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(json.loads(response.content), {
u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
u'Unit': self.week1.display_name}],
u'header': [u'Unit', u'Extended Due Date'],
u'title': u'Due date extensions for %s (%s)' % (
self.user1.profile.name, self.user1.username)}) | 1 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def testSparseFillEmptyRowsGradMatrix(self):
reverse_index_map = [0, 1]
grad_values = [[0, 1], [2, 3]]
# Note: Eager mode and graph mode throw different errors here. Graph mode
# will fail with a ValueError from the shape checking logic, while Eager
# will fail with an InvalidArgumentError from the kernel itself.
if context.executing_eagerly():
with self.assertRaisesRegex(errors.InvalidArgumentError,
r'grad_values must be a vector'):
self.evaluate(
gen_sparse_ops.SparseFillEmptyRowsGrad(
reverse_index_map=reverse_index_map, grad_values=grad_values))
else:
with self.assertRaisesRegex(ValueError,
r'Shape must be rank 1 but is rank 2'):
self.evaluate(
gen_sparse_ops.SparseFillEmptyRowsGrad(
reverse_index_map=reverse_index_map, grad_values=grad_values)) | 1 | Python | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
def __init__(self, path: Union[str, Path]):
super().__init__(path=Path(path))
self['headers'] = {}
self['cookies'] = {}
self['auth'] = {
'type': None,
'username': None,
'password': None
} | 0 | Python | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc":
return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
o = open(outfile, "wb")
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header
o.write("P5\n%d %d\n255\n" % self.size)
while True:
type, size = self.field()
if type != (8, 10):
break
while size > 0:
s = self.fp.read(min(size, 8192))
if not s:
break
o.write(s)
size = size - len(s)
o.close()
try:
try:
# fast
self.im = Image.core.open_ppm(outfile)
except:
# slightly slower
im = Image.open(outfile)
im.load()
self.im = im.im
finally:
try: os.unlink(outfile)
except: pass | 0 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.