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 _inject_file_into_fs(fs, path, contents, append=False):
absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/'))
parent_dir = os.path.dirname(absolute_path)
utils.execute('mkdir', '-p', parent_dir, run_as_root=True)
args = []
if append:
args.append('-a')
args.append(absolute_path)
kwargs = dict(process_input=contents, run_as_root=True)
utils.execute('tee', *args, **kwargs) | 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 tearDown(self):
self.file.close() | 1 | 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 | safe |
def from_html(self, content):
"""
Reserved for future usage.
The desire is to handle form-based (maybe Javascript?) input, making an
API available to a browser. This is on the TODO list but not currently
implemented.
"""
pass | 0 | 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 | vulnerable |
def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
raise NotImplementedError() | 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_login_unknown_code(self):
response = self.client.post('/accounts-rest/login/code/', {
'code': 'unknown',
})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(), {
'__all__': ['Unable to log in with provided login code.'],
'user': ['This field is required.']
}) | 1 | 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 | safe |
def check_auth(username, password):
try:
username = username.encode('windows-1252')
except UnicodeEncodeError:
username = username.encode('utf-8')
user = ub.session.query(ub.User).filter(func.lower(ub.User.name) ==
username.decode('utf-8').lower()).first()
if bool(user and check_password_hash(str(user.password), password)):
return True
else:
ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr)
log.warning('OPDS Login failed for user "%s" IP-address: %s', username.decode('utf-8'), ip_Address)
return False | 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 __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc) | 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 _join_and_check_path_within_fs(fs, *args):
'''os.path.join() with safety check for injected file paths.
Join the supplied path components and make sure that the
resulting path we are injecting into is within the
mounted guest fs. Trying to be clever and specifying a
path with '..' in it will hit this safeguard.
'''
absolute_path, _err = utils.execute('readlink', '-nm',
os.path.join(fs, *args),
run_as_root=True)
if not absolute_path.startswith(os.path.realpath(fs) + '/'):
raise exception.Invalid(_('injected file path not valid'))
return absolute_path | 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_received_control_line_finished_all_chunks_received(self):
buf = DummyBuffer()
inst = self._makeOne(buf)
result = inst.received(b"0;discard\n")
self.assertEqual(inst.control_line, b"")
self.assertEqual(inst.all_chunks_received, True)
self.assertEqual(result, 10)
self.assertEqual(inst.completed, False) | 0 | 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 | vulnerable |
def malt_regex_tagger():
from nltk.tag import RegexpTagger
_tagger = RegexpTagger(
[
(r"\.$", "."),
(r"\,$", ","),
(r"\?$", "?"), # fullstop, comma, Qmark
(r"\($", "("),
(r"\)$", ")"), # round brackets
(r"\[$", "["),
(r"\]$", "]"), # square brackets
(r"^-?[0-9]+(\.[0-9]+)?$", "CD"), # cardinal numbers
(r"(The|the|A|a|An|an)$", "DT"), # articles
(r"(He|he|She|she|It|it|I|me|Me|You|you)$", "PRP"), # pronouns
(r"(His|his|Her|her|Its|its)$", "PRP$"), # possessive
(r"(my|Your|your|Yours|yours)$", "PRP$"), # possessive
(r"(on|On|in|In|at|At|since|Since)$", "IN"), # time prepopsitions
(r"(for|For|ago|Ago|before|Before)$", "IN"), # time prepopsitions
(r"(till|Till|until|Until)$", "IN"), # time prepopsitions
(r"(by|By|beside|Beside)$", "IN"), # space prepopsitions
(r"(under|Under|below|Below)$", "IN"), # space prepopsitions
(r"(over|Over|above|Above)$", "IN"), # space prepopsitions
(r"(across|Across|through|Through)$", "IN"), # space prepopsitions
(r"(into|Into|towards|Towards)$", "IN"), # space prepopsitions
(r"(onto|Onto|from|From)$", "IN"), # space prepopsitions
(r".*able$", "JJ"), # adjectives
(r".*ness$", "NN"), # nouns formed from adjectives
(r".*ly$", "RB"), # adverbs
(r".*s$", "NNS"), # plural nouns
(r".*ing$", "VBG"), # gerunds
(r".*ed$", "VBD"), # past tense verbs
(r".*", "NN"), # nouns (default)
]
)
return _tagger.tag | 1 | Python | CWE-1333 | Inefficient Regular Expression Complexity | The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles. | https://cwe.mitre.org/data/definitions/1333.html | safe |
def test_sydent_rejects_invalid_hostname(self):
"""Tests that the /register endpoint rejects an invalid hostname passed as matrix_server_name"""
self.sydent.run()
bad_hostname = "example.com#"
request, channel = make_request(
self.sydent.reactor,
"POST",
"/_matrix/identity/v2/account/register",
content={
"matrix_server_name": bad_hostname,
"access_token": "foo"
})
request.render(self.sydent.servlets.registerServlet)
self.assertEqual(channel.code, 400) | 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 test_without_crlf(self):
data = "Echo\r\nthis\r\nplease"
s = tobytes(
"GET / HTTP/1.0\r\n"
"Connection: close\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(int(echo.content_length), len(data))
self.assertEqual(len(echo.body), len(data))
self.assertEqual(echo.body, tobytes(data)) | 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 testBadAxis(self):
input_tensor = [2.5, 2.5]
input_min = [0, 0]
input_max = [1, 1]
error_message_pattern = "Shape must be at least rank 11 but is rank 1"
# TODO(b/171260356): Eager mode and graph mode throw different error types
error = errors.InvalidArgumentError if context.executing_eagerly(
) else ValueError
with self.assertRaisesRegex(error, error_message_pattern):
self.evaluate(
array_ops.quantize_and_dequantize_v2(
input=input_tensor,
input_min=input_min,
input_max=input_max,
axis=10)) | 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 mysql_contains(field: Term, value: str) -> Criterion:
return Like(
functions.Cast(field, SqlTypes.CHAR), StrWrapper(f"%{escape_like(value)}%"), escape=""
) | 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 _is_javascript_scheme(s):
is_image_url = False
for image_type in _find_image_dataurls(s):
is_image_url = True
if _is_unsafe_image_type(image_type):
return True
if is_image_url:
return False
return bool(_is_possibly_malicious_scheme(s)) | 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 |
inline bool AveragePool(const uint8* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int filter_width, int filter_height,
int32 output_activation_min,
int32 output_activation_max, uint8* output_data,
const Dims<4>& output_dims) {
tflite::PoolParams params;
params.stride_height = stride_height;
params.stride_width = stride_width;
params.filter_height = filter_height;
params.filter_width = filter_width;
params.padding_values.height = pad_height;
params.padding_values.width = pad_width;
params.quantized_activation_min = output_activation_min;
params.quantized_activation_max = output_activation_max;
return AveragePool(params, DimsToShape(input_dims), input_data,
DimsToShape(output_dims), output_data);
} | 1 | Python | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
def security_group_rule_count_by_group(context, security_group_id):
"""Count rules in a given security group."""
return IMPL.security_group_rule_count_by_group(context, security_group_id) | 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_create_class_from_xml_string_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) as err:
create_class_from_xml_string(NameID, 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 test_list_instructor_tasks_running(self, act):
""" Test list of all running tasks. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.post(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks) | 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 check_valid_restricted_column(column):
if column != "0":
if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \
.filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all():
return False
return True | 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 dataReceived(self, data: bytes) -> None:
self.stream.write(data)
self.length += len(data)
if self.max_size is not None and self.length >= self.max_size:
self.deferred.errback(BodyExceededMaxSize())
self.deferred = defer.Deferred()
self.transport.loseConnection() | 1 | 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 | safe |
def visit_Call(self, node):
""" A couple function calls are supported: bson's ObjectId() and
datetime().
"""
if isinstance(node.func, ast.Name):
expr = None
if node.func.id == 'ObjectId':
expr = "('" + node.args[0].s + "')"
elif node.func.id == 'datetime':
values = []
for arg in node.args:
values.append(str(arg.n))
expr = "(" + ", ".join(values) + ")"
if expr:
self.current_value = eval(node.func.id + expr) | 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 render_POST(self, request):
"""
Register with the Identity Server
"""
send_cors(request)
args = get_args(request, ('matrix_server_name', 'access_token'))
result = yield self.client.get_json(
"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s" % (
args['matrix_server_name'], urllib.parse.quote(args['access_token']),
),
1024 * 5,
)
if 'sub' not in result:
raise Exception("Invalid response from homeserver")
user_id = result['sub']
tok = yield issueToken(self.sydent, user_id)
# XXX: `token` is correct for the spec, but we released with `access_token`
# for a substantial amount of time. Serve both to make spec-compliant clients
# happy.
defer.returnValue({
"access_token": tok,
"token": tok,
}) | 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 test_parse_header_connection_close(self):
data = b"GET /foobar HTTP/1.1\r\nConnection: close\r\n"
self.parser.parse_header(data)
self.assertEqual(self.parser.connection_close, True) | 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 getHostByName(self, name, timeout=None):
if name not in lookups:
return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
return succeed(lookups[name]) | 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 test_anymail_webhook_authorization(self):
errors = check_deprecated_settings(None)
self.assertEqual(errors, [checks.Warning(
"The ANYMAIL_WEBHOOK_AUTHORIZATION setting has been renamed ANYMAIL_WEBHOOK_SECRET to improve security.",
hint="You must update your settings.py. The old name will stop working in a near-future release.",
id="anymail.W001",
)]) | 1 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
def parse_line(s):
s = s.rstrip()
r = re.sub(REG_LINE_GPERF, '', s)
if r != s: return r
r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)
if r != s: return r
r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\1)', s)
if r != s: return r
r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)
if r != s: return r
r = re.sub(REG_ENTRY, '{\\1, \\2, \\3}', s)
if r != s: return r
r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\1, \\2}', s)
if r != s: return r
r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)
if r != s: return r
r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)
if r != s: return r
r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)
if r != s: return r
r = re.sub(REG_CODE_CHECK, 'if (code == gcode && wordlist[key].index >= 0)', s)
if r != s: return r
return s | 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 is_valid_hostname(string: str) -> bool:
"""Validate that a given string is a valid hostname or domain name, with an
optional port number.
For domain names, this only validates that the form is right (for
instance, it doesn't check that the TLD is valid). If a port is
specified, it has to be a valid port number.
:param string: The string to validate
:type string: str
:return: Whether the input is a valid hostname
:rtype: bool
"""
host_parts = string.split(":", 1)
if len(host_parts) == 1:
return hostname_regex.match(string) is not None
else:
host, port = host_parts
valid_hostname = hostname_regex.match(host) is not None
try:
port_num = int(port)
valid_port = (
port == str(port_num) # exclude things like '08090' or ' 8090'
and 1 <= port_num < 65536
except ValueError:
valid_port = False
return valid_hostname and valid_port | 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 clean_code(self):
code = self.cleaned_data['code']
username = code.user.get_username()
user = authenticate(self.request, **{
get_user_model().USERNAME_FIELD: username,
'code': code.code,
})
if not user:
raise forms.ValidationError(
self.error_messages['invalid_code'],
code='invalid_code',
)
self.cleaned_data['user'] = user
return 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_dmcrypt(self):
result = encryption.create_dmcrypt_key()
assert len(base64.b64decode(result)) == 128 | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def _websocket_mask_python(mask, data):
"""Websocket masking function.
`mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
Returns a `bytes` object of the same length as `data` with the mask applied
as specified in section 5.3 of RFC 6455.
This pure-python implementation may be replaced by an optimized version when available.
"""
mask = array.array("B", mask)
unmasked = array.array("B", data)
for i in xrange(len(data)):
unmasked[i] = unmasked[i] ^ mask[i % 4]
if hasattr(unmasked, 'tobytes'):
# tostring was deprecated in py32. It hasn't been removed,
# but since we turn on deprecation warnings in our tests
# we need to use the right one.
return unmasked.tobytes()
else:
return unmasked.tostring() | 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 getaddrspec(self):
"""Parse an RFC 2822 addr-spec."""
aslist = []
self.gotonext()
while self.pos < len(self.field):
preserve_ws = True
if self.field[self.pos] == '.':
if aslist and not aslist[-1].strip():
aslist.pop()
aslist.append('.')
self.pos += 1
preserve_ws = False
elif self.field[self.pos] == '"':
aslist.append('"%s"' % quote(self.getquote()))
elif self.field[self.pos] in self.atomends:
if aslist and not aslist[-1].strip():
aslist.pop()
break
else:
aslist.append(self.getatom())
ws = self.gotonext()
if preserve_ws and ws:
aslist.append(ws)
if self.pos >= len(self.field) or self.field[self.pos] != '@':
return EMPTYSTRING.join(aslist)
aslist.append('@')
self.pos += 1
self.gotonext()
domain = self.getdomain()
if not domain:
# Invalid domain, return an empty address instead of returning a
# local part to denote failed parsing.
return EMPTYSTRING
return EMPTYSTRING.join(aslist) + domain | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def test_http11_generator(self):
body = string.ascii_letters
to_send = "GET / HTTP/1.1\r\nContent-Length: %s\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")
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
expected = b""
for chunk in chunks(body, 10):
expected += tobytes(
"%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk)
)
expected += b"0\r\n\r\n"
self.assertEqual(response_body, expected)
# connection is always closed at the end of a chunked response
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 _glob_to_re(glob: str, word_boundary: bool) -> Pattern:
"""Generates regex for a given glob.
Args:
glob
word_boundary: Whether to match against word boundaries or entire string.
"""
if IS_GLOB.search(glob):
r = re.escape(glob)
r = r.replace(r"\*", ".*?")
r = r.replace(r"\?", ".")
# handle [abc], [a-z] and [!a-z] style ranges.
r = GLOB_REGEX.sub(
lambda x: (
"[%s%s]" % (x.group(1) and "^" or "", x.group(2).replace(r"\\\-", "-"))
),
r,
)
if word_boundary:
r = _re_word_boundary(r)
return re.compile(r, flags=re.IGNORECASE)
else:
r = "^" + r + "$"
return re.compile(r, flags=re.IGNORECASE)
elif word_boundary:
r = re.escape(glob)
r = _re_word_boundary(r)
return re.compile(r, flags=re.IGNORECASE)
else:
r = "^" + re.escape(glob) + "$"
return re.compile(r, flags=re.IGNORECASE) | 0 | 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 | vulnerable |
def testInvalidGroupSize(self, collective_op, device, communication):
dev0 = '/device:%s:0' % device
group_size = -2
group_key = 100
instance_key = 100
in_tensor = constant_op.constant([1.])
with self.assertRaises(errors.InvalidArgumentError):
with ops.device(dev0):
collective_op(
in_tensor,
group_size,
group_key,
instance_key,
communication_hint=communication) | 1 | Python | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | safe |
def __init__(self, hs: "HomeServer"):
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self.clock = hs.get_clock()
self._instance_name = hs.get_instance_name()
# These are safe to load in monolith mode, but will explode if we try
# and use them. However we have guards before we use them to ensure that
# we don't route to ourselves, and in monolith mode that will always be
# the case.
self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
self.edu_handlers = (
{}
) # type: Dict[str, Callable[[str, dict], Awaitable[None]]]
self.query_handlers = {} # type: Dict[str, Callable[[dict], Awaitable[None]]]
# Map from type to instance name that we should route EDU handling to.
self._edu_type_to_instance = {} # type: Dict[str, str] | 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 testRuntimeError(self,
inputs,
exception=errors.InvalidArgumentError,
message=None): | 0 | Python | CWE-824 | Access of Uninitialized Pointer | The program accesses or uses a pointer that has not been initialized. | https://cwe.mitre.org/data/definitions/824.html | vulnerable |
def test_render_idn(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
conditional_escape(w.render('test', 'http://example-äüö.com')),
'<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>'
) | 0 | 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 | vulnerable |
def setup_logging():
"""Configure the python logging appropriately for the tests.
(Logs will end up in _trial_temp.)
"""
root_logger = logging.getLogger()
log_format = "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s" " - %(message)s"
handler = ToTwistedHandler()
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
log_level = os.environ.get("SYDENT_TEST_LOG_LEVEL", "ERROR")
root_logger.setLevel(log_level) | 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 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
o_fd, outfile = tempfile.mkstemp(text=False)
o = os.fdopen(o_fd)
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 | 1 | 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 | safe |
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
if not out_path.startswith(os.path.sep):
out_path = os.path.join(os.path.sep, out_path)
normpath = os.path.normpath(out_path)
out_path = os.path.join(self.chroot, normpath[1:])
vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % 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 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 test_admin_reset(self):
"If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override."
response = self.client.post('/admin_password_reset/',
{'email': '[email protected]'},
HTTP_HOST='adminsite.com'
)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertTrue("http://adminsite.com" in mail.outbox[0].body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) | 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_open_with_filename(self):
tmpname = mktemp('', 'mmap')
fp = memmap(tmpname, dtype=self.dtype, mode='w+',
shape=self.shape)
fp[:] = self.data[:]
del fp
os.unlink(tmpname) | 0 | 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 | vulnerable |
def sanitize_content_filename(filename):
# type: (str) -> str
"""
Sanitize the "filename" value from a Content-Disposition header.
"""
return os.path.basename(filename) | 1 | 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 | safe |
def testSpoofedHeadersDropped(self):
data = b"""\
GET /foobar HTTP/8.4
x-auth_user: bob
content-length: 7
Hello.
"""
self.feed(data)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.headers, {"CONTENT_LENGTH": "7",}) | 0 | 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 | vulnerable |
def testInputPreprocessExampleWithCodeInjection(self):
input_examples_str = 'inputs=os.system("echo hacked")'
with self.assertRaisesRegex(RuntimeError, 'not a valid python literal.'):
saved_model_cli.preprocess_input_examples_arg_string(input_examples_str) | 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 test_logout_get(self):
login_code = LoginCode.objects.create(user=self.user)
self.client.login(username=self.user.username, code=login_code.code)
response = self.client.post('/accounts/logout/?next=/accounts/login/')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '/accounts/login/')
self.assertTrue(response.wsgi_request.user.is_anonymous) | 1 | 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 | safe |
void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride,
int pad_width, int pad_height, int filter_width,
int filter_height, float* output_data,
const Dims<4>& output_dims) {
AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height,
filter_width, filter_height, output_data, output_dims);
} | 0 | Python | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
def test_nested_nodes(self) -> None:
"""A body with some nested nodes. Tests that we iterate over children
in the right order (and don't reverse the order of the text)."""
html = b"""
<a href="somewhere">Welcome <b>the bold <u>and underlined text <svg>
with a cheeky SVG</svg></u> and <strong>some</strong> tail text</b></a>
"""
tree = decode_body(html, "http://example.com/test.html")
og = parse_html_to_open_graph(tree)
self.assertEqual(
og,
{
"og:title": None,
"og:description": "Welcome\n\nthe bold\n\nand underlined text\n\nand\n\nsome\n\ntail text",
},
) | 1 | Python | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | safe |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]:
ret = []
# the type of the calldata
base_args_t = TupleType([arg.typ for arg in sig.base_args])
# tuple with the abi_encoded args
if sig.is_init_func:
base_args_ofst = IRnode(0, location=DATA, typ=base_args_t, encoding=Encoding.ABI)
else:
base_args_ofst = IRnode(4, location=CALLDATA, typ=base_args_t, encoding=Encoding.ABI)
for i, arg in enumerate(sig.base_args):
arg_ir = get_element_ptr(base_args_ofst, i)
if _should_decode(arg.typ):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
dst = IRnode(p, typ=arg.typ, location=MEMORY)
copy_arg = make_setter(dst, arg_ir)
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
# leave it in place
context.vars[arg.name] = VariableRecord(
name=arg.name,
pos=arg_ir,
typ=arg.typ,
mutable=False,
location=arg_ir.location,
encoding=Encoding.ABI,
)
return ret | 0 | 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 | vulnerable |
def is_whitelisted(self, method):
fn = getattr(self, method, None)
if not fn:
raise NotFound("Method {0} not found".format(method))
elif not getattr(fn, "whitelisted", False):
raise Forbidden("Method {0} not whitelisted".format(method)) | 0 | 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 | 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 | 0 | 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 | vulnerable |
async def on_PUT(self, origin, content, query, room_id):
content = await self.handler.on_exchange_third_party_invite_request(
room_id, content
)
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 testBoostedTreesCalculateBestFeatureSplitSecurity2(self):
with self.assertRaises((errors.InvalidArgumentError, ValueError)):
gen_boosted_trees_ops.boosted_trees_calculate_best_feature_split(
node_id_range=[0, 8],
stats_summary=[[[[1.0], [2.0], [3.0]]]],
l1=[0.5],
l2=[0.5],
tree_complexity=[0.1],
min_node_weight=[1.0],
logits_dimension=8) | 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 clear():
self.vars.clear()
self.errors.clear()
for field in self.table:
self.vars[field.name] = field.default | 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 save(self, text):
self._create_dirs()
with open(self._path, "w") as fd:
fd.write(text) | 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 get_info(path: str, root: pathlib.Path) -> typing.Tuple[
pathlib.Path,
dict]: | 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 field_names(ctx, rd, field):
'''
Get a list of all names for the specified field
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(sorted(db.all_field_names(field), key=numeric_sort_key)) | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def testBoostedTreesSparseCalculateBestFeatureSplitSecurity(self):
node_id_range = []
stats_summary_indices = [[]]
stats_summary_values = [1.0]
stats_summary_shape = [1, 1, 1, 1]
l1 = [1.0]
l2 = [1.0]
tree_complexity = [0.5]
min_node_weight = [1.0]
logits_dimension = 3
split_type = 'inequality'
with self.assertRaises((errors.InvalidArgumentError, ValueError)):
gen_boosted_trees_ops.boosted_trees_sparse_calculate_best_feature_split(
node_id_range=node_id_range,
stats_summary_indices=stats_summary_indices,
stats_summary_values=stats_summary_values,
stats_summary_shape=stats_summary_shape,
l1=l1,
l2=l2,
tree_complexity=tree_complexity,
min_node_weight=min_node_weight,
logits_dimension=logits_dimension,
split_type=split_type) | 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 create_book_on_upload(modif_date, meta):
title = meta.title
authr = meta.author
sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)
title_dir = helper.get_valid_filename(title, chars=96)
author_dir = helper.get_valid_filename(db_author.name, chars=96)
# combine path and normalize path from windows systems
path = os.path.join(author_dir, title_dir).replace('\\', '/')
# Calibre adds books with utc as timezone
db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1),
'1', datetime.utcnow(), path, meta.cover, db_author, [], "")
modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session,
'author')
# Add series_index to book
modif_date |= edit_book_series_index(meta.series_id, db_book)
# add languages
invalid=[]
modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid)
if invalid:
for l in invalid:
flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning")
# handle tags
modif_date |= edit_book_tags(meta.tags, db_book)
# handle publisher
modif_date |= edit_book_publisher(meta.publisher, db_book)
# handle series
modif_date |= edit_book_series(meta.series, db_book)
# Add file to book
file_size = os.path.getsize(meta.file_path)
db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir)
db_book.data.append(db_data)
calibre_db.session.add(db_book)
# flush content, get db_book.id available
calibre_db.session.flush()
return db_book, input_authors, title_dir, renamed_authors | 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 check_send_to_kindle_with_converter(formats):
bookformats = list()
if 'EPUB' in formats and 'MOBI' not in formats:
bookformats.append({'format': 'Mobi',
'convert': 1,
'text': _('Convert %(orig)s to %(format)s and send to Kindle',
orig='Epub',
format='Mobi')})
if 'AZW3' in formats and not 'MOBI' in formats:
bookformats.append({'format': 'Mobi',
'convert': 2,
'text': _('Convert %(orig)s to %(format)s and send to Kindle',
orig='Azw3',
format='Mobi')})
return bookformats | 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 get_vars_next(self):
next = current.request.vars._next
host = current.request.env.http_host
if isinstance(next, (list, tuple)):
next = next[0]
if next and self.settings.prevent_open_redirect_attacks:
return self.prevent_open_redirect(next, host)
return next or None | 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 render_hot_books(page, order):
if current_user.check_visibility(constants.SIDEBAR_HOT):
if order[1] not in ['hotasc', 'hotdesc']:
# Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+
#if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or
# order[0][0].compare(func.count(ub.Downloads.book_id).asc())):
order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc'
if current_user.show_detail_random():
random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \
.order_by(func.random()).limit(config.config_random_books)
else:
random = false()
off = int(int(config.config_books_per_page) * (page - 1))
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\
.order_by(*order[0]).group_by(ub.Downloads.book_id)
hot_books = all_books.offset(off).limit(config.config_books_per_page)
entries = list()
for book in hot_books:
downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter(
db.Books.id == book.Downloads.book_id).first()
if downloadBook:
entries.append(downloadBook)
else:
ub.delete_download(book.Downloads.book_id)
numBooks = entries.__len__()
pagination = Pagination(page, config.config_books_per_page, numBooks)
return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1])
else:
abort(404) | 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 home_get_dat():
d = db.sentences_stats('get_data')
n = db.sentences_stats('all_networks')
rows = db.sentences_stats('get_clicks')
c = rows[0][0]
rows = db.sentences_stats('get_sessions')
s = rows[0][0]
vId = ('online', )
rows = db.sentences_stats('get_online', vId)
o = rows[0][0]
return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o}); | 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_mixed(self):
self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 2) | 0 | 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 | vulnerable |
def testInputPreProcessFormats(self):
input_str = 'input1=/path/file.txt[ab3];input2=file2'
input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'
input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)
input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(
input_expr_str, safe=False)
self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))
self.assertTrue(input_dict['input2'] == ('file2', None))
print(input_expr_dict['input3'])
self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))
self.assertAllClose(input_expr_dict['input4'], [4, 5])
self.assertTrue(len(input_dict) == 2)
self.assertTrue(len(input_expr_dict) == 2) | 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 test_ignores(self):
tree = self.parse(ignores)
self.assertEqual([ti.lineno for ti in tree.type_ignores], [2, 5])
tree = self.classic_parse(ignores)
self.assertEqual(tree.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 __init__(
self, cache, safe=safename | 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_all_to_all_group_assignment_wrong_shape(self):
with self.assertRaisesRegex(
ValueError, "group_assignment must have rank 2"):
tpu_ops.all_to_all(
x=[0.0, 0.1652, 0.6543],
group_assignment=[1, -1],
concat_dimension=0,
split_dimension=0,
split_count=2) | 1 | Python | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
def download_check_files(self, filelist):
# only admins and allowed users may download
if not cherrypy.session['admin']:
uo = self.useroptions.forUser(self.getUserId())
if not uo.getOptionValue('media.may_download'):
return 'not_permitted'
# make sure nobody tries to escape from basedir
for f in filelist:
if '/../' in f:
return 'invalid_file'
# make sure all files are smaller than maximum download size
size_limit = cherry.config['media.maximum_download_size']
try:
if self.model.file_size_within_limit(filelist, size_limit):
return 'ok'
else:
return 'too_big'
except OSError as e: # use OSError for python2 compatibility
return str(e) | 0 | 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 | vulnerable |
def getdomain(self):
"""Get the complete domain name from an address."""
sdlist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos += 1
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomment())
elif self.field[self.pos] == '[':
sdlist.append(self.getdomainliteral())
elif self.field[self.pos] == '.':
self.pos += 1
sdlist.append('.')
elif self.field[self.pos] == '@':
# bpo-34155: Don't parse domains with two `@` like
# `[email protected]@important.com`.
return EMPTYSTRING
elif self.field[self.pos] in self.atomends:
break
else:
sdlist.append(self.getatom())
return EMPTYSTRING.join(sdlist) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def _get_insert_token(token):
"""Returns either a whitespace or the line breaks from token."""
# See issue484 why line breaks should be preserved.
m = re.search(r'((\r\n|\r|\n)+) *$', token.value)
if m is not None:
return sql.Token(T.Whitespace.Newline, m.groups()[0])
else:
return sql.Token(T.Whitespace, ' ') | 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_class_from_xml_string(target_class, xml_string):
"""Creates an instance of the target class from a string.
:param target_class: The class which will be instantiated and populated
with the contents of the XML. This class must have a c_tag and a
c_namespace class variable.
:param xml_string: A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
:return: An instance of the target class with members assigned according to
the contents of the XML - or None if the root XML tag and namespace did
not match those of the target class.
"""
if not isinstance(xml_string, six.binary_type):
xml_string = xml_string.encode('utf-8')
tree = ElementTree.fromstring(xml_string)
return create_class_from_element_tree(target_class, 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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
federation_http_client=None, homeserver_to_use=GenericWorkerServer
)
return hs | 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 authenticate(self, username, password):
child = None
try:
child = pexpect.spawn('/bin/sh', ['-c', '/bin/su -c "/bin/echo SUCCESS" - %s' % username], timeout=5)
child.expect('.*:')
child.sendline(password)
result = child.expect(['su: .*', 'SUCCESS'])
except Exception as err:
if child and child.isalive():
child.close()
logging.error('Error checking password: %s', err)
return False
if result == 0:
return False
else:
return True | 0 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
def process_response(self, request, response, spider):
if (
request.meta.get('dont_redirect', False)
or response.status in getattr(spider, 'handle_httpstatus_list', [])
or response.status in request.meta.get('handle_httpstatus_list', [])
or request.meta.get('handle_httpstatus_all', False)
):
return response
allowed_status = (301, 302, 303, 307, 308)
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['Location'])
if response.headers['Location'].startswith(b'//'):
request_scheme = urlparse(request.url).scheme
location = request_scheme + '://' + location.lstrip('/')
redirected_url = urljoin(request.url, location)
if response.status in (301, 307, 308) or request.method == 'HEAD':
redirected = request.replace(url=redirected_url)
return self._redirect(redirected, request, spider, response.status)
redirected = self._redirect_request_using_get(request, redirected_url)
return self._redirect(redirected, request, spider, response.status) | 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 parse_html_description(tree: "etree.Element") -> Optional[str]:
"""
Calculate a text description based on an HTML document.
Grabs any text nodes which are inside the <body/> tag, unless they are within
an HTML5 semantic markup tag (<header/>, <nav/>, <aside/>, <footer/>), or
if they are within a <script/>, <svg/> or <style/> tag, or if they are within
a tag whose content is usually only shown to old browsers
(<iframe/>, <video/>, <canvas/>, <picture/>).
This is a very very very coarse approximation to a plain text render of the page.
Args:
tree: The parsed HTML document.
Returns:
The plain text description, or None if one cannot be generated.
"""
# We don't just use XPATH here as that is slow on some machines.
from lxml import etree
TAGS_TO_REMOVE = (
"header",
"nav",
"aside",
"footer",
"script",
"noscript",
"style",
"svg",
"iframe",
"video",
"canvas",
"img",
"picture",
etree.Comment,
)
# Split all the text nodes into paragraphs (by splitting on new
# lines)
text_nodes = (
re.sub(r"\s+", "\n", el).strip()
for el in _iterate_over_text(tree.find("body"), *TAGS_TO_REMOVE)
)
return summarize_paragraphs(text_nodes) | 0 | Python | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | vulnerable |
def delete_book_gdrive(book, book_format):
error = None
if book_format:
name = ''
for entry in book.data:
if entry.format.upper() == book_format:
name = entry.name + '.' + book_format
gFile = gd.getFileFromEbooksFolder(book.path, name)
else:
gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), book.path.split('/')[1])
if gFile:
gd.deleteDatabaseEntry(gFile['id'])
gFile.Trash()
else:
error = _(u'Book path %(path)s not found on Google Drive', path=book.path) # file not found
return error is None, error | 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 test_sanitize_arg(self):
self.assertEqual(codecov.sanitize_arg('', '& echo test > vuln1.txt'), ' echo test > vuln1.txt') | 1 | Python | CWE-88 | Improper Neutralization of Argument Delimiters in a Command ('Argument Injection') | The software constructs a string for a command to executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string. | https://cwe.mitre.org/data/definitions/88.html | safe |
def fixed_fetch(
url,
payload=None,
method="GET",
headers={},
allow_truncated=False,
follow_redirects=True,
deadline=None, | 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 logout():
if current_user is not None and current_user.is_authenticated:
ub.delete_user_session(current_user.id, flask_session.get('_id',""))
logout_user()
if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):
logout_oauth_user()
log.debug(u"User logged out")
return redirect(url_for('web.login')) | 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 check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):
if not config_calibre_dir:
return False, False
dbpath = os.path.join(config_calibre_dir, "metadata.db")
if not os.path.exists(dbpath):
return False, False
try:
check_engine = create_engine('sqlite://',
echo=False,
isolation_level="SERIALIZABLE",
connect_args={'check_same_thread': False},
poolclass=StaticPool)
with check_engine.begin() as connection:
connection.execute(text("attach database '{}' as calibre;".format(dbpath)))
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path)))
local_session = scoped_session(sessionmaker())
local_session.configure(bind=connection)
database_uuid = local_session().query(Library_Id).one_or_none()
# local_session.dispose()
check_engine.connect()
db_change = config_calibre_uuid != database_uuid.uuid
except Exception:
return False, False
return True, db_change | 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 test_parse_content_disposition(
content_disposition,
default_filename,
expected | 1 | 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 | safe |
def test_valid(self, args):
qutebrowser._validate_untrusted_args(args) | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def read_requirements(name):
project_root = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(project_root, name), 'rb') as f:
# remove whitespace and comments
g = (line.decode('utf-8').lstrip().split('#', 1)[0].rstrip() for line in f)
return [l for l in g if l] | 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 check_xsrf_cookie(self):
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery.
The ``_xsrf`` value may be set as either a form field named ``_xsrf``
or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Prior to release 1.1.1, this check was ignored if the HTTP header
``X-Requested-With: XMLHTTPRequest`` was present. This exception
has been shown to be insecure and has been removed. For more
information please see
http://www.djangoproject.com/weblog/2011/feb/08/security/
http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
"""
token = (self.get_argument("_xsrf", None) or
self.request.headers.get("X-Xsrftoken") or
self.request.headers.get("X-Csrftoken"))
if not token:
raise HTTPError(403, "'_xsrf' argument missing from POST")
_, token, _ = self._decode_xsrf_token(token)
_, expected_token, _ = self._get_raw_xsrf_token()
if not _time_independent_equals(utf8(token), utf8(expected_token)):
raise HTTPError(403, "XSRF cookie does not match POST argument") | 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 main() -> None:
formatter = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(formatter_class=formatter)
parser.add_argument("resource_group")
parser.add_argument("storage_account")
parser.add_argument("admins", type=UUID, nargs="*")
args = parser.parse_args()
client = get_client_from_cli_profile(StorageManagementClient)
storage_keys = client.storage_accounts.list_keys(
args.resource_group, args.storage_account
)
table_service = TableService(
account_name=args.storage_account, account_key=storage_keys.keys[0].value
)
update_admins(table_service, args.resource_group, args.admins) | 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 __init__(self, hs):
super().__init__(hs)
self.hs = hs
self.is_mine_id = hs.is_mine_id
self.http_client = hs.get_simple_http_client()
self._presence_enabled = hs.config.use_presence
# The number of ongoing syncs on this process, by user id.
# Empty if _presence_enabled is false.
self._user_to_num_current_syncs = {} # type: Dict[str, int]
self.notifier = hs.get_notifier()
self.instance_id = hs.get_instance_id()
# user_id -> last_sync_ms. Lists the users that have stopped syncing
# but we haven't notified the master of that yet
self.users_going_offline = {}
self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)
self._set_state_client = ReplicationPresenceSetState.make_client(hs)
self._send_stop_syncing_loop = self.clock.looping_call(
self.send_stop_syncing, UPDATE_SYNCING_USERS_MS
)
hs.get_reactor().addSystemEventTrigger(
"before",
"shutdown",
run_as_background_process,
"generic_presence.on_shutdown",
self._on_shutdown,
) | 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 get_digest(value):
"""Return a hashlib digest algorithm from a string."""
if isinstance(value, str):
value = value.lower()
if value not in ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'):
raise ValueError("Invalid digest algorithm: %s" % value)
value = getattr(hashlib, value)
return value | 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 test_get_form_without_help_text_escaping(self):
response = self.client.get('/contact-us/')
# HTML in help text should not be escaped
self.assertContains(response, "<em>please</em> be polite") | 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_project_quotas_defaults_withclass(self):
self._stub_class()
self._stub_project()
self.context.quota_class = 'test_class'
result = quota.get_project_quotas(self.context, 'admin')
self.assertEqual(result, dict(
instances=5,
cores=10,
ram=25 * 1024,
volumes=5,
gigabytes=500,
floating_ips=5,
security_groups=10,
security_group_rules=20,
metadata_items=64,
injected_files=2,
injected_file_content_bytes=5 * 1024,
)) | 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 update(request, pk):
notification = get_object_or_404(TopicNotification, pk=pk, user=request.user)
form = NotificationForm(data=request.POST, instance=notification)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get(
'next', notification.topic.get_absolute_url())) | 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 render_html(request):
"""
render html with url
:param request:
:return:
"""
if request.method == 'GET':
url = request.GET.get('url')
url = unquote(base64.b64decode(url).decode('utf-8'))
js = request.GET.get('js', 0)
script = request.GET.get('script')
try:
response = requests.get(url, timeout=5)
response.encoding = response.apparent_encoding
html = process_html(response.text)
return HttpResponse(html)
except Exception as e:
return JsonResponse({'message': e.args}, status=500) | 0 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
def test_delete_not_allowed(self):
# Verify we can get the image data
req = webob.Request.blank("/images/%s" % UUID2)
req.method = 'GET'
req.headers['X-Auth-Token'] = 'user:tenant:'
res = req.get_response(self.api)
self.assertEqual(res.status_int, 200)
self.assertEqual(len(res.body), 19)
# Verify we cannot delete the image
req.method = 'DELETE'
res = req.get_response(self.api)
self.assertEqual(res.status_int, 403)
# Verify the image data is still there
req.method = 'GET'
res = req.get_response(self.api)
self.assertEqual(res.status_int, 200)
self.assertEqual(len(res.body), 19) | 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_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) | 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 |
def set_user_password(self, context, user_id, user):
user_ref = self.update_user(context, user_id, user)
try:
for token_id in self.token_api.list_tokens(context, user_id):
self.token_api.delete_token(context, token_id)
except exception.NotImplemented:
# The password has been changed but tokens remain valid for
# backends that can't list tokens for users
LOG.warning('Password changed for %s, but existing tokens remain '
'valid' % user_id)
return user_ref | 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 |
def test_login_inactive_user(self):
self.user.is_active = False
self.user.save()
login_code = LoginCode.objects.create(user=self.user, code='foobar')
response = self.client.post('/accounts-rest/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(), {
'code': ['Unable to log in with provided 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 parse_yaml_query(yaml_content):
"""Parses the given YAML string to attempt to extract a query.
Args:
yaml_content: A string containing YAML content.
Returns:
On success, the processed MLQuery object.
"""
logger.debug("Attempting to parse YAML content:\n%s" % yaml_content)
return parse_query(yaml.load(yaml_content)) | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def _remove_javascript_link(self, link):
# links like "j a v a s c r i p t:" might be interpreted in IE
new = _substitute_whitespace('', unquote_plus(link))
if _is_javascript_scheme(new):
# FIXME: should this be None to delete?
return ''
return link | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.