code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
def handle_protectederror(obj_list, request, e):
"""
Generate a user-friendly error message in response to a ProtectedError exception.
"""
protected_objects = list(e.protected_objects)
protected_count = len(protected_objects) if len(protected_objects) <= 50 else "More than 50"
err_message = (
f"Unable to delete <strong>{', '.join(str(obj) for obj in obj_list)}</strong>. "
f"{protected_count} dependent objects were found: "
)
# Append dependent objects to error message
dependent_objects = []
for dependent in protected_objects[:50]:
if hasattr(dependent, "get_absolute_url"):
dependent_objects.append(f'<a href="{dependent.get_absolute_url()}">{escape(dependent)}</a>')
else:
dependent_objects.append(str(dependent))
err_message += ", ".join(dependent_objects)
messages.error(request, mark_safe(err_message)) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 post(self, request, pk):
virtual_chassis = get_object_or_404(self.queryset, pk=pk)
member_select_form = forms.VCMemberSelectForm(request.POST)
if member_select_form.is_valid():
device = member_select_form.cleaned_data["device"]
device.virtual_chassis = virtual_chassis
data = {k: request.POST[k] for k in ["vc_position", "vc_priority"]}
membership_form = forms.DeviceVCMembershipForm(data=data, validate_vc_position=True, instance=device)
if membership_form.is_valid():
membership_form.save()
msg = f'Added member <a href="{device.get_absolute_url()}">{escape(device)}</a>'
messages.success(request, mark_safe(msg))
if "_addanother" in request.POST:
return redirect(request.get_full_path())
return redirect(self.get_return_url(request, device))
else:
membership_form = forms.DeviceVCMembershipForm(data=request.POST)
return render(
request,
"dcim/virtualchassis_add_member.html",
{
"virtual_chassis": virtual_chassis,
"member_select_form": member_select_form,
"membership_form": membership_form,
"return_url": self.get_return_url(request, virtual_chassis),
},
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 render_description(self, record):
if record.description:
return mark_safe(render_markdown(record.description))
return self.default | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 computed_fields(context, obj, advanced_ui=None):
"""
Render all applicable links for the given object.
This can also check whether the advanced_ui attribute is True or False for UI display purposes.
"""
fields = obj.get_computed_fields(label_as_key=True, advanced_ui=advanced_ui)
if not computed_fields:
return ""
template_code = ""
for label, value in fields.items():
escaped_label = escape(label)
template_code += f"""
<tr>
<td><span title="{escaped_label}">{escaped_label}</span></td>
<td>{escape(value)}</td>
<tr>
"""
return mark_safe(template_code) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_registered_content(obj, method, template_context, return_html=True):
"""
Given an object and a TemplateExtension method name and the template context, return all the
registered content for the object's model.
"""
context = {
"object": obj,
"request": template_context["request"],
"settings": template_context["settings"],
"csrf_token": template_context["csrf_token"],
"perms": template_context["perms"],
}
model_name = obj._meta.label_lower
template_extensions = registry["plugin_template_extensions"].get(model_name, [])
objects = []
html = ""
for template_extension in template_extensions:
# If the class has not overridden the specified method, we can skip it (because we know it
# will raise NotImplementedError).
if getattr(template_extension, method) == getattr(TemplateExtension, method):
continue
# Update context with plugin-specific configuration parameters
plugin_name = template_extension.__module__.split(".")[0]
context["config"] = settings.PLUGINS_CONFIG.get(plugin_name, {})
# Call the method to render content
instance = template_extension(context)
content = getattr(instance, method)()
if not return_html:
for i, content in enumerate(content):
objects.append({f"{plugin_name}:{i+1}": content})
else:
html += content
if not return_html:
return objects
return mark_safe(html) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_custom_field_table_render(self):
queryset = Location.objects.filter(name=self.location.name)
location_table = LocationTable(queryset)
custom_column_expected = {
"text_field": "bar",
"number_field": "456",
"boolean_field": '<span class="text-success"><i class="mdi mdi-check-bold" title="Yes"></i></span>',
"date_field": "2020-01-02",
"url_field": '<a href="http://example.com/2">http://example.com/2</a>',
"choice_field": '<span class="label label-default">Bar</span>',
"multi_choice_field": (
'<span class="label label-default">Bar</span> <span class="label label-default">Baz</span> '
),
}
bound_row = location_table.rows[0]
for col_name, col_expected_value in custom_column_expected.items():
internal_col_name = "cf_" + col_name
custom_column = location_table.base_columns.get(internal_col_name)
self.assertIsNotNone(custom_column)
self.assertIsInstance(custom_column, CustomFieldColumn)
rendered_value = bound_row.get_cell(internal_col_name)
self.assertEqual(rendered_value, col_expected_value) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 post(self, request, pk):
post_data = request.POST
job_button = JobButton.objects.get(pk=pk)
job_model = job_button.job
result = JobResult.enqueue_job(
job_model=job_model,
user=request.user,
object_pk=post_data["object_pk"],
object_model_name=post_data["object_model_name"],
)
msg = f'Job enqueued. <a href="{result.get_absolute_url()}">Click here for the results.</a>'
messages.info(request=request, message=mark_safe(msg))
return redirect(post_data["redirect_path"]) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 render_markdown(value):
"""
Render text as Markdown
Example:
{{ text | render_markdown }}
"""
# Strip HTML tags
value = strip_tags(value)
# Sanitize Markdown links
schemes = "|".join(settings.ALLOWED_URL_SCHEMES)
pattern = rf"\[(.+)\]\((?!({schemes})).*:(.+)\)"
value = re.sub(pattern, "[\\1](\\3)", value, flags=re.IGNORECASE)
# Render Markdown
html = markdown(value, extensions=["fenced_code", "tables"])
return mark_safe(html) # noqa: S308 # suspicious-mark-safe-usage, OK here since we sanitized the string earlier | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_support_message(self):
"""Test the `support_message` tag with config and settings."""
with override_settings():
del settings.SUPPORT_MESSAGE
with override_config():
self.assertHTMLEqual(
helpers.support_message(),
"<p>If further assistance is required, please join the <code>#nautobot</code> channel "
'on <a href="https://slack.networktocode.com/">Network to Code\'s Slack community</a> '
"and post your question.</p>",
)
with override_config(SUPPORT_MESSAGE="Reach out to your support team for assistance."):
self.assertHTMLEqual(
helpers.support_message(),
"<p>Reach out to your support team for assistance.</p>",
)
with override_settings(SUPPORT_MESSAGE="Settings **support** message:\n\n- Item 1\n- Item 2"):
with override_config(SUPPORT_MESSAGE="Config support message"):
self.assertHTMLEqual(
helpers.support_message(),
"<p>Settings <strong>support</strong> message:</p><ul><li>Item 1</li><li>Item 2</li></ul>",
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_render_markdown(self):
self.assertTrue(callable(helpers.render_markdown))
# Test common markdown formatting.
self.assertEqual(helpers.render_markdown("**bold**"), "<p><strong>bold</strong></p>")
self.assertEqual(helpers.render_markdown("__bold__"), "<p><strong>bold</strong></p>")
self.assertEqual(helpers.render_markdown("_italics_"), "<p><em>italics</em></p>")
self.assertEqual(helpers.render_markdown("*italics*"), "<p><em>italics</em></p>")
self.assertEqual(
helpers.render_markdown("**bold and _italics_**"), "<p><strong>bold and <em>italics</em></strong></p>"
)
self.assertEqual(helpers.render_markdown("* list"), "<ul>\n<li>list</li>\n</ul>")
self.assertEqual(
helpers.render_markdown("[I am a link](https://www.example.com)"),
'<p><a href="https://www.example.com">I am a link</a></p>',
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_500_custom_support_message(self, mock_get):
"""Nautobot's custom 500 page should be used and should include a default support message."""
url = reverse("home")
with self.assertTemplateUsed("500.html"):
self.client.raise_request_exception = False
response = self.client.get(url)
self.assertNotContains(response, "Network to Code", status_code=500)
response_content = response.content.decode(response.charset)
self.assertInHTML("Hello world!", response_content) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_404_default_support_message(self):
"""Nautobot's custom 404 page should be used and should include a default support message."""
with self.assertTemplateUsed("404.html"):
response = self.client.get("/foo/bar")
self.assertContains(response, "Network to Code", status_code=404)
response_content = response.content.decode(response.charset)
self.assertInHTML(
"If further assistance is required, please join the <code>#nautobot</code> channel "
'on <a href="https://slack.networktocode.com/">Network to Code\'s Slack community</a> '
"and post your question.",
response_content,
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_500_default_support_message(self, mock_get):
"""Nautobot's custom 500 page should be used and should include a default support message."""
url = reverse("home")
with self.assertTemplateUsed("500.html"):
self.client.raise_request_exception = False
response = self.client.get(url)
self.assertContains(response, "Network to Code", status_code=500)
response_content = response.content.decode(response.charset)
self.assertInHTML(
"If further assistance is required, please join the <code>#nautobot</code> channel "
'on <a href="https://slack.networktocode.com/">Network to Code\'s Slack community</a> '
"and post your question.",
response_content,
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 testConv3DTransposeShapeMismatch(self):
# Test case for GitHub issue 18460
x_shape = [2, 2, 3, 4, 3]
f_shape = [3, 3, 3, 2, 2]
y_shape = [2, 2, 6, 8, 6]
strides = [1, 1, 2, 2, 2]
np.random.seed(1)
x_value = np.random.random_sample(x_shape).astype(np.float64)
f_value = np.random.random_sample(f_shape).astype(np.float64)
nn_ops.conv3d_transpose(
x_value, f_value, y_shape, strides, data_format='NCDHW') | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def testPoolingRatioValueOutOfRange(self):
with self.cached_session() as _:
# Whether turn on `TF2_BEHAVIOR` generates different error messages
with self.assertRaisesRegex(
(errors.InvalidArgumentError, ValueError),
r"(pooling_ratio cannot be smaller than 1, got: .*)|(is negative)"):
result = nn_ops.gen_nn_ops.fractional_avg_pool(
value=np.zeros([3, 30, 30, 3]),
pooling_ratio=[1, -1, 3, 1],
pseudo_random=False,
overlapping=False,
deterministic=False,
seed=0,
seed2=0,
)
self.evaluate(result) | 0 | Python | CWE-415 | Double Free | The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. | https://cwe.mitre.org/data/definitions/415.html | vulnerable |
def testPoolingRatioValueOutOfRange(self):
with self.cached_session() as _:
# Whether turn on `TF2_BEHAVIOR` generates different error messages
with self.assertRaisesRegex(
(errors.InvalidArgumentError, ValueError),
r"(pooling_ratio cannot be smaller than 1, got: .*)|(is negative)"):
result = nn_ops.gen_nn_ops.fractional_max_pool(
value=np.zeros([3, 30, 30, 3]),
pooling_ratio=[1, -1, 3, 1],
pseudo_random=False,
overlapping=False,
deterministic=False,
seed=0,
seed2=0,
)
self.evaluate(result) | 0 | Python | CWE-415 | Double Free | The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. | https://cwe.mitre.org/data/definitions/415.html | vulnerable |
def testSnapshotRecoveryFailsWithBadSplitNames(self, bad_split_filename):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), bad_split_filename))
with self.assertRaisesRegex(ValueError, "can't parse"):
cluster.restart_dispatcher() | 0 | Python | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
def testSnapshotRecoveryFailsWithOutOfOrderSplitName(self):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), "split_1_0"))
with self.assertRaisesRegex(ValueError, "found conflict"):
cluster.restart_dispatcher() | 0 | Python | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
def testParallelConcatShapeZero(self):
if not tf2.enabled():
self.skipTest("only fails in TF2")
@def_function.function
def f():
y = gen_array_ops.parallel_concat(values=[["tf"]], shape=0)
return y
with self.assertRaisesRegex(errors.InvalidArgumentError,
r"0th dimension of value .* is less than"):
f() | 0 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
def create_ssh_cred() -> None:
from jinja2 import Environment, FileSystemLoader
user_group = roxywi_common.get_user_group()
name = common.checkAjaxInput(form.getvalue('new_ssh'))
name = f'{name}_{user_group}'
enable = common.checkAjaxInput(form.getvalue('ssh_enable'))
group = common.checkAjaxInput(form.getvalue('new_group'))
username = common.checkAjaxInput(form.getvalue('ssh_user'))
password = common.checkAjaxInput(form.getvalue('ssh_pass'))
page = common.checkAjaxInput(form.getvalue('page'))
page = page.split("#")[0]
lang = roxywi_common.get_user_lang()
if username is None or name is None:
print(error_mess)
else:
if sql.insert_new_ssh(name, enable, group, username, password):
env = Environment(loader=FileSystemLoader('templates/'), autoescape=True)
template = env.get_template('ajax/new_ssh.html')
output_from_parsed_template = template.render(groups=sql.select_groups(), sshs=sql.select_ssh(name=name), page=page, lang=lang)
print(output_from_parsed_template)
roxywi_common.logging('Roxy-WI server', f'New SSH credentials {name} has been created', roxywi=1, login=1) | 0 | Python | CWE-668 | Exposure of Resource to Wrong Sphere | The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource. | https://cwe.mitre.org/data/definitions/668.html | vulnerable |
def extract_ip_or_domain(url):
ip_regex = re.compile("^(?:http://|https://)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})")
domain_regex = re.compile("^(?:http://|https://)([a-zA-Z0-9.-]+)")
match = ip_regex.findall(url)
if len(match):
ip_address = match[0]
try:
ipaddress.ip_address(ip_address) # Validate the IP address
return ip_address
except ValueError:
pass
match = domain_regex.findall(url)
if len(match):
return match[0]
return None | 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 webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
print(request.body)
return HttpResponse("[accepted]") | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
configuration = {item["name"]: item["value"] for item in self.configuration}
self.config = GatewayConfig(
gateway_name=GATEWAY_NAME,
auto_capture=True, # FIXME check this
supported_currencies=configuration["Supported currencies"],
connection_params={
"api_key": configuration["API key"],
"merchant_account": configuration["Merchant Account"],
"return_url": configuration["Return Url"],
"origin_key": configuration["Origin Key"],
"origin_url": configuration["Origin Url"],
},
)
api_key = self.config.connection_params["api_key"]
self.adyen = Adyen.Adyen(xapikey=api_key) | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def create_transaction(
payment: Payment,
kind: str,
payment_information: PaymentData,
action_required: bool = False,
gateway_response: GatewayResponse = None,
error_msg=None,
) -> Transaction:
"""Create a transaction based on transaction kind and gateway response."""
# Default values for token, amount, currency are only used in cases where
# response from gateway was invalid or an exception occured
if not gateway_response:
gateway_response = GatewayResponse(
kind=kind,
action_required=False,
transaction_id=payment_information.token,
is_success=False,
amount=payment_information.amount,
currency=payment_information.currency,
error=error_msg,
raw_response={},
)
txn = Transaction.objects.create(
payment=payment,
action_required=action_required,
kind=gateway_response.kind,
token=gateway_response.transaction_id,
is_success=gateway_response.is_success,
amount=gateway_response.amount,
currency=gateway_response.currency,
error=gateway_response.error,
customer_id=gateway_response.customer_id,
gateway_response=gateway_response.raw_response or {},
action_required_data=gateway_response.action_required_data or {},
)
return txn | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def gateway_postprocess(transaction, payment):
if not transaction.is_success:
return
if transaction.action_required:
payment.to_confirm = True
payment.save(update_fields=["to_confirm"])
return
transaction_kind = transaction.kind
# if transaction.action_required:
# payment.charge_status = ChargeStatus.ACTION_REQUIRED
# payment.save(update_fields=["charge_status", ])
if transaction_kind in {TransactionKind.CAPTURE, TransactionKind.CONFIRM}:
payment.captured_amount += transaction.amount
# Set payment charge status to fully charged
# only if there is no more amount needs to charge
payment.charge_status = ChargeStatus.PARTIALLY_CHARGED
if payment.get_charge_amount() <= 0:
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.save(update_fields=["charge_status", "captured_amount", "modified"])
elif transaction_kind == TransactionKind.VOID:
payment.is_active = False
payment.save(update_fields=["is_active", "modified"])
elif transaction_kind == TransactionKind.REFUND:
changed_fields = ["captured_amount", "modified"]
payment.captured_amount -= transaction.amount
payment.charge_status = ChargeStatus.PARTIALLY_REFUNDED
if payment.captured_amount <= 0:
payment.charge_status = ChargeStatus.FULLY_REFUNDED
payment.is_active = False
changed_fields += ["charge_status", "is_active"]
payment.save(update_fields=changed_fields)
elif transaction_kind == TransactionKind.PENDING:
payment.charge_status = ChargeStatus.PENDING
payment.save(
update_fields=["charge_status",]
) | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def test_account_reset_password_user_is_inactive(
mocked_notify, user_api_client, customer_user, channel_USD
):
user = customer_user
user.is_active = False
user.save()
variables = {
"email": customer_user.email,
"redirectUrl": "https://www.example.com",
"channel": channel_USD.slug,
}
response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
results = response.json()
assert "errors" in results
assert (
results["errors"][0]["message"]
== "Invalid token. User does not exist or is inactive."
)
assert not mocked_notify.called | 0 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | vulnerable |
def mutate(cls, root, info: ResolveInfo, **data):
disallow_replica_in_context(info.context)
setup_context_user(info.context)
if not cls.check_permissions(info.context, data=data):
raise PermissionDenied(permissions=cls._meta.permissions)
manager = get_plugin_manager_promise(info.context).get()
result = manager.perform_mutation(
mutation_cls=cls, root=root, info=info, data=data
)
if result is not None:
return result
try:
response = cls.perform_mutation(root, info, **data)
if response.errors is None:
response.errors = []
return response
except ValidationError as e:
return cls.handle_errors(e) | 0 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | vulnerable |
def test_graphql_execution_exception(monkeypatch, api_client):
def mocked_execute(*args, **kwargs):
raise IOError("Spanish inquisition")
monkeypatch.setattr("graphql.backend.core.execute_and_validate", mocked_execute)
response = api_client.post_graphql("{ shop { name }}")
assert response.status_code == 400
content = get_graphql_content_from_response(response)
assert content["errors"][0]["message"] == "Spanish inquisition" | 0 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | vulnerable |
async def test_secure_channel_key_expiration(srv_crypto_one_cert, mocker):
timeout = 1
_, cert = srv_crypto_one_cert
clt = Client(uri_crypto_cert)
clt.secure_channel_timeout = timeout * 1000
user_cert = uacrypto.CertProperties(peer_creds['certificate'], "DER")
user_key = uacrypto.CertProperties(
path=peer_creds['private_key'],
extension="PEM",
)
server_cert = uacrypto.CertProperties(cert)
await clt.set_security(
security_policies.SecurityPolicyBasic256Sha256,
user_cert,
user_key,
server_certificate=server_cert,
mode=ua.MessageSecurityMode.SignAndEncrypt
)
async with clt:
assert clt.uaclient.security_policy.symmetric_cryptography.Prev_Verifier is None
assert clt.uaclient.security_policy.symmetric_cryptography.Prev_Decryptor is None
await asyncio.sleep(timeout * 1.2)
sym_crypto = clt.uaclient.security_policy.symmetric_cryptography
prev_verifier = sym_crypto.Prev_Verifier
prev_decryptor = sym_crypto.Prev_Decryptor
assert isinstance(prev_verifier, Verifier)
assert isinstance(prev_decryptor, Decryptor)
mock_decry_reset = mocker.patch.object(prev_verifier, "reset", wraps=prev_verifier.reset)
mock_verif_reset = mocker.patch.object(prev_decryptor, "reset", wraps=prev_decryptor.reset)
assert mock_decry_reset.call_count == 0
assert mock_verif_reset.call_count == 0
await asyncio.sleep(timeout * 0.3)
assert await clt.get_objects_node().get_children()
assert sym_crypto.key_expiration > 0
assert sym_crypto.prev_key_expiration > 0
assert sym_crypto.key_expiration > sym_crypto.prev_key_expiration
assert mock_decry_reset.call_count == 1
assert mock_verif_reset.call_count == 1
assert clt.uaclient.security_policy.symmetric_cryptography.Prev_Verifier is None
assert clt.uaclient.security_policy.symmetric_cryptography.Prev_Decryptor is None | 0 | Python | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
def data_received(self, data):
self._buffer += data
# try to parse the incoming data
while self._buffer:
try:
buf = Buffer(self._buffer)
try:
header = header_from_binary(buf)
except NotEnoughData:
logger.debug('Not enough data while parsing header from client, waiting for more')
return
if len(buf) < header.body_size:
logger.debug('We did not receive enough data from client. Need %s got %s', header.body_size,
len(buf))
return
# we have a complete message
self.messages.put_nowait((header, buf))
self._buffer = self._buffer[(header.header_size + header.body_size):]
except Exception:
logger.exception('Exception raised while parsing message from client')
return | 0 | Python | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
def render(
self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping
) -> str:
"""Takes token stream and generates HTML.
:param tokens: list on block tokens to render
:param options: params of parser instance
:param env: additional data from parsed input
"""
result = ""
for i, token in enumerate(tokens):
if token.type == "inline":
assert token.children is not None
result += self.renderInline(token.children, options, env)
elif token.type in self.rules:
result += self.rules[token.type](tokens, i, options, env)
else:
result += self.renderToken(tokens, i, options, env)
return result | 0 | 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 | vulnerable |
def renderInlineAsText(
self,
tokens: Sequence[Token] | None,
options: OptionsDict,
env: MutableMapping,
) -> str:
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with stripped markup,
instead of simple escaping.
:param tokens: list on block tokens to render
:param options: params of parser instance
:param env: additional data from parsed input
"""
result = ""
for token in tokens or []:
if token.type == "text":
result += token.content
elif token.type == "image":
assert token.children is not None
result += self.renderInlineAsText(token.children, options, env)
elif token.type == "softbreak":
result += "\n"
return result | 0 | 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 | vulnerable |
def image(
self,
tokens: Sequence[Token],
idx: int,
options: OptionsDict,
env: MutableMapping,
) -> str:
token = tokens[idx]
# "alt" attr MUST be set, even if empty. Because it's mandatory and
# should be placed on proper position for tests.
assert (
token.attrs and "alt" in token.attrs
), '"image" token\'s attrs must contain `alt`'
# Replace content with actual value
token.attrSet("alt", self.renderInlineAsText(token.children, options, env))
return self.renderToken(tokens, idx, options, env) | 0 | 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 | vulnerable |
def replace(state: StateCore) -> None:
if not state.md.options.typographer:
return
for token in state.tokens:
if token.type != "inline":
continue
assert token.children is not None
if SCOPED_ABBR_RE.search(token.content):
replace_scoped(token.children)
if RARE_RE.search(token.content):
replace_rare(token.children) | 0 | 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 | vulnerable |
def smartquotes(state: StateCore) -> None:
if not state.md.options.typographer:
return
for token in state.tokens:
if token.type != "inline" or not QUOTE_RE.search(token.content):
continue
assert token.children is not None
process_inlines(token.children, state) | 0 | 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 | vulnerable |
def convert_file(filename: str) -> None:
"""
Parse a Markdown file and dump the output to stdout.
"""
try:
with open(filename, "r") as fin:
rendered = MarkdownIt().render(fin.read())
print(rendered, end="")
except OSError:
sys.stderr.write(f'Cannot open file "{filename}".\n')
sys.exit(1) | 0 | 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 | vulnerable |
def get(self, path: str) -> None:
parts = path.split("/")
component_name = parts[0]
component_root = self._registry.get_component_path(component_name)
if component_root is None:
self.write(f"{path} not found")
self.set_status(404)
return
filename = "/".join(parts[1:])
abspath = os.path.join(component_root, filename)
LOGGER.debug("ComponentRequestHandler: GET: %s -> %s", path, abspath)
try:
with open(abspath, "r", encoding="utf-8") as file:
contents = file.read()
except (OSError, UnicodeDecodeError) as e:
self.write(f"{path} read error: {e}")
self.set_status(404)
return
self.write(contents)
self.set_header("Content-Type", self.get_content_type(abspath))
self.set_extra_headers(path) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 validate_absolute_path(self, root, absolute_path):
try:
media_file_manager.get(absolute_path)
except KeyError:
LOGGER.error("MediaFileManager: Missing file %s" % absolute_path)
raise tornado.web.HTTPError(404, "%s not found", absolute_path)
return absolute_path | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_invalid_content_request(self):
"""Test request failure when invalid content (file) is provided."""
with mock.patch("streamlit.components.v1.components.os.path.isdir"):
declare_component("test", path=PATH)
with mock.patch("streamlit.components.v1.components.open") as m:
m.side_effect = OSError("Invalid content")
response = self._request_component("components_test.test")
self.assertEqual(404, response.code)
self.assertEqual(
b"components_test.test read error: Invalid content",
response.body,
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_invalid_component_request(self):
"""Test request failure when invalid component name is provided."""
response = self._request_component("invalid_component")
self.assertEqual(404, response.code)
self.assertEqual(b"invalid_component not found", response.body) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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_invalid_encoding_request(self):
"""Test request failure when invalid encoded file is provided."""
with mock.patch("streamlit.components.v1.components.os.path.isdir"):
declare_component("test", path=PATH)
with mock.patch("streamlit.components.v1.components.open") as m:
m.side_effect = UnicodeDecodeError(
"utf-8", b"", 9, 11, "unexpected end of data"
)
response = self._request_component("components_test.test")
self.assertEqual(404, response.code)
self.assertEqual(
b"components_test.test read error: 'utf-8' codec can't decode bytes in position 9-10: unexpected end of data",
response.body,
) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 convert(cls, bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False,
invert_images=False, write_to=None, output_width=None,
output_height=None, **kwargs):
"""Convert an SVG document to the format for this class.
Specify the input by passing one of these:
:param bytestring: The SVG source as a byte-string.
:param file_obj: A file-like object.
:param url: A filename.
Give some options:
:param dpi: The ratio between 1 inch and 1 pixel.
:param parent_width: The width of the parent container in pixels.
:param parent_height: The height of the parent container in pixels.
:param scale: The ouptut scaling factor.
:param unsafe: A boolean allowing XML entities and very large files
(WARNING: vulnerable to XXE attacks and various DoS).
Specifiy the output with:
:param write_to: The filename of file-like object where to write the
output. If None or not provided, return a byte string.
Only ``bytestring`` can be passed as a positional argument, other
parameters are keyword-only.
"""
tree = Tree(
bytestring=bytestring, file_obj=file_obj, url=url, unsafe=unsafe,
**kwargs)
output = write_to or io.BytesIO()
instance = cls(
tree, output, dpi, None, parent_width, parent_height, scale,
output_width, output_height, background_color,
map_rgba=negate_color if negate_colors else None,
map_image=invert_image if invert_images else None)
instance.finish()
if write_to is None:
return output.getvalue() | 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 download_url(url, proxies=None):
"""
Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is
for deprecated behavior allowing to download config/models with a single url instead of using the Hub.
Args:
url (`str`): The url of the file to download.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
Returns:
`str`: The location of the temporary file where the url was downloaded.
"""
warnings.warn(
f"Using `from_pretrained` with the url of a file (here {url}) is deprecated and won't be possible anymore in"
" v5 of Transformers. You should host your file on the Hub (hf.co) instead and use the repository ID. Note"
" that this is not compatible with the caching system (your file will be downloaded at each execution) or"
" multiple processes (each process will download the file in a different temporary file)."
)
tmp_file = tempfile.mktemp()
with open(tmp_file, "wb") as f:
http_get(url, f, proxies=proxies)
return tmp_file | 0 | Python | CWE-377 | Insecure Temporary File | Creating and using insecure temporary files can leave application and system data vulnerable to attack. | https://cwe.mitre.org/data/definitions/377.html | vulnerable |
def test_legacy_index_retriever_retrieve(self):
n_docs = 1
retriever = self.get_dummy_legacy_index_retriever()
hidden_states = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
)
retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(doc_dicts), 2)
self.assertEqual(sorted(doc_dicts[0]), ["text", "title"])
self.assertEqual(len(doc_dicts[0]["text"]), n_docs)
self.assertEqual(doc_dicts[0]["text"][0], "bar") # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]["text"][0], "foo") # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist(), [[1], [0]]) | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def test_legacy_index_retriever_retrieve(self):
n_docs = 1
retriever = self.get_dummy_legacy_index_retriever()
hidden_states = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
)
retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(doc_dicts), 2)
self.assertEqual(sorted(doc_dicts[0]), ["text", "title"])
self.assertEqual(len(doc_dicts[0]["text"]), n_docs)
self.assertEqual(doc_dicts[0]["text"][0], "bar") # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]["text"][0], "foo") # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist(), [[1], [0]]) | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def get_dummy_legacy_index_retriever(self):
dataset = Dataset.from_dict(
{
"id": ["0", "1"],
"text": ["foo", "bar"],
"title": ["Foo", "Bar"],
"embeddings": [np.ones(self.retrieval_vector_size + 1), 2 * np.ones(self.retrieval_vector_size + 1)],
}
)
dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
index_file_name = os.path.join(self.tmpdirname, "hf_bert_base.hnswSQ8_correct_phi_128.c_index")
dataset.save_faiss_index("embeddings", index_file_name + ".index.dpr")
pickle.dump(dataset["id"], open(index_file_name + ".index_meta.dpr", "wb"))
passages_file_name = os.path.join(self.tmpdirname, "psgs_w100.tsv.pkl")
passages = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
pickle.dump(passages, open(passages_file_name, "wb"))
config = RagConfig(
retrieval_vector_size=self.retrieval_vector_size,
question_encoder=DPRConfig().to_dict(),
generator=BartConfig().to_dict(),
index_name="legacy",
index_path=self.tmpdirname,
)
retriever = RagRetriever(
config, question_encoder_tokenizer=self.get_dpr_tokenizer(), generator_tokenizer=self.get_bart_tokenizer()
)
return retriever | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def get_dummy_legacy_index_retriever(self):
dataset = Dataset.from_dict(
{
"id": ["0", "1"],
"text": ["foo", "bar"],
"title": ["Foo", "Bar"],
"embeddings": [np.ones(self.retrieval_vector_size + 1), 2 * np.ones(self.retrieval_vector_size + 1)],
}
)
dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
index_file_name = os.path.join(self.tmpdirname, "hf_bert_base.hnswSQ8_correct_phi_128.c_index")
dataset.save_faiss_index("embeddings", index_file_name + ".index.dpr")
pickle.dump(dataset["id"], open(index_file_name + ".index_meta.dpr", "wb"))
passages_file_name = os.path.join(self.tmpdirname, "psgs_w100.tsv.pkl")
passages = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
pickle.dump(passages, open(passages_file_name, "wb"))
config = RagConfig(
retrieval_vector_size=self.retrieval_vector_size,
question_encoder=DPRConfig().to_dict(),
generator=BartConfig().to_dict(),
index_name="legacy",
index_path=self.tmpdirname,
)
retriever = RagRetriever(
config, question_encoder_tokenizer=self.get_dpr_tokenizer(), generator_tokenizer=self.get_bart_tokenizer()
)
return retriever | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def test_legacy_hf_index_retriever_save_and_from_pretrained(self):
retriever = self.get_dummy_legacy_index_retriever()
with tempfile.TemporaryDirectory() as tmp_dirname:
retriever.save_pretrained(tmp_dirname)
retriever = RagRetriever.from_pretrained(tmp_dirname)
self.assertIsInstance(retriever, RagRetriever)
hidden_states = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
)
out = retriever.retrieve(hidden_states, n_docs=1)
self.assertTrue(out is not None) | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def test_legacy_hf_index_retriever_save_and_from_pretrained(self):
retriever = self.get_dummy_legacy_index_retriever()
with tempfile.TemporaryDirectory() as tmp_dirname:
retriever.save_pretrained(tmp_dirname)
retriever = RagRetriever.from_pretrained(tmp_dirname)
self.assertIsInstance(retriever, RagRetriever)
hidden_states = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
)
out = retriever.retrieve(hidden_states, n_docs=1)
self.assertTrue(out is not None) | 0 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | vulnerable |
def dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = Path(destination) / path.lstrip("/")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
f.write(content)
return content | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = Path(destination) / path.lstrip("/")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
f.write(content)
return content | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 _find_working_git(self):
test_cmd = 'version'
if app.GIT_PATH:
main_git = '"' + app.GIT_PATH + '"'
else:
main_git = 'git'
log.debug(u'Checking if we can use git commands: {0} {1}', main_git, test_cmd)
_, _, exit_status = self._run_git(main_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', main_git)
return main_git
else:
log.debug(u'Not using: {0}', main_git)
# trying alternatives
alternative_git = []
# osx people who start sr from launchd have a broken path, so try a hail-mary attempt for them
if platform.system().lower() == 'darwin':
alternative_git.append('/usr/local/git/bin/git')
if platform.system().lower() == 'windows':
if main_git != main_git.lower():
alternative_git.append(main_git.lower())
if alternative_git:
log.debug(u'Trying known alternative git locations')
for cur_git in alternative_git:
log.debug(u'Checking if we can use git commands: {0} {1}', cur_git, test_cmd)
_, _, exit_status = self._run_git(cur_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', cur_git)
return cur_git
else:
log.debug(u'Not using: {0}', cur_git) | 0 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
def _set_document_file_metadata(self):
self.file.open()
# Set new document file size
self.file_size = self.file.size
# Set new document file hash
self._set_file_hash(self.file.read())
self.file.seek(0) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 _set_document_file_metadata(self):
self.file.open()
# Set new document file size
self.file_size = self.file.size
# Set new document file hash
self._set_file_hash(self.file.read())
self.file.seek(0) | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 get_file_hash(self):
if self.file_hash == "":
with self.open_file() as f:
self._set_file_hash(f.read())
self.save(update_fields=["file_hash"])
return self.file_hash | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 get_file_hash(self):
if self.file_hash == "":
with self.open_file() as f:
self._set_file_hash(f.read())
self.save(update_fields=["file_hash"])
return self.file_hash | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 _set_file_hash(self, file_contents):
self.file_hash = hashlib.sha1(file_contents).hexdigest() | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 _set_file_hash(self, file_contents):
self.file_hash = hashlib.sha1(file_contents).hexdigest() | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 get_file_hash(self):
if self.file_hash == "":
with self.open_file() as f:
self._set_file_hash(f.read())
self.save(update_fields=["file_hash"])
return self.file_hash | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 get_file_hash(self):
if self.file_hash == "":
with self.open_file() as f:
self._set_file_hash(f.read())
self.save(update_fields=["file_hash"])
return self.file_hash | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 _set_file_hash(self, file_contents):
self.file_hash = hashlib.sha1(file_contents).hexdigest() | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 _set_file_hash(self, file_contents):
self.file_hash = hashlib.sha1(file_contents).hexdigest() | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 _set_image_file_metadata(self):
self.file.open()
# Set new image file size
self.file_size = self.file.size
# Set new image file hash
self._set_file_hash(self.file.read())
self.file.seek(0) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 _set_image_file_metadata(self):
self.file.open()
# Set new image file size
self.file_size = self.file.size
# Set new image file hash
self._set_file_hash(self.file.read())
self.file.seek(0) | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 to_python(self, data):
"""
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Willow supports). Overridden from ImageField to use
Willow instead of Pillow as the image library in order to enable SVG support.
"""
f = FileField.to_python(self, data)
if f is None:
return None
# We need to get a file object for Pillow. When we get a path, we need to open
# the file first. And we have to read the data into memory to pass to Willow.
if hasattr(data, "temporary_file_path"):
with open(data.temporary_file_path(), "rb") as fh:
file = BytesIO(fh.read())
else:
if hasattr(data, "read"):
file = BytesIO(data.read())
else:
file = BytesIO(data["content"])
try:
# Annotate the python representation of the FileField with the image
# property so subclasses can reuse it for their own validation
f.image = willow.Image.open(file)
f.content_type = image_format_name_to_content_type(f.image.format_name)
except Exception as exc:
# Willow doesn't recognize it as an image.
raise ValidationError(
self.error_messages["invalid_image"],
code="invalid_image",
) from exc
if hasattr(f, "seek") and callable(f.seek):
f.seek(0)
if f is not None:
self.check_image_file_size(f)
self.check_image_file_format(f)
self.check_image_pixel_size(f)
return f | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 to_python(self, data):
"""
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Willow supports). Overridden from ImageField to use
Willow instead of Pillow as the image library in order to enable SVG support.
"""
f = FileField.to_python(self, data)
if f is None:
return None
# We need to get a file object for Pillow. When we get a path, we need to open
# the file first. And we have to read the data into memory to pass to Willow.
if hasattr(data, "temporary_file_path"):
with open(data.temporary_file_path(), "rb") as fh:
file = BytesIO(fh.read())
else:
if hasattr(data, "read"):
file = BytesIO(data.read())
else:
file = BytesIO(data["content"])
try:
# Annotate the python representation of the FileField with the image
# property so subclasses can reuse it for their own validation
f.image = willow.Image.open(file)
f.content_type = image_format_name_to_content_type(f.image.format_name)
except Exception as exc:
# Willow doesn't recognize it as an image.
raise ValidationError(
self.error_messages["invalid_image"],
code="invalid_image",
) from exc
if hasattr(f, "seek") and callable(f.seek):
f.seek(0)
if f is not None:
self.check_image_file_size(f)
self.check_image_file_format(f)
self.check_image_pixel_size(f)
return f | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product 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 test_split_backslash():
stmts = sqlparse.parse(r"select '\\'; select '\''; select '\\\'';")
assert len(stmts) == 3 | 0 | Python | CWE-1333 | Inefficient Regular Expression Complexity | The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles. | https://cwe.mitre.org/data/definitions/1333.html | vulnerable |
def connect(self) -> dict:
"""
Set up the connection required by the handler.
Returns:
HandlerStatusResponse
"""
headers = {
'Content-Type': 'application/json',
}
data = '{' + f'"userName": "{self.connection_data["username"]}","password": "{self.connection_data["password"]}"' + '}'
response = requests.post(self.base_url + '/apiv2/login', headers=headers, data=data, verify=False)
return {
'Authorization': '_dremio' + response.json()['token'],
'Content-Type': 'application/json',
} | 0 | Python | CWE-311 | Missing Encryption of Sensitive Data | The product does not encrypt sensitive or critical information before storage or transmission. | https://cwe.mitre.org/data/definitions/311.html | vulnerable |
def on_file(file):
nonlocal file_object
data["file"] = file.file_name.decode()
file_object = file.file_object | 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 on_file(file):
nonlocal file_object
data["file"] = file.file_name.decode()
file_object = file.file_object | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def create(self, target: str, df: Optional[pd.DataFrame] = None, args: Optional[Dict] = None) -> None:
if 'using' not in args:
raise Exception("LlamaIndex engine requires a USING clause! Refer to its documentation for more details.")
if 'index_class' not in args['using']:
args['using']['index_class'] = self.default_index_class
elif args['using']['index_class'] not in self.supported_index_class:
raise Exception(f"Invalid index class argument. Please use one of {self.supported_index_class}")
if 'reader' not in args['using']:
args['using']['reader'] = self.default_reader
elif args['using']['reader'] not in self.supported_reader:
raise Exception(f"Invalid operation mode. Please use one of {self.supported_reader}")
# workaround to create llama model without input data
if df is None or df.empty:
df = pd.DataFrame([{'text': ''}])
if args['using']['reader'] == 'DFReader':
dstrs = df.apply(lambda x: ', '.join([f'{col}: {str(entry)}' for col, entry in zip(df.columns, x)]), axis=1)
reader = list(map(lambda x: Document(x), dstrs.tolist()))
elif args['using']['reader'] == 'SimpleWebPageReader':
if 'source_url_link' not in args['using']:
raise Exception("SimpleWebPageReader requires a `source_url_link` parameter. Refer to LlamaIndex documentation for more details.") # noqa
reader = SimpleWebPageReader(html_to_text=True).load_data([args['using']['source_url_link']])
else:
raise Exception(f"Invalid operation mode. Please use one of {self.supported_reader}.")
self.model_storage.json_set('args', args)
index = self._setup_index(reader)
path = self.model_storage.folder_get('context')
index.storage_context.persist(persist_dir=path)
self.model_storage.folder_sync('context') | 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 create(self, target: str, df: Optional[pd.DataFrame] = None, args: Optional[Dict] = None) -> None:
if 'using' not in args:
raise Exception("LlamaIndex engine requires a USING clause! Refer to its documentation for more details.")
if 'index_class' not in args['using']:
args['using']['index_class'] = self.default_index_class
elif args['using']['index_class'] not in self.supported_index_class:
raise Exception(f"Invalid index class argument. Please use one of {self.supported_index_class}")
if 'reader' not in args['using']:
args['using']['reader'] = self.default_reader
elif args['using']['reader'] not in self.supported_reader:
raise Exception(f"Invalid operation mode. Please use one of {self.supported_reader}")
# workaround to create llama model without input data
if df is None or df.empty:
df = pd.DataFrame([{'text': ''}])
if args['using']['reader'] == 'DFReader':
dstrs = df.apply(lambda x: ', '.join([f'{col}: {str(entry)}' for col, entry in zip(df.columns, x)]), axis=1)
reader = list(map(lambda x: Document(x), dstrs.tolist()))
elif args['using']['reader'] == 'SimpleWebPageReader':
if 'source_url_link' not in args['using']:
raise Exception("SimpleWebPageReader requires a `source_url_link` parameter. Refer to LlamaIndex documentation for more details.") # noqa
reader = SimpleWebPageReader(html_to_text=True).load_data([args['using']['source_url_link']])
else:
raise Exception(f"Invalid operation mode. Please use one of {self.supported_reader}.")
self.model_storage.json_set('args', args)
index = self._setup_index(reader)
path = self.model_storage.folder_get('context')
index.storage_context.persist(persist_dir=path)
self.model_storage.folder_sync('context') | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def select(self, query: ast.Select) -> pd.DataFrame:
conditions = extract_comparison_conditions(query.where)
urls = []
for op, arg1, arg2 in conditions:
if op == 'or':
raise NotImplementedError(f'OR is not supported')
if arg1 == 'url':
url = arg2
if op == '=':
urls = [str(url)]
elif op == 'in':
if type(url) == str:
urls = [str(url)]
else:
urls = url
else:
raise NotImplementedError(
f'url can be url = "someurl", you can also crawl multiple sites, as follows: url IN ("url1", "url2", ..)')
else:
pass
if len(urls) == 0:
raise NotImplementedError(
f'You must specify what url you want to crawl, for example: SELECT * FROM crawl WHERE url IN ("someurl", ..)')
if query.limit is None:
raise NotImplementedError(f'You must specify a LIMIT which defines the number of pages to crawl')
limit = query.limit.value
if limit < 0:
limit = 0
result = get_all_websites(urls, limit, html=False)
if len(result) > limit:
result = result[:limit]
# filter targets
result = project_dataframe(result, query.targets, self.get_columns())
return result | 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 select(self, query: ast.Select) -> pd.DataFrame:
conditions = extract_comparison_conditions(query.where)
urls = []
for op, arg1, arg2 in conditions:
if op == 'or':
raise NotImplementedError(f'OR is not supported')
if arg1 == 'url':
url = arg2
if op == '=':
urls = [str(url)]
elif op == 'in':
if type(url) == str:
urls = [str(url)]
else:
urls = url
else:
raise NotImplementedError(
f'url can be url = "someurl", you can also crawl multiple sites, as follows: url IN ("url1", "url2", ..)')
else:
pass
if len(urls) == 0:
raise NotImplementedError(
f'You must specify what url you want to crawl, for example: SELECT * FROM crawl WHERE url IN ("someurl", ..)')
if query.limit is None:
raise NotImplementedError(f'You must specify a LIMIT which defines the number of pages to crawl')
limit = query.limit.value
if limit < 0:
limit = 0
result = get_all_websites(urls, limit, html=False)
if len(result) > limit:
result = result[:limit]
# filter targets
result = project_dataframe(result, query.targets, self.get_columns())
return result | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def test_basic_init_function(get_contract):
code = """
val: public(uint256)
@external
def __init__(a: uint256):
self.val = a
"""
c = get_contract(code, *[123])
assert c.val() == 123
# Make sure the init code does not access calldata
opcodes = vyper.compile_code(code, ["opcodes"])["opcodes"].split(" ")
ir_return_idx = opcodes.index("JUMP")
assert "CALLDATALOAD" in opcodes
assert "CALLDATACOPY" not in opcodes[:ir_return_idx]
assert "CALLDATALOAD" not in opcodes[:ir_return_idx] | 0 | Python | CWE-670 | Always-Incorrect Control Flow Implementation | The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated. | https://cwe.mitre.org/data/definitions/670.html | vulnerable |
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict:
ret = {}
offset = 0
for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}):
varinfo = node.target._metadata["varinfo"]
type_ = varinfo.typ
varinfo.set_position(CodeOffset(offset))
len_ = math.ceil(type_.size_in_bytes / 32) * 32
# this could have better typing but leave it untyped until
# we understand the use case better
ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_}
offset += len_
return ret | 0 | Python | CWE-789 | Memory Allocation with Excessive Size Value | The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated. | https://cwe.mitre.org/data/definitions/789.html | vulnerable |
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict:
ret = {}
offset = 0
for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}):
varinfo = node.target._metadata["varinfo"]
type_ = varinfo.typ
varinfo.set_position(CodeOffset(offset))
len_ = math.ceil(type_.size_in_bytes / 32) * 32
# this could have better typing but leave it untyped until
# we understand the use case better
ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_}
offset += len_
return ret | 0 | Python | CWE-193 | Off-by-one Error | A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value. | https://cwe.mitre.org/data/definitions/193.html | vulnerable |
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict:
ret = {}
offset = 0
for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}):
varinfo = node.target._metadata["varinfo"]
type_ = varinfo.typ
varinfo.set_position(CodeOffset(offset))
len_ = math.ceil(type_.size_in_bytes / 32) * 32
# this could have better typing but leave it untyped until
# we understand the use case better
ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_}
offset += len_
return ret | 0 | Python | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | vulnerable |
def append_dyn_array(darray_node, elem_node):
assert isinstance(darray_node.typ, DArrayT)
assert darray_node.typ.count > 0, "jerk boy u r out"
ret = ["seq"]
with darray_node.cache_when_complex("darray") as (b1, darray_node):
len_ = get_dyn_array_count(darray_node)
with len_.cache_when_complex("old_darray_len") as (b2, len_):
assertion = ["assert", ["lt", len_, darray_node.typ.count]]
ret.append(IRnode.from_list(assertion, error_msg=f"{darray_node.typ} bounds check"))
ret.append(STORE(darray_node, ["add", len_, 1]))
# NOTE: typechecks elem_node
# NOTE skip array bounds check bc we already asserted len two lines up
ret.append(
make_setter(get_element_ptr(darray_node, len_, array_bounds_check=False), elem_node)
)
return IRnode.from_list(b1.resolve(b2.resolve(ret))) | 0 | Python | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
def make_byte_array_copier(dst, src):
assert isinstance(src.typ, _BytestringT)
assert isinstance(dst.typ, _BytestringT)
_check_assign_bytes(dst, src)
# TODO: remove this branch, copy_bytes and get_bytearray_length should handle
if src.value == "~empty":
# set length word to 0.
return STORE(dst, 0)
with src.cache_when_complex("src") as (b1, src):
with get_bytearray_length(src).cache_when_complex("len") as (b2, len_):
max_bytes = src.typ.maxlen
ret = ["seq"]
# store length
ret.append(STORE(dst, len_))
dst = bytes_data_ptr(dst)
src = bytes_data_ptr(src)
ret.append(copy_bytes(dst, src, len_, max_bytes))
return b1.resolve(b2.resolve(ret)) | 0 | Python | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
def lookup_internal_function(self, method_name, args_ir, ast_source):
# TODO is this the right module for me?
"""
Using a list of args, find the internal method to use, and
the kwargs which need to be filled in by the compiler
"""
sig = self.sigs["self"].get(method_name, None)
def _check(cond, s="Unreachable"):
if not cond:
raise CompilerPanic(s)
# these should have been caught during type checking; sanity check
_check(sig is not None)
_check(sig.internal)
_check(len(sig.base_args) <= len(args_ir) <= len(sig.args))
# more sanity check, that the types match
# _check(all(l.typ == r.typ for (l, r) in zip(args_ir, sig.args))
num_provided_kwargs = len(args_ir) - len(sig.base_args)
num_kwargs = len(sig.default_args)
kwargs_needed = num_kwargs - num_provided_kwargs
kw_vals = list(sig.default_values.values())[:kwargs_needed]
return sig, kw_vals | 0 | Python | NVD-CWE-noinfo | null | null | null | vulnerable |
def build_IR(self, expr, args, kwargs, context):
placeholder_node = IRnode.from_list(
context.new_internal_variable(BytesT(128)), typ=BytesT(128), location=MEMORY
)
return IRnode.from_list(
[
"seq",
["mstore", placeholder_node, args[0]],
["mstore", ["add", placeholder_node, 32], args[1]],
["mstore", ["add", placeholder_node, 64], args[2]],
["mstore", ["add", placeholder_node, 96], args[3]],
[
"pop",
[
"staticcall",
["gas"],
1,
placeholder_node,
128,
MemoryPositions.FREE_VAR_SPACE,
32,
],
],
["mload", MemoryPositions.FREE_VAR_SPACE],
],
typ=AddressT(),
) | 0 | Python | CWE-252 | Unchecked Return Value | The product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions. | https://cwe.mitre.org/data/definitions/252.html | vulnerable |
def __init__(self, message="Error Message not found.", *items):
"""
Exception initializer.
Arguments
---------
message : str
Error message to display with the exception.
*items : VyperNode | Tuple[str, VyperNode], optional
Vyper ast node(s), or tuple of (description, node) indicating where
the exception occured. Source annotations are generated in the order
the nodes are given.
A single tuple of (lineno, col_offset) is also understood to support
the old API, but new exceptions should not use this approach.
"""
self.message = message
self.lineno = None
self.col_offset = None
if len(items) == 1 and isinstance(items[0], tuple) and isinstance(items[0][0], int):
# support older exceptions that don't annotate - remove this in the future!
self.lineno, self.col_offset = items[0][:2]
else:
self.annotations = items | 0 | Python | CWE-667 | Improper Locking | The product 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 | vulnerable |
def validate_identifier(attr):
if not re.match("^[_a-zA-Z][a-zA-Z0-9_]*$", attr):
raise StructureException(f"'{attr}' contains invalid character(s)")
if attr.lower() in RESERVED_KEYWORDS:
raise StructureException(f"'{attr}' is a reserved keyword") | 0 | Python | CWE-667 | Improper Locking | The product 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 | vulnerable |
def on_part_end(self) -> None:
message = (MultiPartMessage.PART_END, b"")
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_part_begin(self) -> None:
message = (MultiPartMessage.PART_BEGIN, b"")
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_part_data(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.PART_DATA, data[start:end])
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_header_field(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_FIELD, data[start:end])
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_header_value(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_VALUE, data[start:end])
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages: typing.List[typing.Tuple[MultiPartMessage, bytes]] = [] | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_end(self) -> None:
message = (MultiPartMessage.END, b"")
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_headers_finished(self) -> None:
message = (MultiPartMessage.HEADERS_FINISHED, b"")
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 on_header_end(self) -> None:
message = (MultiPartMessage.HEADER_END, b"")
self.messages.append(message) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 form(self) -> AwaitableOrContextManager[FormData]:
return AwaitableOrContextManagerWrapper(self._get_form()) | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 |
async def _get_form(self) -> FormData:
if self._form is None:
assert (
parse_options_header is not None
), "The `python-multipart` library must be installed to use form parsing."
content_type_header = self.headers.get("Content-Type")
content_type: bytes
content_type, _ = parse_options_header(content_type_header)
if content_type == b"multipart/form-data":
try:
multipart_parser = MultiPartParser(self.headers, self.stream())
self._form = await multipart_parser.parse()
except MultiPartException as exc:
if "app" in self.scope:
raise HTTPException(status_code=400, detail=exc.message)
raise exc
elif content_type == b"application/x-www-form-urlencoded":
form_parser = FormParser(self.headers, self.stream())
self._form = await form_parser.parse()
else:
self._form = FormData()
return self._form | 0 | Python | CWE-400 | Uncontrolled Resource Consumption | The product 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 execute(self):
# clean up tmp extraction folder
if os.path.exists(TEMP_EXTRACTION_PATH) and not CleanupDir(TEMP_EXTRACTION_PATH).run():
logger.error('Could not clean temp folder')
raise IOError
# untar the package into tmp folder
with closing(tarfile.open(self.gppkg.abspath)) as tarinfo:
tarinfo.extractall(TEMP_EXTRACTION_PATH)
# move all the deps into same folder as the main rpm
path = os.path.join(TEMP_EXTRACTION_PATH, DEPS_DIR)
if os.path.exists(path):
for cur_file in os.listdir(path):
shutil.move(os.path.join(TEMP_EXTRACTION_PATH, DEPS_DIR, cur_file), TEMP_EXTRACTION_PATH) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 open(self, *args, **kwargs):
"""Websocket connection opened.
Call our terminal manager to get a terminal, and connect to it as a
client.
"""
# Jupyter has a mixin to ping websockets and keep connections through
# proxies alive. Call super() to allow that to set up:
tornado.websocket.WebSocketHandler.open(self, *args, **kwargs)
api_key = self.get_argument('api_key', None, True)
token = self.get_argument('token', None, True)
cwd = self.get_argument('cwd', None, True)
term_name = self.get_argument('term_name', None, True)
user = None
if REQUIRE_USER_AUTHENTICATION and api_key and token:
oauth_client = Oauth2Application.query.filter(
Oauth2Application.client_id == api_key,
).first()
if oauth_client:
oauth_token, valid = authenticate_client_and_token(oauth_client.id, token)
valid = valid and \
oauth_token and \
oauth_token.user
if valid:
user = oauth_token.user
else:
raise Exception('Invalid token')
self.term_name = term_name if term_name else 'tty'
if user:
self.term_name = f'{self.term_name}_{user.id}'
self._logger.info("TermSocket.open: %s", self.term_name)
self.terminal = self.term_manager.get_terminal(self.term_name, cwd=cwd)
self.terminal.clients.append(self)
self.__initiate_terminal(self.terminal) | 0 | Python | CWE-306 | Missing Authentication for Critical Function | The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. | https://cwe.mitre.org/data/definitions/306.html | vulnerable |
def __init__(self, path):
self.path = path | 0 | Python | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
def _write(self, contents: dict):
LOGGER.debug(f'Writing to {self.path}')
with open(self.path, 'w') as fp:
fp.write(json.dumps(contents)) | 0 | Python | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
def secret_path(monkeypatch, tmp_path):
secret_path = str(tmp_path / '.test')
monkeypatch.setattr(auth, 'SECRET_FILE_PATH', secret_path)
yield secret_path | 0 | Python | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.