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 testRaggedCountSparseOutputEmptySplits(self):
splits = []
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Must provide at least 2 elements for the splits argument"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False)) | 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 validate_and_sanitize_search_inputs(fn, instance, args, kwargs):
kwargs.update(dict(zip(fn.__code__.co_varnames, args)))
sanitize_searchfield(kwargs['searchfield'])
kwargs['start'] = cint(kwargs['start'])
kwargs['page_len'] = cint(kwargs['page_len'])
if kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']):
return []
return fn(**kwargs) | 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 wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect(request.GET.get('next', request.user.st.get_absolute_url()))
return view_func(request, *args, **kwargs) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def test_webhook_authorization(self):
errors = check_deprecated_settings(None)
self.assertEqual(errors, [checks.Warning(
"The ANYMAIL setting 'WEBHOOK_AUTHORIZATION' has been renamed '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 format_time(self, data):
"""
A hook to control how times are formatted.
Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).
Default is ``iso-8601``, which looks like "03:02:14".
"""
if self.datetime_formatting == 'rfc-2822':
return format_time(data)
return data.isoformat() | 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 unichrs(s):
return ''.join(chr(int(x, 16)) for x in s.split('+')) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def get(self, key):
"""
Gets the object specified by key. It will also unserialize the object
before returning if it is serialized in memcache with JSON, or if it
is pickled and unpickling is allowed.
: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:
if self._allow_unpickle:
value = pickle.loads(value)
else:
value = None
elif int(line[2]) & JSON_FLAG:
value = json.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) | 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_certificates_features_csv(self):
"""
Test for certificate csv features.
"""
url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
# firstly generating downloadable certificates with 'honor' mode
certificate_count = 3
for __ in xrange(certificate_count):
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
current_date = datetime.date.today().strftime("%B %d, %Y")
response = self.client.get(url, {'csv': 'true'})
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv'))
self.assertEqual(
response.content.strip(),
'"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"'
+ str(self.course.id) + '","honor","3","' + current_date + '"'
) | 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 parse_func_type_input(source):
return ast.parse(source, "<unknown>", "func_type") | 1 | Python | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey, | 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 _should_decode(typ):
# either a basetype which needs to be clamped
# or a complex type which contains something that
# needs to be clamped.
if isinstance(typ, BaseType):
return typ.typ not in ("int256", "uint256", "bytes32")
if isinstance(typ, (ByteArrayLike, DArrayType)):
return True
if isinstance(typ, SArrayType):
return _should_decode(typ.subtype)
if isinstance(typ, TupleLike):
return any(_should_decode(t) for t in typ.tuple_members())
raise CompilerPanic(f"_should_decode({typ})") # pragma: notest | 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 test_coupon_redeem_count_in_ecommerce_section(self):
"""
Test that checks the redeem count in the instructor_dashboard coupon section
"""
# add the coupon code for the course
coupon = Coupon(
code='test_code', description='test_description', course_id=self.course.id,
percentage_discount='10', created_by=self.instructor, is_active=True
)
coupon.save()
# Coupon Redeem Count only visible for Financial Admins.
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
PaidCourseRegistration.add_to_order(self.cart, self.course.id)
# apply the coupon code to the item in the cart
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
self.assertEqual(resp.status_code, 200)
# URL for instructor dashboard
instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
# visit the instructor dashboard page and
# check that the coupon redeem count should be 0
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Number Redeemed', resp.content)
self.assertIn('<td>0</td>', resp.content)
# now make the payment of your cart items
self.cart.purchase()
# visit the instructor dashboard page and
# check that the coupon redeem count should be 1
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Number Redeemed', resp.content)
self.assertIn('<td>1</td>', resp.content) | 0 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | vulnerable |
def respond_error(self, context, exception):
context.respond_server_error()
stack = traceback.format_exc()
return """
<html>
<body>
<style>
body {
font-family: sans-serif;
color: #888;
text-align: center;
}
body pre {
width: 600px;
text-align: left;
margin: auto;
font-family: monospace;
}
</style>
<img src="/ajenti:static/main/error.jpeg" />
<br/>
<p>
Server error
</p>
<pre>
%s
</pre>
</body>
</html>
""" % cgi.escape(stack) | 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 on_permitted_domain(team: Team, request: HttpRequest) -> bool:
permitted_domains = ["127.0.0.1", "localhost"]
for url in team.app_urls:
hostname = parse_domain(url)
if hostname:
permitted_domains.append(hostname)
origin = parse_domain(request.headers.get("Origin"))
referer = parse_domain(request.headers.get("Referer"))
for permitted_domain in permitted_domains:
if "*" in permitted_domain:
pattern = "^{}$".format(permitted_domain.replace(".", "\\.").replace("*", "(.*)"))
if (origin and re.search(pattern, origin)) or (referer and re.search(pattern, referer)):
return True
else:
if permitted_domain == origin or permitted_domain == referer:
return True
return False | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def test_reset_student_attempts_delete(self):
""" Test delete single student state. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'delete_module': True,
})
self.assertEqual(response.status_code, 200)
# make sure the module has been deleted
self.assertEqual(
StudentModule.objects.filter(
student=self.module_to_reset.student,
course_id=self.module_to_reset.course_id,
# module_id=self.module_to_reset.module_id,
).count(),
0
) | 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 get_release_file(root, request):
session = DBSession()
f = ReleaseFile.by_id(session, int(request.matchdict['file_id']))
url = f.url
if url.startswith('http://pypi.python.org'):
url = 'https' + url[4:]
rv = {'id': f.id,
'url': url,
'filename': f.filename,
}
f.downloads += 1
f.release.downloads += 1
f.release.package.downloads += 1
session.add(f.release.package)
session.add(f.release)
session.add(f)
return rv | 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_reset_date(self):
self.test_change_due_date()
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
) | 1 | Python | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
def parse_json(raw_data):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
return json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
return results | 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_logout_post(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar')
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) | 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_started_typing_remote_send(self):
self.room_members = [U_APPLE, U_ONION]
self.get_success(
self.handler.started_typing(
target_user=U_APPLE,
requester=create_requester(U_APPLE),
room_id=ROOM_ID,
timeout=20000,
)
)
put_json = self.hs.get_federation_http_client().put_json
put_json.assert_called_once_with(
"farm",
path="/_matrix/federation/v1/send/1000000",
data=_expect_edu_transaction(
"m.typing",
content={
"room_id": ROOM_ID,
"user_id": U_APPLE.to_string(),
"typing": True,
},
),
json_data_callback=ANY,
long_retries=True,
backoff_on_404=True,
try_trailing_slash_on_400=True,
) | 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_json_dumps_xss(self):
"""Testing json_dumps doesn't allow XSS injection"""
# This is bug 3406.
obj = {
'xss': '</script><script>alert(1);</script>'
}
self.assertEqual(
json_dumps(obj),
'{"xss": "\\u003C/script\\u003E\\u003Cscript\\u003E'
'alert(1);\\u003C/script\\u003E"}') | 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 safe_text(raw_text: str) -> jinja2.Markup:
"""
Process text: treat it as HTML but escape any tags (ie. just escape the
HTML) then linkify it.
"""
return jinja2.Markup(
bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False))
) | 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 qute_settings(url):
"""Handler for qute://settings. View/change qute configuration."""
global csrf_token
if url.path() == '/set':
if url.password() != csrf_token:
message.error("Invalid CSRF token for qute://settings!")
raise QuteSchemeError("Invalid CSRF token!",
QNetworkReply.ContentAccessDenied)
return _qute_settings_set(url)
# Requests to qute://settings/set should only be allowed from
# qute://settings. As an additional security precaution, we generate a CSRF
# token to use here.
if secrets:
csrf_token = secrets.token_urlsafe()
else:
# On Python < 3.6, from secrets.py
token = base64.urlsafe_b64encode(os.urandom(32))
csrf_token = token.rstrip(b'=').decode('ascii')
src = jinja.render('settings.html', title='settings',
configdata=configdata,
confget=config.instance.get_str,
csrf_token=csrf_token)
return 'text/html', src | 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 model_from_config(config, custom_objects=None):
"""Instantiates a Keras model from its config.
Usage:
```
# for a Functional API model
tf.keras.Model().from_config(model.get_config())
# for a Sequential model
tf.keras.Sequential().from_config(model.get_config())
```
Args:
config: Configuration dictionary.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
Returns:
A Keras model instance (uncompiled).
Raises:
TypeError: if `config` is not a dictionary.
"""
if isinstance(config, list):
raise TypeError('`model_from_config` expects a dictionary, not a list. '
'Maybe you meant to use '
'`Sequential.from_config(config)`?')
from tensorflow.python.keras.layers import deserialize # pylint: disable=g-import-not-at-top
return deserialize(config, custom_objects=custom_objects) | 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 testInputPreProcessErrorBadFormat(self):
input_str = 'inputx=file[[v1]v2'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str)
input_str = 'inputx:file'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str)
input_str = 'inputx:np.zeros((5))'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_input_exprs_arg_string(input_str) | 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 _assert_matches(
self, condition: Dict[str, Any], content: Dict[str, Any], msg=None | 1 | Python | CWE-331 | Insufficient Entropy | The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
def get_credits(request, project=None, component=None):
"""View for credits."""
if project is None:
obj = None
kwargs = {"translation__isnull": False}
elif component is None:
obj = get_project(request, project)
kwargs = {"translation__component__project": obj}
else:
obj = get_component(request, project, component)
kwargs = {"translation__component": obj}
form = ReportsForm(request.POST)
if not form.is_valid():
show_form_errors(request, form)
return redirect_param(obj or "home", "#reports")
data = generate_credits(
None if request.user.has_perm("reports.view", obj) else request.user,
form.cleaned_data["start_date"],
form.cleaned_data["end_date"],
**kwargs,
)
if form.cleaned_data["style"] == "json":
return JsonResponse(data=data, safe=False)
if form.cleaned_data["style"] == "html":
start = "<table>"
row_start = "<tr>"
language_format = "<th>{0}</th>"
translator_start = "<td><ul>"
translator_format = '<li><a href="mailto:{0}">{1}</a> ({2})</li>'
translator_end = "</ul></td>"
row_end = "</tr>"
mime = "text/html"
end = "</table>"
else:
start = ""
row_start = ""
language_format = "* {0}\n"
translator_start = ""
translator_format = " * {1} <{0}> ({2})"
translator_end = ""
row_end = ""
mime = "text/plain"
end = ""
result = [start]
for language in data:
name, translators = language.popitem()
result.append(row_start)
result.append(language_format.format(name))
result.append(
translator_start
+ "\n".join(translator_format.format(*t) for t in translators)
+ translator_end
)
result.append(row_end)
result.append(end)
return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8") | 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 load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
self.mode = self.im.mode
self.size = self.im.size
self.tile = [] | 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_send_event_single_sender(self):
"""Test that using a single federation sender worker correctly sends a
new event.
"""
mock_client = Mock(spec=["put_json"])
mock_client.put_json.return_value = make_awaitable({})
self.make_worker_hs(
"synapse.app.federation_sender",
{"send_federation": True},
federation_http_client=mock_client,
)
user = self.register_user("user", "pass")
token = self.login("user", "pass")
room = self.create_room_with_remote_server(user, token)
mock_client.put_json.reset_mock()
self.create_and_send_event(room, UserID.from_string(user))
self.replicate()
# Assert that the event was sent out over federation.
mock_client.put_json.assert_called()
self.assertEqual(mock_client.put_json.call_args[0][0], "other_server")
self.assertTrue(mock_client.put_json.call_args[1]["data"].get("pdus")) | 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 feed_get_cover(book_id):
return get_book_cover(book_id) | 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, sydent):
self.sydent = sydent
# The default endpoint factory in Twisted 14.0.0 (which we require) uses the
# BrowserLikePolicyForHTTPS context factory which will do regular cert validation
# 'like a browser'
self.agent = Agent(
self.sydent.reactor,
connectTimeout=15,
) | 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 testNonScalarKeyOrderedMap(self):
with ops.Graph().as_default() as g:
x = array_ops.placeholder(dtypes.float32)
v = 2. * (array_ops.zeros([128, 128]) + x)
t = data_flow_ops.gen_data_flow_ops.ordered_map_stage(
key=constant_op.constant(value=[1], shape=(1, 3), dtype=dtypes.int64),
indices=np.array([[6]]),
values=[x, v],
dtypes=[dtypes.int64],
capacity=0,
memory_limit=0,
container='container1',
shared_name='',
name=None)
g.finalize()
with self.session(graph=g) as sess:
with self.assertRaisesRegex(errors.InvalidArgumentError,
'key must be an int64 scalar'):
sess.run(t, feed_dict={x: 1}) | 1 | Python | CWE-843 | Access of Resource Using Incompatible Type ('Type Confusion') | The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type. | https://cwe.mitre.org/data/definitions/843.html | safe |
def test_login_post(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/')
response = self.client.post('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '/private/')
self.assertEqual(response.wsgi_request.user, self.user)
self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists()) | 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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
http_client=None, homeserver_to_use=GenericWorkerServer
)
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 skip(self, type):
if type == TType.BOOL:
self.readBool()
elif type == TType.BYTE:
self.readByte()
elif type == TType.I16:
self.readI16()
elif type == TType.I32:
self.readI32()
elif type == TType.I64:
self.readI64()
elif type == TType.DOUBLE:
self.readDouble()
elif type == TType.FLOAT:
self.readFloat()
elif type == TType.STRING:
self.readString()
elif type == TType.STRUCT:
name = self.readStructBegin()
while True:
(name, type, id) = self.readFieldBegin()
if type == TType.STOP:
break
self.skip(type)
self.readFieldEnd()
self.readStructEnd()
elif type == TType.MAP:
(ktype, vtype, size) = self.readMapBegin()
for _ in range(size):
self.skip(ktype)
self.skip(vtype)
self.readMapEnd()
elif type == TType.SET:
(etype, size) = self.readSetBegin()
for _ in range(size):
self.skip(etype)
self.readSetEnd()
elif type == TType.LIST:
(etype, size) = self.readListBegin()
for _ in range(size):
self.skip(etype)
self.readListEnd()
else:
raise TProtocolException(
TProtocolException.INVALID_DATA,
"Unexpected type for skipping {}".format(type)
) | 1 | Python | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
def testSparseCountSparseOutputBadNumberOfValues(self):
indices = [[0, 0], [0, 1], [1, 0]]
values = [1, 1, 1, 10]
weights = [1, 2, 4, 6]
dense_shape = [2, 3]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Number of values must match first dimension of indices"):
self.evaluate(
gen_count_ops.SparseCountSparseOutput(
indices=indices,
values=values,
dense_shape=dense_shape,
weights=weights,
binary_output=False)) | 1 | Python | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
def __init__(
self,
*,
resource_group: str,
location: str,
application_name: str,
owner: str,
client_id: Optional[str],
client_secret: Optional[str],
app_zip: str,
tools: str,
instance_specific: str,
third_party: str,
arm_template: str,
workbook_data: str,
create_registration: bool,
migrations: List[str],
export_appinsights: bool,
log_service_principal: bool,
multi_tenant_domain: str,
upgrade: bool,
subscription_id: Optional[str],
admins: List[UUID] | 0 | Python | CWE-285 | Improper Authorization | The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action. | https://cwe.mitre.org/data/definitions/285.html | vulnerable |
def testStringNGramsBadDataSplits(self, splits):
data = ["aa", "bb", "cc", "dd", "ee", "ff"]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
r"Invalid split value|First split value must be 0"):
self.evaluate(
gen_string_ops.string_n_grams(
data=data,
data_splits=splits,
separator="",
ngram_widths=[2],
left_pad="",
right_pad="",
pad_width=0,
preserve_short_sequences=False)) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
def setUp(self):
shape = (2, 4, 3)
rand = np.random.random
self.x = rand(shape) + rand(shape).astype(np.complex)*1j
self.x[0,:, 1] = [nan, inf, -inf, nan]
self.dtype = self.x.dtype
self.file = tempfile.NamedTemporaryFile()
self.filename = self.file.name | 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 build_key(self, filename, entry, metadata):
"""
generates a new key according the the specification
"""
type = self.key_specs[entry.get('name')]['type']
bits = self.key_specs[entry.get('name')]['bits']
if type == 'rsa':
cmd = "openssl genrsa %s " % bits
elif type == 'dsa':
cmd = "openssl dsaparam -noout -genkey %s" % bits
key = Popen(cmd, shell=True, stdout=PIPE).stdout.read()
return key | 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 is_valid_hostname(string: str) -> bool:
"""Validate that a given string is a valid hostname or domain name.
For domain names, this only validates that the form is right (for
instance, it doesn't check that the TLD is valid).
:param string: The string to validate
:type string: str
:return: Whether the input is a valid hostname
:rtype: bool
"""
return hostname_regex.match(string) is not None | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
async def on_GET(self, origin, _content, query, room_id, user_id):
"""
Args:
origin (unicode): The authenticated server_name of the calling server
_content (None): (GETs don't have bodies)
query (dict[bytes, list[bytes]]): Query params from the request.
**kwargs (dict[unicode, unicode]): the dict mapping keys to path
components as specified in the path match regexp.
Returns:
Tuple[int, object]: (response code, response object)
"""
versions = query.get(b"ver")
if versions is not None:
supported_versions = [v.decode("utf-8") for v in versions]
else:
supported_versions = ["1"]
content = await self.handler.on_make_join_request(
origin, room_id, user_id, supported_versions=supported_versions
)
return 200, content | 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 runTest(self):
for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP):
encryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv)
ciphertext = encryption_cipher.encrypt(self.plaintext)
if mode != self.module.MODE_OPENPGP:
decryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv)
else:
eiv = ciphertext[:self.module.block_size+2]
ciphertext = ciphertext[self.module.block_size+2:]
decryption_cipher = self.module.new(a2b_hex(self.key), mode, eiv)
decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
self.assertEqual(self.plaintext, decrypted_plaintext) | 0 | Python | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
def test_received_error_from_parser(self):
from waitress.utilities import BadRequest
data = (
b"GET /foobar HTTP/1.1\r\n"
b"Transfer-Encoding: chunked\r\n"
b"X-Foo: 1\r\n"
b"\r\n"
b"garbage\r\n"
)
# header
result = self.parser.received(data)
# body
result = self.parser.received(data[result:])
self.assertEqual(result, 9)
self.assertTrue(self.parser.completed)
self.assertTrue(isinstance(self.parser.error, BadRequest)) | 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 authorize_and_redirect(request):
if not request.GET.get("redirect"):
return HttpResponse("You need to pass a url to ?redirect=", status=401)
if not request.META.get("HTTP_REFERER"):
return HttpResponse('You need to make a request that includes the "Referer" header.', status=400)
referer_url = urlparse(request.META["HTTP_REFERER"])
redirect_url = urlparse(request.GET["redirect"])
if referer_url.hostname != redirect_url.hostname:
return HttpResponse(f"Can only redirect to the same domain as the referer: {referer_url.hostname}", status=400)
if referer_url.scheme != redirect_url.scheme:
return HttpResponse(f"Can only redirect to the same scheme as the referer: {referer_url.scheme}", status=400)
if referer_url.port != redirect_url.port:
return HttpResponse(
f"Can only redirect to the same port as the referer: {referer_url.port or 'no port in URL'}", status=400
)
return render_template(
"authorize_and_redirect.html",
request=request,
context={"domain": redirect_url.hostname, "redirect_url": request.GET["redirect"]},
) | 0 | Python | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | vulnerable |
def __init__(self, bus, object_path):
super(Engine, self).__init__(connection=bus.get_connection(),
object_path=object_path)
# create anthy context
self.__context = Anthy.GContext()
self.__context.set_encoding(Anthy.UTF8_ENCODING)
# init state
self.__idle_id = 0
self.__prop_dict = {}
self.__input_purpose = 0
self.__has_input_purpose = False
if hasattr(IBus, 'InputPurpose'):
self.__has_input_purpose = True
try:
self.__is_utf8 = (getpreferredencoding().lower() == 'utf-8')
except:
self.__is_utf8 = False
self.__ibus_version = 0.0
# self.__lookup_table = ibus.LookupTable.new(page_size=9,
# cursor_pos=0,
# cursor_visible=True,
# round=True)
size = self.__prefs.get_value('common', 'page_size')
self.__lookup_table = IBus.LookupTable.new(page_size=size,
cursor_pos=0,
cursor_visible=True,
round=True)
self.__prop_list = self.__init_props()
self.__init_signal()
# use reset to init values
self.__reset()
ibus_config = bus.get_config()
if ibus_config != None:
ibus_config.connect('value-changed',
self.__config_value_changed_cb) | 1 | Python | CWE-255 | Credentials Management Errors | Weaknesses in this category are related to the management of credentials. | https://cwe.mitre.org/data/definitions/255.html | safe |
def _get_http_request(self, expected_host, expected_port):
clients = self.reactor.tcpClients
(host, port, factory, _timeout, _bindAddress) = clients[-1]
self.assertEqual(host, expected_host)
self.assertEqual(port, expected_port)
# complete the connection and wire it up to a fake transport
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol.makeConnection(transport)
return transport, protocol | 1 | Python | CWE-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 edit_book_series_index(series_index, book):
# Add default series_index to book
modif_date = False
series_index = series_index or '1'
if not series_index.replace('.', '', 1).isdigit():
flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=series_index), category="warning")
return False
if str(book.series_index) != series_index:
book.series_index = series_index
modif_date = True
return modif_date | 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 render_archived_books(page, sort_param):
order = sort_param[0] or []
archived_books = (
ub.session.query(ub.ArchivedBook)
.filter(ub.ArchivedBook.user_id == int(current_user.id))
.filter(ub.ArchivedBook.is_archived == True)
.all()
)
archived_book_ids = [archived_book.book_id for archived_book in archived_books]
archived_filter = db.Books.id.in_(archived_book_ids)
entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books,
0,
archived_filter,
order,
True,
False, 0)
name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
pagename = "archived"
return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
title=name, page=pagename, order=sort_param[1]) | 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 testSpecQuoteAttribute(c):
input_ = [["StartTag", "http://www.w3.org/1999/xhtml", "span",
[{"namespace": None, "name": "foo", "value": c}]]]
if c == '"':
output_ = ["<span foo='%s'>" % c]
else:
output_ = ['<span foo="%s">' % c]
options_ = {"quote_attr_values": "spec"}
runSerializerTest(input_, output_, options_) | 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 quota_set(id):
return {'quota_set': {'id': id, 'metadata_items': 128, 'volumes': 10,
'gigabytes': 1000, 'ram': 51200, 'floating_ips': 10,
'instances': 10, 'injected_files': 5, 'cores': 20,
'injected_file_content_bytes': 10240,
'security_groups': 10, 'security_group_rules': 20}} | 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 testInputPreProcessErrorBadFormat(self):
input_str = 'inputx=file[[v1]v2'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str)
input_str = 'inputx:file'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str)
input_str = 'inputx:np.zeros((5))'
with self.assertRaisesRegex(RuntimeError, 'format is incorrect'):
saved_model_cli.preprocess_input_exprs_arg_string(input_str, safe=False) | 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_http10_list(self):
body = string.ascii_letters
to_send = (
"GET /list HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: %d\r\n\r\n" % len(body)
)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers["content-length"], str(len(body)))
self.assertEqual(headers.get("connection"), "Keep-Alive")
self.assertEqual(response_body, tobytes(body))
# remote keeps connection open because it divined the content length
# from a length-1 list
self.sock.send(to_send)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0") | 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 _get_index_absolute_path(index):
return os.path.join(INDEXDIR, index) | 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 create_code_for_user(cls, user, next=None):
if not user.is_active:
return None
login_code = LoginCode(user=user)
if next is not None:
login_code.next = next
login_code.save()
return login_code | 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 feed_ratingindex():
off = request.args.get("offset") or 0
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
(db.Ratings.rating / 2).label('name')) \
.join(db.books_ratings_link)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(text('books_ratings_link.rating'))\
.order_by(db.Ratings.rating).all()
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries))
element = list()
for entry in entries:
element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name)))
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination) | 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 _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.message.Message()
for key, value in response_headers.items():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
try:
header_str = info.as_string()
except UnicodeEncodeError:
setattr(info, "_write_headers", _bind_write_headers(info))
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join(
[status_header.encode("utf-8"), header_str.encode("utf-8"), content]
)
cache.set(cachekey, text) | 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_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>'
) | 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_reset_extension_to_deleted_date(self):
"""
Test that we can delete a due date extension after deleting the normal
due date, without causing an error.
"""
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
'due_datetime': '12/30/2013 00:00'
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),
get_extended_due(self.course, self.week1, self.user1))
self.week1.due = None
self.week1 = self.store.update_item(self.week1, self.user1.id)
# Now, week1's normal due date is deleted but the extension still exists.
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
) | 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 __init__(self):
self.request = None
self.response = None
self.config = None
self.misp = None
self.event_json = None
self.event_tags = None | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def test_parse_header_11_te_chunked(self):
# NB: test that capitalization of header value is unimportant
data = b"GET /foobar HTTP/1.1\ntransfer-encoding: ChUnKed"
self.parser.parse_header(data)
self.assertEqual(self.parser.body_rcv.__class__.__name__, "ChunkedReceiver") | 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_entrance_exam_delete_state_with_staff(self):
""" Test entrance exam delete state failure with staff access. """
self.client.logout()
staff_user = StaffFactory(course_key=self.course.id)
self.client.login(username=staff_user.username, password='test')
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
'delete_module': True,
})
self.assertEqual(response.status_code, 403) | 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 _get_element_ptr_tuplelike(parent, key):
typ = parent.typ
assert isinstance(typ, TupleLike)
if isinstance(typ, StructType):
assert isinstance(key, str)
subtype = typ.members[key]
attrs = list(typ.tuple_keys())
index = attrs.index(key)
annotation = key
else:
assert isinstance(key, int)
subtype = typ.members[key]
attrs = list(range(len(typ.members)))
index = key
annotation = None
# generated by empty() + make_setter
if parent.value == "~empty":
return IRnode.from_list("~empty", typ=subtype)
if parent.value == "multi":
assert parent.encoding != Encoding.ABI, "no abi-encoded literals"
return parent.args[index]
ofst = 0 # offset from parent start
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
member_t = typ.members[attrs[index]]
for i in range(index):
member_abi_t = typ.members[attrs[i]].abi_type
ofst += member_abi_t.embedded_static_size()
return _getelemptr_abi_helper(parent, member_t, ofst)
if parent.location.word_addressable:
for i in range(index):
ofst += typ.members[attrs[i]].storage_size_in_words
elif parent.location.byte_addressable:
for i in range(index):
ofst += typ.members[attrs[i]].memory_bytes_required
else:
raise CompilerPanic(f"bad location {parent.location}") # pragma: notest
return IRnode.from_list(
add_ofst(parent, ofst),
typ=subtype,
location=parent.location,
encoding=parent.encoding,
annotation=annotation,
) | 0 | Python | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
def command(self):
res = self._gnupg().list_secret_keys()
return self._success("Searched for secret keys", res) | 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 __init__(self, hs):
super().__init__(hs)
self.clock = hs.get_clock()
self.client = hs.get_http_client()
self.key_servers = self.config.key_servers | 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 main(srcfile, dump_module=False):
argv0 = sys.argv[0]
components = argv0.split(os.sep)
argv0 = os.sep.join(components[-2:])
auto_gen_msg = common_msg % argv0
mod = asdl.parse(srcfile)
if dump_module:
print('Parsed Module:')
print(mod)
if not asdl.check(mod):
sys.exit(1)
if H_FILE:
with open(H_FILE, "w") as f:
f.write(auto_gen_msg)
f.write('#include "asdl.h"\n\n')
c = ChainOfVisitors(TypeDefVisitor(f),
StructVisitor(f),
PrototypeVisitor(f),
)
c.visit(mod)
f.write("PyObject* Ta3AST_mod2obj(mod_ty t);\n")
f.write("mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
f.write("int Ta3AST_Check(PyObject* obj);\n")
if C_FILE:
with open(C_FILE, "w") as f:
f.write(auto_gen_msg)
f.write('#include <stddef.h>\n')
f.write('\n')
f.write('#include "Python.h"\n')
f.write('#include "%s-ast.h"\n' % mod.name)
f.write('\n')
f.write("static PyTypeObject AST_type;\n")
v = ChainOfVisitors(
PyTypesDeclareVisitor(f),
PyTypesVisitor(f),
Obj2ModPrototypeVisitor(f),
FunctionVisitor(f),
ObjVisitor(f),
Obj2ModVisitor(f),
ASTModuleVisitor(f),
PartingShots(f),
)
v.visit(mod) | 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 _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def _load_from(self, data: bytes) -> None:
if data.strip() == b'':
data = XMP_EMPTY # on some platforms lxml chokes on empty documents
def basic_parser(xml):
return parse(BytesIO(xml))
def strip_illegal_bytes_parser(xml):
return parse(BytesIO(re_xml_illegal_bytes.sub(b'', xml)))
def recovery_parser(xml):
parser = XMLParser(recover=True)
return parse(BytesIO(xml), parser)
def replace_with_empty_xmp(_xml=None):
log.warning("Error occurred parsing XMP, replacing with empty XMP.")
return basic_parser(XMP_EMPTY)
if self.overwrite_invalid_xml:
parsers: Iterable[Callable] = [
basic_parser,
strip_illegal_bytes_parser,
recovery_parser,
replace_with_empty_xmp,
]
else:
parsers = [basic_parser]
for parser in parsers:
try:
self._xmp = parser(data)
except (XMLSyntaxError if self.overwrite_invalid_xml else NeverRaise) as e:
if str(e).startswith("Start tag expected, '<' not found") or str(
e
).startswith("Document is empty"):
self._xmp = replace_with_empty_xmp()
break
else:
break
try:
pis = self._xmp.xpath('/processing-instruction()')
for pi in pis:
etree.strip_tags(self._xmp, pi.tag)
self._get_rdf_root()
except (Exception if self.overwrite_invalid_xml else NeverRaise) as e:
log.warning("Error occurred parsing XMP", exc_info=e)
self._xmp = replace_with_empty_xmp()
return | 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 test_underscore_traversal(self):
t = self.folder.t
t.write('<p tal:define="p context/__class__" />')
with self.assertRaises(NotFound):
t()
t.write('<p tal:define="p nocall: random/_itertools/repeat"/>')
with self.assertRaises((NotFound, LocationError)):
t()
t.write('<p tal:content="random/_itertools/repeat/foobar"/>')
with self.assertRaises((NotFound, LocationError)):
t() | 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 execute_cmd(cmd, from_async=False):
"""execute a request as python module"""
for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
# override using the first hook
cmd = hook
break
# via server script
if run_server_script_api(cmd):
return None
try:
method = get_attr(cmd)
except Exception as e:
if frappe.local.conf.developer_mode:
raise e
else:
frappe.respond_as_web_page(title='Invalid Method', html='Method not found',
indicator_color='red', http_status_code=404)
return
if from_async:
method = method.queue
is_whitelisted(method)
is_valid_http_method(method)
return frappe.call(method, **frappe.form_dict) | 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_svg_data_links(self):
# Remove SVG images with potentially insecure content.
svg = b'<svg onload="alert(123)" />'
svgz = gzip.compress(svg)
svg_b64 = base64.b64encode(svg).decode('ASCII')
svgz_b64 = base64.b64encode(svgz).decode('ASCII')
urls = [
"data:image/svg+xml;base64," + svg_b64,
"data:image/svg+xml-compressed;base64," + svgz_b64,
]
for url in urls:
html = '<img src="%s">' % url
s = lxml.html.fragment_fromstring(html)
cleaned = lxml.html.tostring(clean_html(s))
self.assertEqual(
b'<img src="">',
cleaned,
"%s -> %s" % (url, cleaned)) | 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_win_inaccessible_ddir(self):
"""
create new defualt_dir if current one is not accessible
"""
tmpdir = tempfile.mkdtemp()
try:
d_dir = catalog.default_dir_win(tmpdir)
try:
os.chmod(d_dir, stat.S_IREAD | stat.S_IEXEC)
except OSError:
raise KnownFailureTest("Can't change permissions of default_dir.")
new_ddir = catalog.default_dir_win(tmpdir)
assert_(not os.path.samefile(new_ddir, d_dir))
new_ddir2 = catalog.default_dir_win(tmpdir)
assert_(os.path.samefile(new_ddir, new_ddir2))
finally:
os.chmod(d_dir, 0o700)
remove_tree(tmpdir) | 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 list_forum_members(request, course_id):
"""
Lists forum members of a certain rolename.
Limited to staff access.
The requesting user must be at least staff.
Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
which is limited to instructors.
Takes query parameter `rolename`.
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
course = get_course_by_id(course_id)
has_instructor_access = has_access(request.user, 'instructor', course)
has_forum_admin = has_forum_access(
request.user, course_id, FORUM_ROLE_ADMINISTRATOR
)
rolename = request.GET.get('rolename')
# default roles require either (staff & forum admin) or (instructor)
if not (has_forum_admin or has_instructor_access):
return HttpResponseBadRequest(
"Operation requires staff & forum admin or instructor access"
)
# EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
return HttpResponseBadRequest("Operation requires instructor access.")
# filter out unsupported for roles
if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]:
return HttpResponseBadRequest(strip_tags(
"Unrecognized rolename '{}'.".format(rolename)
))
try:
role = Role.objects.get(name=rolename, course_id=course_id)
users = role.users.all().order_by('username')
except Role.DoesNotExist:
users = []
def extract_user_info(user):
""" Convert user to dict for json rendering. """
return {
'username': user.username,
'email': user.email,
'first_name': user.first_name,
'last_name': user.last_name,
}
response_payload = {
'course_id': course_id.to_deprecated_string(),
rolename: map(extract_user_info, users),
}
return JsonResponse(response_payload) | 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 test_login_post(self):
login_code = LoginCode.objects.create(user=self.user, next='/private/')
response = self.client.post('/accounts/login/code/', {
'user': login_code.user.pk,
'code': login_code.code,
})
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '/private/')
self.assertEqual(response.wsgi_request.user, self.user)
self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists()) | 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 logical_volume_size(path):
"""Get logical volume size in bytes.
:param path: logical volume path
"""
# TODO(p-draigbrady) POssibly replace with the more general
# use of blockdev --getsize64 in future
out, _err = execute('lvs', '-o', 'lv_size', '--noheadings', '--units',
'b', '--nosuffix', path, run_as_root=True)
return int(out) | 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 test_list_course_role_members_staff(self):
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'rolename': 'staff',
})
self.assertEqual(response.status_code, 200)
# check response content
expected = {
'course_id': self.course.id.to_deprecated_string(),
'staff': [
{
'username': self.other_staff.username,
'email': self.other_staff.email,
'first_name': self.other_staff.first_name,
'last_name': self.other_staff.last_name,
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected) | 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 testMultiple(self):
with ops.Graph().as_default() as g:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(test.gpu_device_name()):
stager = data_flow_ops.MapStagingArea([dtypes.float32, dtypes.float32])
stage = stager.put(pi, [x, v], [0, 1])
k, (z, y) = stager.get(gi)
y = math_ops.reduce_max(z * math_ops.matmul(y, y))
g.finalize()
with self.session(graph=g) as sess:
sess.run(stage, feed_dict={x: -1, pi: 0})
for i in range(10):
_, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i})
self.assertAllClose(
4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4) | 1 | Python | CWE-843 | Access of Resource Using Incompatible Type ('Type Confusion') | The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type. | https://cwe.mitre.org/data/definitions/843.html | safe |
def __init__(self, private_key):
self.signer = Signer(private_key)
self.public_key = self.signer.public_key | 0 | Python | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
def test_certificates_features_csv(self):
"""
Test for certificate csv features.
"""
url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
url += '?csv=true'
# firstly generating downloadable certificates with 'honor' mode
certificate_count = 3
for __ in xrange(certificate_count):
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
current_date = datetime.date.today().strftime("%B %d, %Y")
response = self.client.get(url)
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv'))
self.assertEqual(
response.content.strip(),
'"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"'
+ str(self.course.id) + '","honor","3","' + current_date + '"'
) | 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 validate_request(self, request):
"""If configured for webhook basic auth, validate request has correct auth."""
if self.basic_auth:
basic_auth = get_request_basic_auth(request)
if basic_auth is None or basic_auth not in self.basic_auth:
# noinspection PyUnresolvedReferences
raise AnymailWebhookValidationFailure(
"Missing or invalid basic auth in Anymail %s webhook" % self.esp_name) | 0 | Python | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
def verify_cert_against_key(self, filename, key_filename):
"""
check that a certificate validates against its private key.
"""
cert = self.data + filename
key = self.data + key_filename
cmd = "openssl x509 -noout -modulus -in %s | openssl md5" % cert
cert_md5 = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read()
cmd = "openssl rsa -noout -modulus -in %s | openssl md5" % key
key_md5 = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read()
if cert_md5 == key_md5:
return True
return False | 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_equal_body(self):
# check server doesnt close connection when body is equal to
# cl header
to_send = tobytes(
"GET /equal_body HTTP/1.0\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: 0\r\n"
"\r\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
content_length = int(headers.get("content-length")) or None
self.assertEqual(content_length, 9)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(content_length, len(response_body))
self.assertEqual(response_body, tobytes("abcdefghi"))
# remote does not close connection (keepalive header)
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") | 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_list_entrance_exam_instructor_with_invalid_exam_key(self):
""" Test list task history for entrance exam failure if course has invalid exam. """
url = reverse('list_entrance_exam_instructor_tasks',
kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})
response = self.client.post(url, {
'unique_student_identifier': self.student.email,
})
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 testMultiple(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(test.gpu_device_name()):
stager = data_flow_ops.MapStagingArea([dtypes.float32, dtypes.float32])
stage = stager.put(pi, [x, v], [0, 1])
k, (z, y) = stager.get(gi)
y = math_ops.reduce_max(z * math_ops.matmul(y, y))
G.finalize()
with self.session(graph=G) as sess:
sess.run(stage, feed_dict={x: -1, pi: 0})
for i in range(10):
_, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i})
self.assertAllClose(
4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4) | 0 | Python | CWE-843 | Access of Resource Using Incompatible Type ('Type Confusion') | The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type. | https://cwe.mitre.org/data/definitions/843.html | vulnerable |
def get_auth(self, username=None, password=None):
basic_auth_header = "Basic " + b64encode(self.raw_auth.encode()).strip().decode('latin1')
return basic_auth(basic_auth_header) | 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 testProxyGET(self):
data = (
b"GET https://example.com:8080/foobar HTTP/8.4\r\n"
b"content-length: 6\r\n"
b"\r\n"
b"Hello."
)
parser = self.parser
self.feed(data)
self.assertTrue(parser.completed)
self.assertEqual(parser.version, "8.4")
self.assertFalse(parser.empty)
self.assertEqual(parser.headers, {"CONTENT_LENGTH": "6"})
self.assertEqual(parser.path, "/foobar")
self.assertEqual(parser.command, "GET")
self.assertEqual(parser.proxy_scheme, "https")
self.assertEqual(parser.proxy_netloc, "example.com:8080")
self.assertEqual(parser.command, "GET")
self.assertEqual(parser.query, "")
self.assertEqual(parser.get_body_stream().getvalue(), b"Hello.") | 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 sql_one_row(self, sentence, column):
self.cursor.execute(sentence)
return self.cursor.fetchone()[column] | 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 _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return 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 test_siblings_cant_talk(router):
l1 = router.local()
l2 = router.local()
logs = testlib.LogCapturer()
logs.start()
try:
l2.call(ping_context, l1)
except mitogen.core.CallError:
e = sys.exc_info()[1]
msg = mitogen.core.Router.unidirectional_msg % (
l2.context_id,
l1.context_id,
)
assert msg in str(e)
assert 'routing mode prevents forward of ' in logs.stop() | 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_recursive_tf_function_call_each_other_with_gradients(self):
@def_function.function
def recursive_fn1(n, x):
if n <= 1:
return x
return n * recursive_fn2(n - 1, x)
@def_function.function
def recursive_fn2(n, x):
if n <= 1:
return 2 * x
return n * recursive_fn1(n - 1, x)
x = variables.Variable(1.0)
with backprop.GradientTape() as tape:
g1 = recursive_fn1(5, x)
dg1_dx = tape.gradient(g1, x)
self.assertEqual(dg1_dx.numpy(), 120)
with backprop.GradientTape() as tape:
g2 = recursive_fn2(5, x)
dg2_dx = tape.gradient(g2, x)
self.assertEqual(dg2_dx.numpy(), 240) | 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 aesDecrypt(data, key):
cipher = AES.new(key)
return cipher.decrypt(data).rstrip() | 0 | Python | CWE-310 | Cryptographic Issues | Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed. | https://cwe.mitre.org/data/definitions/310.html | vulnerable |
def test_entrance_exam_reset_student_attempts_nonsense(self):
""" Test failure with both unique_student_identifier and all_students. """
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course.id)})
response = self.client.post(url, {
'unique_student_identifier': self.student.email,
'all_students': True,
})
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):
self.mock_federation = Mock()
self.mock_registry = Mock()
self.query_handlers = {}
def register_query_handler(query_type, handler):
self.query_handlers[query_type] = handler
self.mock_registry.register_query_handler = register_query_handler
hs = yield setup_test_homeserver(
self.addCleanup,
federation_http_client=None,
resource_for_federation=Mock(),
federation_client=self.mock_federation,
federation_server=Mock(),
federation_registry=self.mock_registry,
)
self.store = hs.get_datastore()
self.frank = UserID.from_string("@1234ABCD:test")
self.bob = UserID.from_string("@4567:test")
self.alice = UserID.from_string("@alice:remote")
yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart))
self.handler = hs.get_profile_handler()
self.hs = 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 __init__(self, bot):
super().__init__()
self.bot = bot
self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True)
self.config.register_global(custom={}, tenorkey=None)
self.config.register_guild(custom={})
self.try_after = None
| 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 |
bool AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride,
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) {
return AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width,
pad_height, filter_width, filter_height,
output_activation_min, output_activation_max,
output_data, output_dims);
} | 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 test_basic():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=3) as uri:
response, content = http.request(uri, "GET")
assert response.status == 401
http.add_credentials("joe", password)
response, content = http.request(uri, "GET")
assert response.status == 200 | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
def makeTrustRoot(self):
# If this option is specified, use a specific root CA cert. This is useful for testing when it's not
# practical to get the client cert signed by a real root CA but should never be used on a production server.
caCertFilename = self.sydent.cfg.get('http', 'replication.https.cacert')
if len(caCertFilename) > 0:
try:
fp = open(caCertFilename)
caCert = twisted.internet.ssl.Certificate.loadPEM(fp.read())
fp.close()
except:
logger.warn("Failed to open CA cert file %s", caCertFilename)
raise
logger.warn("Using custom CA cert file: %s", caCertFilename)
return twisted.internet._sslverify.OpenSSLCertificateAuthorities([caCert.original])
else:
return twisted.internet.ssl.OpenSSLDefaultPaths() | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
def __init__(self, protocol='http', hostname='localhost', port='8080',
subsystem=None, accept='application/json',
trust_env=None, verify=False): | 0 | Python | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
def author_list():
if current_user.check_visibility(constants.SIDEBAR_AUTHOR):
if current_user.get_view_property('author', 'dir') == 'desc':
order = db.Authors.sort.desc()
order_no = 0
else:
order = db.Authors.sort.asc()
order_no = 1
entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(text('books_authors_link.author')).order_by(order).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all()
# If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name
# starts a change session
autor_copy = copy.deepcopy(entries)
for entry in autor_copy:
entry.Authors.name = entry.Authors.name.replace('|', ',')
return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist,
title=u"Authors", page="authorlist", data='author', 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 _inject_file_into_fs(fs, path, contents):
absolute_path = os.path.join(fs, path.lstrip('/'))
parent_dir = os.path.dirname(absolute_path)
utils.execute('mkdir', '-p', parent_dir, run_as_root=True)
utils.execute('tee', absolute_path, process_input=contents,
run_as_root=True) | 0 | Python | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.