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_uses_xdg_config_home(self, apiver):
with WindowsSafeTempDir() as d:
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
XDG_CONFIG_HOME_ENV_VAR: d,
}
)
if apiver in ['v0', 'v1']:
expected_path = os.path.abspath(os.path.join(self.home, '.b2_account_info'))
else:
assert os.path.exists(os.path.join(d, 'b2'))
expected_path = os.path.abspath(os.path.join(d, 'b2', 'account_info'))
actual_path = os.path.abspath(account_info.filename)
assert expected_path == actual_path | 0 | Python | CWE-367 | Time-of-check Time-of-use (TOCTOU) Race Condition | The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state. | https://cwe.mitre.org/data/definitions/367.html | vulnerable |
def test_token_expiry_maintained(self):
foo_client = self.get_client(self.user_foo)
orig_token = foo_client.service_catalog.catalog['token']
time.sleep(1.01)
reauthenticated_token = foo_client.tokens.authenticate(
token=foo_client.auth_token)
self.assertEquals(orig_token['expires'],
reauthenticated_token.expires) | 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_student_progress_url(request, course_id):
"""
Get the progress url of a student.
Limited to staff access.
Takes query parameter unique_student_identifier and if the student exists
returns e.g. {
'progress_url': '/../...'
}
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
user = get_student_from_identifier(request.POST.get('unique_student_identifier'))
progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id})
response_payload = {
'course_id': course_id.to_deprecated_string(),
'progress_url': progress_url,
}
return JsonResponse(response_payload) | 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 _default_logfile(exe_name):
'''
Retrieve the logfile name
'''
if salt.utils.is_windows():
logfile_tmp = tempfile.NamedTemporaryFile(dir=os.environ['TMP'],
prefix=exe_name,
suffix='.log',
delete=False)
logfile = logfile_tmp.name
logfile_tmp.close()
else:
logfile = salt.utils.path_join(
'/var/log',
'{0}.log'.format(exe_name)
)
return logfile | 1 | Python | CWE-19 | Data Processing Errors | Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information. | https://cwe.mitre.org/data/definitions/19.html | safe |
def task_status(request, task_id):
"""
get task status info
:param request: request object
:param task_id: task id
:return:
"""
if request.method == 'GET':
result = []
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
jobs = DjangoJob.objects.filter(name=job_id)
logger.debug('jobs from djangojob %s', jobs)
# if job does not exist, for date mode exceed time
if not jobs: continue
job = DjangoJob.objects.get(name=job_id)
executions = serialize('json', DjangoJobExecution.objects.filter(job=job))
result.append({
'client': model_to_dict(client),
'next': job.next_run_time,
'executions': json.loads(executions)
})
return JsonResponse({'data': result}) | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):
"""
Test update forum role membership.
Get unique_student_identifier, rolename and action and update forum role.
"""
url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(
url,
{
'unique_student_identifier': identifier,
'rolename': rolename,
'action': action,
}
)
# Status code should be 200.
self.assertEqual(response.status_code, 200)
user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
if action == 'allow':
self.assertIn(rolename, user_roles)
elif action == 'revoke':
self.assertNotIn(rolename, user_roles) | 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 process_command_line(self, argv, verbose=1):
usage = "usage: %s start | stop | restart | status | debug " \
"[--pidfile=...] " \
"(run as non-daemon)" % os.path.basename(argv[0])
if len(argv) < 2:
print usage
raise SystemExit
else:
operation = argv[1]
if len(argv) > 2 and argv[2].startswith('--pidfile=') and \
len(argv[2]) > len('--pidfile='):
self.pidfile = argv[2][len('--pidfile='):]
pid = self.get_pid()
if operation == 'status':
if self.is_process_running():
print "Server process %s is running." % pid
else:
print "Server is not running."
elif operation == 'start':
if self.is_process_running():
print "Server process %s is already running." % pid
raise SystemExit
else:
if verbose:
print "Starting server process."
self.daemon_start()
elif operation == 'stop':
if self.is_process_running():
self.daemon_stop()
if verbose:
print "Server process %s stopped." % pid
else:
print "Server process %s is not running." % pid
raise SystemExit
elif operation == 'restart':
self.daemon_stop()
if verbose:
print "Restarting server process."
self.daemon_start()
elif operation == 'debug':
self.daemon_start(0)
else:
print "Unknown operation:", operation
raise SystemExit | 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 subscribe_for_tags(request):
"""process subscription of users by tags"""
#todo - use special separator to split tags
tag_names = request.REQUEST.get('tags','').strip().split()
pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
if request.user.is_authenticated():
if request.method == 'POST':
if 'ok' in request.POST:
request.user.mark_tags(
pure_tag_names,
wildcards,
reason = 'good',
action = 'add'
)
request.user.message_set.create(
message = _('Your tag subscription was saved, thanks!')
)
else:
message = _(
'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
) % {'url': request.path + '?tags=' + request.REQUEST['tags']}
request.user.message_set.create(message = message)
return HttpResponseRedirect(reverse('index'))
else:
data = {'tags': tag_names}
return render(request, 'subscribe_for_tags.html', data)
else:
all_tag_names = pure_tag_names + wildcards
message = _('Please sign in to subscribe for: %(tags)s') \
% {'tags': ', '.join(all_tag_names)}
request.user.message_set.create(message = message)
request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
return HttpResponseRedirect(url_utils.get_login_url()) | 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 get(self, key):
"""
Gets the object specified by key. It will also unpickle the object
before returning if it is pickled in memcache.
:param key: key
:returns: value of the key in memcache
"""
key = md5hash(key)
value = None
for (server, fp, sock) in self._get_conns(key):
try:
sock.sendall('get %s\r\n' % key)
line = fp.readline().strip().split()
while line[0].upper() != 'END':
if line[0].upper() == 'VALUE' and line[1] == key:
size = int(line[3])
value = fp.read(size)
if int(line[2]) & PICKLE_FLAG:
value = pickle.loads(value)
fp.readline()
line = fp.readline().strip().split()
self._return_conn(server, fp, sock)
return value
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 get_server_key(self):
"""
Retrieve the server's public key.
:return: rsa public key
:rtype: str
"""
return self.server.GET('/pulp/static/rsa_pub.key', ignore_prefix=True) | 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 get_vars_next(self):
next = current.request.vars._next
if isinstance(next, (list, tuple)):
next = next[0]
if next and self.settings.prevent_open_redirect_attacks:
return prevent_open_redirect(next)
return next or None | 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 attemptRequestWithMaliciousMethod(self, method):
"""
Attempt a request with the provided method.
@param method: see L{MethodInjectionTestsMixin}
"""
uri = b'http://twisted.invalid'
client.getPage(uri, method=method) | 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 _cbrt(x):
return math.pow(x, 1.0/3) | 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 get_proxied_blacklisted_http_client(self) -> SimpleHttpClient:
"""
An HTTP client that uses configured HTTP(S) proxies and blacklists IPs
based on the IP range blacklist.
"""
return SimpleHttpClient(
self,
ip_blacklist=self.config.ip_range_blacklist,
http_proxy=os.getenvb(b"http_proxy"),
https_proxy=os.getenvb(b"HTTPS_PROXY"),
) | 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 harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
`self.iterations` is 30000, this method should run password through
another 10000 iterations of PBKDF2. Similar approaches should exist
for any hasher that has a work factor. If not, this method should be
defined as a no-op to silence the warning.
"""
warnings.warn('subclasses of BasePasswordHasher should provide a harden_runtime() method') | 1 | 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 | safe |
def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
self.debug_log("running triggers")
for notifier in os.listdir(self.data):
self.debug_log("running %s" % notifier)
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = os.path.join(self.data, notifier)
self.async_run([npath] + args) | 1 | 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 | safe |
def _get_object_element(dataset, seq_no, rel_path, download_link):
"""If rel_path and download_link are not None, we are called from scope.
Otherwise we are called from ID and need to run SQL query to fetch these attrs."""
if rel_path is None:
query = "SELECT rel_path, download_link FROM " + \
dataset + \
" WHERE sequence_no = %s"
cnx = mysql.connector.connect(user=DB_USER,
password=DB_PASSWORD,
host=DB_HOST,
database=DB_DBNAME,
port=DB_PORT)
cursor = cnx.cursor()
cursor.execute(query, (seq_no,))
row = cursor.fetchone()
if not row:
return None
rel_path, download_link = row[0], row[1]
if LOCAL_OBJ_URI:
src_uri = 'file://' + os.path.join(DATAROOT, dataset, rel_path)
else:
src_uri = url_for('.get_object_src_http', dataset=dataset, rel_path=rel_path)
return '<object id={} src={} hyperfind.external-link={} />' \
.format(
quoteattr(url_for('.get_object_id', dataset=dataset, seq_no=seq_no)),
quoteattr(src_uri),
quoteattr(download_link)) | 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 delete_user_session(user_id, session_key):
try:
log.info("Deleted session_key : " + session_key)
session.query(User_Sessions).filter(User_Sessions.user_id==user_id,
User_Sessions.session_key==session_key).delete()
session.commit()
except (exc.OperationalError, exc.InvalidRequestError):
session.rollback()
log.exception(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 testBadInputSizes(self):
self._testBadInputSize(
tin=math_ops.cast(
constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),
error_regex="must be rank 4")
self._testBadInputSize(
tfilter=math_ops.cast(
constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),
error_regex="must be rank 4")
self._testBadInputSize(
min_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
error_regex="must be rank 0")
self._testBadInputSize(
max_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
error_regex="must be rank 0")
self._testBadInputSize(
min_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
error_regex="must be rank 0")
self._testBadInputSize(
max_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
error_regex="must be rank 0") | 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 makepasv(self):
"""Internal: Does the PASV or EPSV handshake -> (address, port)"""
if self.af == socket.AF_INET:
untrusted_host, port = parse227(self.sendcmd('PASV'))
if self.trust_server_pasv_ipv4_address:
host = untrusted_host
else:
host = self.sock.getpeername()[0]
else:
host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
return host, port | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def delete(self, req, image_id):
self._enforce(req, 'delete_image')
image = self._get_image(req.context, image_id)
if image['protected']:
msg = _("Unable to delete as image %(image_id)s is protected"
% locals())
raise webob.exc.HTTPForbidden(explanation=msg)
if image['location'] and CONF.delayed_delete:
status = 'pending_delete'
else:
status = 'deleted'
try:
self.db_api.image_update(req.context, image_id, {'status': status})
self.db_api.image_destroy(req.context, image_id)
if image['location']:
if CONF.delayed_delete:
self.store_api.schedule_delayed_delete_from_backend(
image['location'], id)
else:
self.store_api.safe_delete_from_backend(image['location'],
req.context, id)
except (exception.NotFound, exception.Forbidden):
msg = ("Failed to find image %(image_id)s to delete" % locals())
LOG.info(msg)
raise webob.exc.HTTPNotFound()
else:
self.notifier.info('image.delete', image) | 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 testRaggedCountSparseOutputBadSplitsEnd(self):
splits = [0, 5]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Splits must end with the number of values"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 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 snake_case(value: str) -> str:
return stringcase.snakecase(group_title(_sanitize(value))) | 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 setUp(self):
self.mock_federation_resource = MockHttpResource()
self.mock_http_client = Mock(spec=[])
self.mock_http_client.put_json = DeferredMockCallable()
hs = yield setup_test_homeserver(
self.addCleanup, http_client=self.mock_http_client, keyring=Mock(),
)
self.filtering = hs.get_filtering()
self.datastore = hs.get_datastore() | 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 check_is_symlink():
""" Check if intermediate dir is symlink. """
try:
return not os.path.islink(im_dir)
except OSError:
return False | 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 testRaggedCountSparseOutput(self):
splits = [0, 4, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
output_indices, output_values, output_shape = self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits, values=values, weights=weights, binary_output=False))
self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]],
output_indices)
self.assertAllEqual([7, 3, 5, 7, 6], output_values)
self.assertAllEqual([2, 11], output_shape) | 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 create_dmcrypt_key():
"""
Create the secret dm-crypt key used to decrypt a device.
"""
# get the customizable dmcrypt key size (in bits) from ceph.conf fallback
# to the default of 1024
dmcrypt_key_size = conf.ceph.get_safe(
'osd',
'osd_dmcrypt_key_size',
default=1024,
)
# The size of the key is defined in bits, so we must transform that
# value to bytes (dividing by 8) because we read in bytes, not bits
random_string = os.urandom(int(dmcrypt_key_size / 8))
key = base64.b64encode(random_string).decode('utf-8')
return key | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def test_get_students_features_cohorted(self, is_cohorted):
"""
Test that get_students_features includes cohort info when the course is
cohorted, and does not when the course is not cohorted.
"""
url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})
set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted)
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertEqual('cohort' in res_json['feature_names'], is_cohorted) | 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 move(request, topic_id):
topic = get_object_or_404(Topic, pk=topic_id)
form = CommentMoveForm(topic=topic, data=request.POST)
if form.is_valid():
comments = form.save()
for comment in comments:
comment_posted(comment=comment, mentions=None)
topic.decrease_comment_count()
post_comment_move(comment=comment, topic=topic)
else:
messages.error(request, render_form_errors(form))
return redirect(request.POST.get('next', 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 _check_group_whitelist(self, username, user_id, is_admin, access_token):
http_client = AsyncHTTPClient()
headers = _api_headers(access_token)
# Check if we are a member of each group in the whitelist
for group in map(url_escape, self.gitlab_group_whitelist):
url = "%s/groups/%s/members/%d" % (GITLAB_API, group, user_id)
req = HTTPRequest(url, method="GET", headers=headers)
resp = yield http_client.fetch(req, raise_error=False)
if resp.code == 200:
return True # user _is_ in group
return False | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def test_broken_chunked_encoding(self):
control_line = "20;\r\n" # 20 hex = 32 dec
s = "This string has 32 characters.\r\n"
to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n"
to_send += control_line + s
# garbage in input
to_send += "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n"
to_send += control_line + s
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)
# receiver caught garbage and turned it into a 400
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertEqual(
sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"]
)
self.assertEqual(headers["content-type"], "text/plain")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 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 test_reset_student_attempts_deletall(self):
""" Make sure no one can delete all students state on a problem. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
'delete_module': True,
})
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 _inject_admin_password_into_fs(admin_passwd, fs, execute=None):
"""Set the root password to admin_passwd
admin_password is a root password
fs is the path to the base of the filesystem into which to inject
the key.
This method modifies the instance filesystem directly,
and does not require a guest agent running in the instance.
"""
# The approach used here is to copy the password and shadow
# files from the instance filesystem to local files, make any
# necessary changes, and then copy them back.
admin_user = 'root'
fd, tmp_passwd = tempfile.mkstemp()
os.close(fd)
fd, tmp_shadow = tempfile.mkstemp()
os.close(fd)
utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,
run_as_root=True)
utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,
run_as_root=True)
_set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)
utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),
run_as_root=True)
os.unlink(tmp_passwd)
utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),
run_as_root=True)
os.unlink(tmp_shadow) | 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_create_catalog(self):
pardir = self.get_test_dir(erase=1)
cat = catalog.get_catalog(pardir,'c')
assert_(cat is not None)
cat.close()
remove_tree(pardir) | 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 _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval | 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 verify_password(plain_password, user_password):
if plain_password == user_password:
LOG.debug("password true")
return True
return False | 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 _handle_carbon_received(self, msg):
if msg['from'].bare == self.xmpp.boundjid.bare:
self.xmpp.event('carbon_received', msg) | 1 | 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 | safe |
def main():
_validate_untrusted_args(sys.argv)
parser = get_argparser()
argv = sys.argv[1:]
args = parser.parse_args(argv)
if args.json_args is not None:
args = _unpack_json_args(args)
earlyinit.early_init(args)
# We do this imports late as earlyinit needs to be run first (because of
# version checking and other early initialization)
from qutebrowser import app
return app.run(args) | 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 prevent_open_redirect(next, host):
# Prevent an attacker from adding an arbitrary url after the
# _next variable in the request.
if next:
parts = next.split('/')
if ':' not in parts[0] and parts[:2] != ['', '']:
return next
elif len(parts) > 2 and parts[0].endswith(':') and parts[1:3] == ['', host]:
return next
return 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 set_admins(self) -> None:
name = self.results["deploy"]["func-name"]["value"]
key = self.results["deploy"]["func-key"]["value"]
table_service = TableService(account_name=name, account_key=key)
if self.admins:
update_admins(table_service, self.application_name, self.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 test_property_from_data_array(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},)
ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty")
FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty")
from openapi_python_client.parser.properties import property_from_data
p = property_from_data(name=name, required=required, data=data)
FloatProperty.assert_called_once_with(name=f"{name}_item", required=True, default="0.0")
ListProperty.assert_called_once_with(
name=name, required=required, default=None, inner_property=FloatProperty.return_value
)
assert p == ListProperty.return_value | 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 from_yaml(self, content):
"""
Given some YAML data, returns a Python dictionary of the decoded data.
"""
if yaml is None:
raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.")
return yaml.safe_load(content) | 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_filelike_nocl_http10(self):
to_send = "GET /filelike_nocl HTTP/1.0\n\n"
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")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 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 recursive_fn2(n):
if n <= 1:
return 2
return recursive_fn1(n - 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 download_list():
if current_user.get_view_property('download', 'dir') == 'desc':
order = ub.User.name.desc()
order_no = 0
else:
order = ub.User.name.asc()
order_no = 1
if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\
.join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all()
charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \
.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \
.group_by(func.upper(func.substr(ub.User.name, 1, 1))).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Downloads"), page="downloadlist", data="download", order=order_no)
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 test_check_safe_path(self):
ret = disk_api._join_and_check_path_within_fs('/foo', 'etc',
'something.conf')
self.assertEquals(ret, '/foo/etc/something.conf') | 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 _clean_data_struct(orig_data):
'''
walk a complex data structure, and use _clean_data() to
remove any template tags that may exist
'''
if isinstance(orig_data, dict):
data = orig_data.copy()
for key in data:
new_key = _clean_data_struct(key)
new_val = _clean_data_struct(data[key])
if key != new_key:
del data[key]
data[new_key] = new_val
elif isinstance(orig_data, list):
data = orig_data[:]
for i in range(0, len(data)):
data[i] = _clean_data_struct(data[i])
elif isinstance(orig_data, basestring):
data = _clean_data(orig_data)
else:
data = orig_data
return data | 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 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) | 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 to_plist(self, data, options=None):
"""
Given some Python data, produces binary plist output.
"""
options = options or {}
if biplist is None:
raise ImproperlyConfigured("Usage of the plist aspects requires biplist.")
return biplist.writePlistToString(self.to_simple(data, options)) | 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 _setup_master(self):
Router.max_message_size = self.config['max_message_size']
if self.config['profiling']:
enable_profiling()
self.broker = Broker(activate_compat=False)
self.router = Router(self.broker)
self.router.debug = self.config.get('debug', False)
self.router.unidirectional = self.config['unidirectional']
self.router.add_handler(
fn=self._on_shutdown_msg,
handle=SHUTDOWN,
policy=has_parent_authority,
)
self.master = Context(self.router, 0, 'master')
parent_id = self.config['parent_ids'][0]
if parent_id == 0:
self.parent = self.master
else:
self.parent = Context(self.router, parent_id, 'parent')
in_fd = self.config.get('in_fd', 100)
in_fp = os.fdopen(os.dup(in_fd), 'rb', 0)
os.close(in_fd)
out_fp = os.fdopen(os.dup(self.config.get('out_fd', 1)), 'wb', 0)
self.stream = MitogenProtocol.build_stream(self.router, parent_id)
self.stream.accept(in_fp, out_fp)
self.stream.name = 'parent'
self.stream.receive_side.keep_alive = False
listen(self.stream, 'disconnect', self._on_parent_disconnect)
listen(self.broker, 'exit', self._on_broker_exit) | 1 | Python | CWE-254 | 7PK - Security Features | Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. | https://cwe.mitre.org/data/definitions/254.html | safe |
def test_nonexistent_catalog_is_none(self):
pardir = self.get_test_dir(erase=1)
cat = catalog.get_catalog(pardir,'r')
remove_tree(pardir)
assert_(cat is None) | 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_filelike_nocl_http10(self):
to_send = "GET /filelike_nocl HTTP/1.0\r\n\r\n"
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")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in 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 test_request_body_too_large_with_no_cl_http11_connclose(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.1\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 (assumed 0)
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 _create_dirs(path):
""" create provided path, ignore errors """
try:
os.makedirs(path, mode=0o700)
except OSError:
pass | 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_reset_entrance_exam_all_student_attempts(self, act):
""" Test reset all student attempts for entrance exam. """
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'all_students': True,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | 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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
self.handler = hs.get_device_handler()
self.store = hs.get_datastore()
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 count(cls, **kwargs):
"""Return a count of server side resources given
filtering arguments in kwargs.
"""
url = urljoin(recurly.base_uri(), cls.collection_path)
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.count_for_url(url) | 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 is_leaf(cls, path):
path = os.path.join(filesystem.FOLDER, path.replace("/", os.sep))
return os.path.isdir(path) and 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_notfilelike_nocl_http11(self):
to_send = "GET /notfilelike_nocl HTTP/1.1\n\n"
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.1")
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
# connection has been closed (no content-length)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | 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 __unicode__(self):
return self.xml() | 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_shared_models(self, args: "DictConfig") -> Dict[str, dict]:
with open(args.blueprint.model_opt_path) as f:
all_model_opts = yaml.load(f.read())
active_model_opts = {
model: opt
for model, opt in all_model_opts.items()
if self.conversations_needed[model] > 0
}
return TurkLikeAgent.get_bot_agents(args=args, model_opts=active_model_opts) | 0 | 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 | vulnerable |
def test_notfilelike_nocl_http11(self):
to_send = "GET /notfilelike_nocl HTTP/1.1\r\n\r\n"
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.1")
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
# connection has been closed (no content-length)
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_format_quota_set(self):
raw_quota_set = {
'instances': 10,
'cores': 20,
'ram': 51200,
'volumes': 10,
'floating_ips': 10,
'metadata_items': 128,
'gigabytes': 1000,
'injected_files': 5,
'injected_file_content_bytes': 10240}
quota_set = self.controller._format_quota_set('test_class',
raw_quota_set)
qs = quota_set['quota_class_set']
self.assertEqual(qs['id'], 'test_class')
self.assertEqual(qs['instances'], 10)
self.assertEqual(qs['cores'], 20)
self.assertEqual(qs['ram'], 51200)
self.assertEqual(qs['volumes'], 10)
self.assertEqual(qs['gigabytes'], 1000)
self.assertEqual(qs['floating_ips'], 10)
self.assertEqual(qs['metadata_items'], 128)
self.assertEqual(qs['injected_files'], 5)
self.assertEqual(qs['injected_file_content_bytes'], 10240) | 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 table_get_custom_enum(c_id):
ret = list()
cc = (calibre_db.session.query(db.Custom_Columns)
.filter(db.Custom_Columns.id == c_id)
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())
ret.append({'value': "", 'text': ""})
for idx, en in enumerate(cc.get_display_dict()['enum_values']):
ret.append({'value': en, 'text': en})
return json.dumps(ret) | 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_get_ora2_responses_already_running(self):
url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})
with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
mock_submit_ora2_task.side_effect = AlreadyRunningError()
response = self.client.post(url, {})
already_running_status = "An ORA data report generation task is already in progress."
self.assertIn(already_running_status, response.content) | 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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(http_client=None)
self.handler = hs.get_federation_handler()
self.store = hs.get_datastore()
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 make_homeserver(self, reactor, clock):
self.fetches = []
def get_file(destination, path, output_stream, args=None, max_size=None):
"""
Returns tuple[int,dict,str,int] of file length, response headers,
absolute URI, and response code.
"""
def write_to(r):
data, response = r
output_stream.write(data)
return response
d = Deferred()
d.addCallback(write_to)
self.fetches.append((d, destination, path, args))
return make_deferred_yieldable(d)
client = Mock()
client.get_file = get_file
self.storage_path = self.mktemp()
self.media_store_path = self.mktemp()
os.mkdir(self.storage_path)
os.mkdir(self.media_store_path)
config = self.default_config()
config["media_store_path"] = self.media_store_path
config["thumbnail_requirements"] = {}
config["max_image_pixels"] = 2000000
provider_config = {
"module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend",
"store_local": True,
"store_synchronous": False,
"store_remote": True,
"config": {"directory": self.storage_path},
}
config["media_storage_providers"] = [provider_config]
hs = self.setup_test_homeserver(config=config, federation_http_client=client)
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 test_build_attr(self):
assert set(ClearableFileInput().build_attrs({}).keys()) == {
"class",
"data-url",
"data-fields-x-amz-algorithm",
"data-fields-x-amz-date",
"data-fields-x-amz-signature",
"data-fields-x-amz-credential",
"data-fields-policy",
"data-fields-key",
}
assert ClearableFileInput().build_attrs({})["class"] == "s3file"
assert (
ClearableFileInput().build_attrs({"class": "my-class"})["class"]
== "my-class s3file"
) | 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_get_sale_records_features_json(self):
"""
Test that the response from get_sale_records is in json format.
"""
for i in range(5):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i),
course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor,
invoice=self.sale_invoice_1,
invoice_item=self.invoice_item,
mode_slug='honor'
)
course_registration_code.save()
url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {})
res_json = json.loads(response.content)
self.assertIn('sale', res_json)
for res in res_json['sale']:
self.validate_sale_records_response(
res,
course_registration_code,
self.sale_invoice_1,
0,
invoice_item=self.invoice_item
) | 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 test_methodWithCLRFRejected(self):
"""
Issuing a request with a method that contains a carriage
return and line feed fails with a L{ValueError}.
"""
with self.assertRaises(ValueError) as cm:
method = b"GET\r\nX-Injected-Header: value"
self.attemptRequestWithMaliciousMethod(method)
self.assertRegex(str(cm.exception), "^Invalid method") | 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 read_config(self, config, **kwargs):
# FIXME: federation_domain_whitelist needs sytests
self.federation_domain_whitelist = None # type: Optional[dict]
federation_domain_whitelist = config.get("federation_domain_whitelist", None)
if federation_domain_whitelist is not None:
# turn the whitelist into a hash for speed of lookup
self.federation_domain_whitelist = {}
for domain in federation_domain_whitelist:
self.federation_domain_whitelist[domain] = True
self.federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", []
)
# Attempt to create an IPSet from the given ranges
try:
self.federation_ip_range_blacklist = IPSet(
self.federation_ip_range_blacklist
)
# Always blacklist 0.0.0.0, ::
self.federation_ip_range_blacklist.update(["0.0.0.0", "::"])
except Exception as e:
raise ConfigError(
"Invalid range(s) provided in federation_ip_range_blacklist: %s" % e
)
federation_metrics_domains = config.get("federation_metrics_domains") or []
validate_config(
_METRICS_FOR_DOMAINS_SCHEMA,
federation_metrics_domains,
("federation_metrics_domains",),
)
self.federation_metrics_domains = set(federation_metrics_domains) | 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 deserialize(self, content, format='application/json'):
"""
Given some data and a format, calls the correct method to deserialize
the data and returns the result.
"""
desired_format = None
format = format.split(';')[0]
for short_format, long_format in self.content_types.items():
if format == long_format:
if hasattr(self, "from_%s" % short_format):
desired_format = short_format
break
if desired_format is None:
raise UnsupportedFormat("The format indicated '%s' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
deserialized = getattr(self, "from_%s" % desired_format)(content)
return deserialized | 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 escape_text(text: EscapableEntity) -> str:
"""Escape HTML text
We only strip some tags and allow some simple tags
such as <h1>, <b> or <i> to be part of the string.
This is useful for messages where we want to keep formatting
options. (Formerly known as 'permissive_attrencode')
Args:
text:
Examples:
>>> escape_text("Hello this is dog!")
'Hello this is dog!'
This is lame.
>>> escape_text("Hello this <a href=\"\">is dog</a>!")
'Hello this <a href=>is dog</a>!'
Returns:
"""
if isinstance(text, HTML):
return text.__html__()
text = escape_attribute(text)
text = _UNESCAPER_TEXT.sub(r'<\1\2>', text)
for a_href in _A_HREF.finditer(text):
text = text.replace(a_href.group(0), u"<a href=%s>" % _QUOTE.sub(u"\"", a_href.group(1)))
return text.replace(u"&nbsp;", u" ") | 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 testInvalidSparseTensor(self):
with test_util.force_cpu():
shape = [2, 2]
val = [0]
dense = constant_op.constant(np.zeros(shape, dtype=np.int32))
for bad_idx in [
[[-1, 0]], # -1 is invalid.
[[1, 3]], # ...so is 3.
]:
sparse = sparse_tensor.SparseTensorValue(bad_idx, val, shape)
with self.assertRaisesRegex(
(ValueError, errors_impl.InvalidArgumentError), "invalid index"):
s = sparse_ops.sparse_add(sparse, dense)
self.evaluate(s) | 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 sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId)) | 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 test_pathWithCRLFRejected(self):
"""
Issuing a request with a URI whose path contains a carriage
return and line feed fails with a L{ValueError}.
"""
with self.assertRaises(ValueError) as cm:
uri = b"http://twisted.invalid/\r\npath"
self.attemptRequestWithMaliciousURI(uri)
self.assertRegex(str(cm.exception), "^Invalid URI") | 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_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin):
session = Session(self.config_dir)
session['cookies'] = initial_cookie
session.remove_cookies([expired_cookie])
assert expired_cookie not in session.cookies | 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 _download_file(bucket, filename, local_dir):
key = bucket.get_key(filename)
local_filename = os.path.join(local_dir, filename)
key.get_contents_to_filename(local_filename)
return local_filename | 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 resolveHostName(
self, recv: IResolutionReceiver, hostname: str, portNumber: int = 0 | 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 logout(request):
""" Clears the session and logs the current user out. """
request.user_logout()
# FIXME(gabriel): we don't ship a view named splash
return shortcuts.redirect('splash') | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
async def handle_404(request, response):
if 'json' not in response.headers['Content-Type']:
if request.path.endswith('/'):
return web.HTTPFound(request.path.rstrip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(request.path)
}, status=404)
return response | 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_object_src_http(dataset, rel_path):
path = _get_obj_abosolute_path(dataset, rel_path)
response = send_file(path,
cache_timeout=datetime.timedelta(
days=365).total_seconds(),
add_etags=True,
conditional=True)
return response | 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, directory=None, pattern='__jinja2_%s.cache'):
if directory is None:
directory = self._get_default_cache_dir()
self.directory = directory
self.pattern = pattern | 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_course_has_entrance_exam_in_student_attempts_reset(self):
""" Test course has entrance exam id set while resetting attempts"""
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course.id)})
response = self.client.post(url, {
'all_students': True,
'delete_module': False,
})
self.assertEqual(response.status_code, 400) | 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 setUp(self):
"""
Set up global staff role so authorization will not fail.
"""
super(TestEndpointHttpMethods, self).setUp()
global_user = GlobalStaffFactory()
self.client.login(username=global_user.username, password='test') | 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 test_received_bad_host_header(self):
from waitress.utilities import BadRequest
data = b"""\
HTTP/1.0 GET /foobar
Host: foo
"""
result = self.parser.received(data)
self.assertEqual(result, 33)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.error.__class__, BadRequest) | 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 testRaggedCountSparseOutput(self):
splits = [0, 4, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
output_indices, output_values, output_shape = self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits, values=values, weights=weights, binary_output=False))
self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]],
output_indices)
self.assertAllEqual([7, 3, 5, 7, 6], output_values)
self.assertAllEqual([2, 11], output_shape) | 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 _is_javascript_scheme(s):
if _is_image_dataurl(s):
return None
return _is_possibly_malicious_scheme(s) | 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 test_endpoints_reject_get(self, data):
"""
Tests that POST endpoints are rejected with 405 when using GET.
"""
url = reverse(data, kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(
response.status_code, 405,
"Endpoint {} returned status code {} instead of a 405. It should not allow GET.".format(
data, response.status_code
)
) | 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 test_roundtrip_file(self):
f = open(self.filename, 'wb')
self.x.tofile(f)
f.close()
# NB. doesn't work with flush+seek, due to use of C stdio
f = open(self.filename, 'rb')
y = np.fromfile(f, dtype=self.dtype)
f.close()
assert_array_equal(y, self.x.flat)
os.unlink(self.filename) | 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 _lookup(self, name, *args, **kwargs):
instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
# safely catch run failures per #5059
try:
ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)
except (AnsibleUndefinedVariable, UndefinedError) as e:
raise AnsibleUndefinedVariable(e)
except Exception as e:
if self._fail_on_lookup_errors:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, "
"original message: %s" % (name, type(e), e))
ran = None
if ran:
if wantlist:
ran = wrap_var(ran)
else:
try:
ran = UnsafeProxy(",".join(ran))
except TypeError:
if isinstance(ran, list) and len(ran) == 1:
ran = wrap_var(ran[0])
else:
ran = wrap_var(ran)
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name) | 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 test_poisoned_http_host_admin_site(self):
"Poisoned HTTP_HOST headers can't be used for reset emails on admin views"
with self.assertRaises(SuspiciousOperation):
self.client.post('/admin_password_reset/',
{'email': '[email protected]'},
HTTP_HOST='www.example:[email protected]'
)
self.assertEqual(len(mail.outbox), 0) | 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_quotas_defaults(self):
uri = '/v2/fake_tenant/os-quota-sets/fake_tenant/defaults'
req = fakes.HTTPRequest.blank(uri)
res_dict = self.controller.defaults(req, 'fake_tenant')
expected = {'quota_set': {
'id': 'fake_tenant',
'instances': 10,
'cores': 20,
'ram': 51200,
'volumes': 10,
'gigabytes': 1000,
'floating_ips': 10,
'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'security_groups': 10,
'security_group_rules': 20,
}}
self.assertEqual(res_dict, expected) | 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 getresponse(self):
mapper = routes.Mapper()
api = context.UnauthenticatedContextMiddleware(rserver.API(mapper))
webob_res = self.req.get_response(api)
return utils.FakeHTTPResponse(status=webob_res.status_int,
headers=webob_res.headers,
data=webob_res.body) | 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 setUp(self):
config = {
"general": {
"ip.blacklist": "5.0.0.0/8",
"ip.whitelist": "5.1.1.1",
},
}
self.sydent = make_sydent(test_config=config)
self.reactor = self.sydent.reactor
self.safe_domain, self.safe_ip = b"safe.test", b"1.2.3.4"
self.unsafe_domain, self.unsafe_ip = b"danger.test", b"5.6.7.8"
self.allowed_domain, self.allowed_ip = b"allowed.test", b"5.1.1.1"
# Configure the reactor's DNS resolver.
for (domain, ip) in (
(self.safe_domain, self.safe_ip),
(self.unsafe_domain, self.unsafe_ip),
(self.allowed_domain, self.allowed_ip),
):
self.reactor.lookups[domain.decode()] = ip.decode()
self.reactor.lookups[ip.decode()] = ip.decode()
self.ip_whitelist = self.sydent.ip_whitelist
self.ip_blacklist = self.sydent.ip_blacklist | 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 make_homeserver(self, reactor, clock):
config = self.default_config()
config["redaction_retention_period"] = "30d"
return self.setup_test_homeserver(
resource_for_federation=Mock(), http_client=None, config=config
) | 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 check_ownership():
""" Intermediate dir owner should be same as owner of process. """
if sys.platform != 'win32':
try:
im_dir_stat = os.stat(im_dir)
except OSError:
return False
proc_uid = os.getuid()
return proc_uid == im_dir_stat.st_uid
return True | 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 load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs):
"""
This is the image 'Preview' tab for the right-hand panel.
"""
context = {}
# the index of a field within a well
index = getIntOrDefault(request, "index", 0)
manager = BaseContainer(conn, **{str(c_type): long(c_id)})
if share_id:
context["share"] = BaseShare(conn, share_id)
if c_type == "well":
manager.image = manager.well.getImage(index)
allRdefs = manager.image.getAllRenderingDefs()
rdefs = {}
rdefId = manager.image.getRenderingDefId()
# remove duplicates per user
for r in allRdefs:
ownerId = r["owner"]["id"]
r["current"] = r["id"] == rdefId
# if duplicate rdefs for user, pick one with highest ID
if ownerId not in rdefs or rdefs[ownerId]["id"] < r["id"]:
rdefs[ownerId] = r
rdefs = rdefs.values()
# format into rdef strings,
# E.g. {c: '1|3118:35825$FF0000,2|2086:18975$FFFF00', m: 'c'}
rdefQueries = []
for r in rdefs:
chs = []
for i, c in enumerate(r["c"]):
act = "-"
if c["active"]:
act = ""
color = c["lut"] if "lut" in c else c["color"]
reverse = "r" if c["inverted"] else "-r"
chs.append(
"%s%s|%s:%s%s$%s" % (act, i + 1, c["start"], c["end"], reverse, color)
)
rdefQueries.append(
{
"id": r["id"],
"owner": r["owner"],
"c": ",".join(chs),
"m": r["model"] == "greyscale" and "g" or "c",
}
)
max_w, max_h = conn.getMaxPlaneSize()
size_x = manager.image.getSizeX()
size_y = manager.image.getSizeY()
context["tiledImage"] = (size_x * size_y) > (max_w * max_h)
context["manager"] = manager
context["rdefsJson"] = json.dumps(rdefQueries)
context["rdefs"] = rdefs
context["template"] = "webclient/annotations/metadata_preview.html"
return context | 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 |
async def on_room_state_request(
self, origin: str, room_id: str, event_id: str | 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 test_use_yaml_safe_load(mock_yaml):
"""
Ensure we're using yaml.safe_load not yaml.load
"""
from confire.config import Configuration
Configuration.CONF_PATHS = [TESTCONF]
Configuration.load()
mock_yaml.safe_load.assert_called_once()
mock_yaml.load.assert_not_called() | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.