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 testEmptyShapeWithEditDistanceRaisesError(self):
para = {
"hypothesis_indices": [[]],
"hypothesis_values": ["tmp/"],
"hypothesis_shape": [],
"truth_indices": [[]],
"truth_values": [""],
"truth_shape": [],
"normalize": False,
}
# Check edit distance raw op with empty shape in eager mode.
with self.assertRaisesRegex(
(errors.InvalidArgumentError, ValueError),
(
r"Input Hypothesis SparseTensors must have rank at least 2, but"
" hypothesis_shape rank is: 0|Input SparseTensors must have rank "
"at least 2, but truth_shape rank is: 0"
),
):
array_ops.gen_array_ops.EditDistance(**para)
# Check raw op with tf.function
@def_function.function
def TestFunction():
"""Wrapper function for edit distance call."""
array_ops.gen_array_ops.EditDistance(**para)
with self.assertRaisesRegex(
ValueError,
(
"Input Hypothesis SparseTensors must have rank at least 2, but"
" hypothesis_shape rank is: 0"
),
):
TestFunction()
# Check with python wrapper API
hypothesis_indices = [[]]
hypothesis_values = [0]
hypothesis_shape = []
truth_indices = [[]]
truth_values = [1]
truth_shape = []
expected_output = [] # dummy ignored
with self.assertRaisesRegex(
ValueError,
(
"Input Hypothesis SparseTensors must have rank at least 2, but"
" hypothesis_shape rank is: 0"
),
):
self._testEditDistance(
hypothesis=(hypothesis_indices, hypothesis_values, hypothesis_shape),
truth=(truth_indices, truth_values, truth_shape),
normalize=False,
expected_output=expected_output,
) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The product 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 TestFunction():
"""Wrapper function for edit distance call."""
array_ops.gen_array_ops.EditDistance(**para) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The product 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 testSnapshotRecoveryFailsWithBadSplitNames(self, bad_split_filename):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), bad_split_filename))
with self.assertRaisesRegex(
ValueError, "Expected split_<local_split_index>_<global_split_index>"):
cluster.restart_dispatcher() | 1 | 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 | safe |
def testSnapshotRecoveryFailsWithOutOfOrderSplitName(self):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), "split_1_0"))
with self.assertRaisesRegex(
ValueError, "The local split index 1 exceeds the global split index 0"):
cluster.restart_dispatcher() | 1 | 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 | safe |
def testAvgPoolGradSamePaddingZeroStrideZeroSize(self):
output_gradient_vals = np.array([0.39117979], dtype=np.float32)
output_gradient_vals = output_gradient_vals.reshape([1, 1, 1, 1])
with self.session() as sess:
with self.test_scope():
output_gradients = array_ops.placeholder(
dtypes.float32, shape=output_gradient_vals.shape
)
t = gen_nn_ops.avg_pool_grad(
orig_input_shape=[1, 0, 0, 0],
grad=output_gradients,
ksize=[1, 0, 0, 0],
strides=[1, 0, 0, 0],
padding="SAME",
data_format="NCHW",
)
with self.assertRaisesRegex(
errors.InvalidArgumentError,
(
"Sliding window ksize field for dimension 1 must be positive but"
" is 0"
),
):
sess.run(t, {output_gradients: output_gradient_vals}) | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
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 .* must be greater than"
):
f() | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def func():
y = op(**para)
return y | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testParallelConcatFailsWithRankZeroShape(self):
op = array_ops.ParallelConcat
para = {"shape": 0, "values": [1]}
def func():
y = op(**para)
return y
with self.assertRaisesRegex(
Exception, "(rank|dimension) of .* must be greater than .* 0"
):
func() | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testImportShapeInference(self, is_anonymous):
v = variables.Variable(1)
@def_function.function(jit_compile=True)
def foo():
return gen_lookup_ops.lookup_table_import_v2(
table_handle=v.handle, keys=[1.1, 2.2], values=1
)
with self.assertRaisesRegex(
ValueError, r"Shape must be at least rank 1 but is rank 0"
):
foo() | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def foo():
return gen_lookup_ops.lookup_table_import_v2(
table_handle=v.handle, keys=[1.1, 2.2], values=1
) | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testOutOfBoundsIndexRaisesInvalidArgument(self):
with self.assertRaisesRegex(errors.InvalidArgumentError, "out of range"):
indices = [[-1000], [405], [519], [758], [1015]]
data = [
[110.27793884277344],
[120.29475402832031],
[157.2418212890625],
[157.2626953125],
[188.45382690429688],
]
self.evaluate(self.stitch_op(indices, data)) | 1 | 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 | safe |
def testInvalidSplitLength(self):
with self.session(), self.test_scope():
tensor_list_split = list_ops.tensor_list_split(
tensor=[1], element_shape=[-1], lengths=[0]
)
with self.assertRaisesRegex(
errors.UnimplementedError, "All lengths must be positive"
):
self.evaluate(tensor_list_split) | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
def testInvalidSplitLength(self):
with self.session(), self.test_scope():
tensor_list_split = list_ops.tensor_list_split(
tensor=[1], element_shape=[-1], lengths=[0]
)
with self.assertRaisesRegex(
errors.UnimplementedError, "All lengths must be positive"
):
self.evaluate(tensor_list_split) | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testInputRank0(self):
with self.session():
with self.test_scope():
bincount = gen_math_ops.bincount(arr=6, size=804, weights=[52, 351])
with self.assertRaisesRegex(
errors.InvalidArgumentError,
(
"`weights` must be the same shape as `arr` or a length-0"
" `Tensor`, in which case it acts as all weights equal to 1."
),
):
self.evaluate(bincount) | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
def upload_ssh_key(name: str, user_group: str, key: str) -> bool:
if '..' in name:
print('error: nice try')
return False
try:
key = paramiko.pkey.load_private_key(key)
except Exception as e:
print(f'error: Cannot save SSH key file: {e}')
return False
lib_path = get_config.get_config_var('main', 'lib_path')
full_dir = f'{lib_path}/keys/'
ssh_keys = f'{name}.pem'
try:
_check_split = name.split('_')[1]
split_name = True
except Exception:
split_name = False
if not os.path.isfile(ssh_keys) and not split_name:
name = f'{name}_{user_group}'
if not os.path.exists(full_dir):
os.makedirs(full_dir)
ssh_keys = f'{full_dir}{name}.pem'
try:
key.write_private_key_file(ssh_keys)
except Exception as e:
print(f'error: Cannot save SSH key file: {e}')
return False
else:
print(f'success: SSH key has been saved into: {ssh_keys}')
try:
os.chmod(ssh_keys, 0o600)
except IOError as e:
roxywi_common.logging('Roxy-WI server', e.args[0], roxywi=1)
return False
roxywi_common.logging("Roxy-WI server", f"A new SSH cert has been uploaded {ssh_keys}", roxywi=1, login=1)
return True | 1 | 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 | safe |
def create_ssh_cred() -> None:
from jinja2 import Environment, FileSystemLoader
name = common.checkAjaxInput(form.getvalue('new_ssh'))
enable = common.checkAjaxInput(form.getvalue('ssh_enable'))
group = common.checkAjaxInput(form.getvalue('new_group'))
group_name = sql.get_group_name_by_id(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()
name = f'{name}_{group_name}'
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) | 1 | 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 | safe |
def test_proxy_url_forgery(self):
"""The GeoNode Proxy should preserve the original request headers."""
import geonode.proxy.views
from urllib.parse import urlsplit
class Response:
status_code = 200
content = "Hello World"
headers = {
"Content-Type": "text/plain",
"Vary": "Authorization, Accept-Language, Cookie, origin",
"X-Content-Type-Options": "nosniff",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "same-origin",
"X-Frame-Options": "SAMEORIGIN",
"Content-Language": "en-us",
"Content-Length": "119",
"Content-Disposition": 'attachment; filename="filename.tif"',
}
request_mock = MagicMock()
request_mock.return_value = (Response(), None)
# Non-Legit requests attempting SSRF
geonode.proxy.views.http_client.request = request_mock
url = f"http://example.org\@%23{urlsplit(settings.SITEURL).hostname}"
response = self.client.get(f"{self.proxy_url}?url={url}")
self.assertEqual(response.status_code, 403)
url = f"http://125.126.127.128\@%23{urlsplit(settings.SITEURL).hostname}"
response = self.client.get(f"{self.proxy_url}?url={url}")
self.assertEqual(response.status_code, 403)
# Legit requests using the local host (SITEURL)
url = f"/\@%23{urlsplit(settings.SITEURL).hostname}"
response = self.client.get(f"{self.proxy_url}?url={url}")
self.assertEqual(response.status_code, 200)
url = f"{settings.SITEURL}\@%23{urlsplit(settings.SITEURL).hostname}"
response = self.client.get(f"{self.proxy_url}?url={url}")
self.assertEqual(response.status_code, 200) | 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 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 | 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 extract_ip_or_domain(url):
# Decode the URL to handle percent-encoded characters
_url = remove_credentials_from_url(unquote(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 | 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 remove_credentials_from_url(url):
# Parse the URL
parsed_url = urlparse(url)
# Remove the username and password from the parsed URL
parsed_url = parsed_url._replace(netloc=parsed_url.netloc.split("@")[-1])
# Reconstruct the URL without credentials
cleaned_url = urlunparse(parsed_url)
return cleaned_url | 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 payment_gateway_notification_event(
*, order: Order, user: UserType, message: str, payment: Payment
) -> OrderEvent:
if not _user_is_valid(user):
user = None
parameters = {"message": message}
if payment:
parameters.update({"gateway": payment.gateway, "payment_id": payment.token})
return OrderEvent.objects.create(
order=order,
type=OrderEvents.PAYMENT_GATEWAY_NOTIFICATION,
user=user,
parameters=parameters,
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def _update_config_items(
cls, configuration_to_update: List[dict], current_config: List[dict]
):
super()._update_config_items(configuration_to_update, current_config)
for item in current_config:
if item.get("name") == "Notification password":
item["value"] = make_password(item["value"]) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
config = self._get_gateway_config()
return handle_webhook(request, config) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def __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=configuration[
"Automatically mark payment as a capture"
], # 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"],
"live": configuration["Live"],
"webhook_hmac": configuration["HMAC secret key"],
"webhook_user": configuration["Notification user"],
"webhook_user_password": configuration["Notification password"],
},
)
api_key = self.config.connection_params["api_key"]
self.adyen = Adyen.Adyen(xapikey=api_key) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def convert_adyen_price_format(value: str, currency: str):
value = Decimal(value)
precision = get_currency_precision(currency)
number_places = Decimal(10) ** -precision
return value * number_places | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_payment_notification_for_order(
payment: Payment, success_msg: str, failed_msg: Optional[str], is_success: bool
):
if not payment.order:
# Order is not assigned
return
msg = success_msg if is_success else failed_msg
payment_gateway_notification_event(
order=payment.order, user=None, message=msg, payment=payment
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_cancel_or_refund(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
additional_data = notification.get("additionalData")
action = additional_data.get("modification.action")
if action == "refund":
handle_refund(notification, gateway_config)
elif action == "cancel":
handle_cancellation(notification, gateway_config) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(
payment, transaction_id, TransactionKind.CAPTURE_FAILED
)
if transaction and transaction.is_success:
# it is already failed
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.CAPTURE_FAILED
)
gateway_postprocess(new_transaction, payment)
msg = f"Adyen: The capture for {transaction_id} failed due to a technical issue."
create_payment_notification_for_order(payment, msg, None, True) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
if transaction and transaction.is_success:
# it is already refunded
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.REFUND
)
gateway_postprocess(new_transaction, payment)
success_msg = f"Adyen: The refund {transaction_id} request was successful."
failed_msg = f"Adyen: The refund {transaction_id} request failed."
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
json_data = json.loads(request.body)
# JSON and HTTP POST notifications always contain a single NotificationRequestItem
# object.
notification = json_data.get("notificationItems")[0].get(
"NotificationRequestItem", {}
)
if not validate_hmac_signature(notification, gateway_config):
return HttpResponseBadRequest("Invalid or missing hmac signature.")
if not validate_auth_user(notification, gateway_config):
return HttpResponseBadRequest("Invalid or missing basic auth.")
event_handler = EVENT_MAP.get(notification.get("eventCode", ""))
if event_handler:
event_handler(notification, gateway_config)
return HttpResponse("[accepted]")
return HttpResponseNotFound() | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def get_transaction(
payment: "Payment", transaction_id: str, kind: TransactionKind,
) -> Transaction:
transaction = payment.transactions.filter(kind=kind, token=transaction_id)
return transaction | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_reversed_refund(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(
payment, transaction_id, TransactionKind.REFUND_REVERSED
)
if transaction and not transaction.is_success:
# it is already refunded
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.REFUND_REVERSED
)
gateway_postprocess(new_transaction, payment)
msg = (
f"Adyen: The refunded amount from {transaction_id} has been returned to Adyen, "
f"and is back in your account. This may happen if the shopper's bank account "
f"is no longer valid"
)
create_payment_notification_for_order(payment, msg, msg, transaction.is_success) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def webhook_not_implemented(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
adyen_id = notification.get("pspReference")
success = notification.get("success", True)
event = notification.get("eventCode")
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
msg = (
f"Received not implemented notification from Adyen. Event name: {event}, "
f"success: {success}, adyen reference: {adyen_id}."
)
create_payment_notification_for_order(payment, msg, None, True) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") -> bool:
username = gateway_config.connection_params["webhook_user"]
password = gateway_config.connection_params["webhook_user_password"]
auth_header = headers.get("Authorization")
if not auth_header and not username:
return True
split_auth = auth_header.split(maxsplit=1)
prefix = "BASIC"
if len(split_auth) != 2 or split_auth[0].upper() != prefix:
return False
auth = split_auth[1]
try:
request_username, request_password = base64.b64decode(auth).split(":")
user_is_correct = request_username == username
if user_is_correct and check_password(request_password, password):
return True
except binascii.Error:
pass
return False | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.CANCEL)
if transaction:
# it is already cancelled
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.CANCEL
)
gateway_postprocess(new_transaction, payment)
success_msg = "Adyen: The cancel request was successful."
failed_msg = "Adyen: The request failed."
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def get_payment(payment_id: str) -> Payment:
_type, payment_id = from_global_id(payment_id)
payment = Payment.objects.prefetch_related("order").filter(id=payment_id).first()
return payment | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_new_transaction(notification, payment, kind):
transaction_id = notification.get("pspReference")
currency = notification.get("amount", {}).get("currency")
amount = convert_adyen_price_format(
notification.get("amount", {}).get("value"), currency
)
is_success = True if notification.get("success") == "true" else False
gateway_response = GatewayResponse(
kind=kind,
action_required=False,
transaction_id=transaction_id,
is_success=is_success,
amount=amount,
currency=currency,
error="",
raw_response={},
)
return create_transaction(
payment,
kind=kind,
payment_information=None,
action_required=False,
gateway_response=gateway_response,
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_refund_with_data(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
if transaction:
# it is already refunded
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.REFUND
)
gateway_postprocess(new_transaction, payment)
success_msg = f"Adyen: The refund {transaction_id} request was successful."
failed_msg = f"Adyen: The refund {transaction_id} request failed."
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def validate_hmac_signature(
notification: Dict[str, Any], gateway_config: "GatewayConfig"
) -> bool:
"""
pspReference 7914073381342284
originalReference
merchantAccountCode YOUR_MERCHANT_ACCOUNT
merchantReference TestPayment-1407325143704
value 1130
currency EUR
eventCode AUTHORISATION
success true
"""
hmac_key = gateway_config.connection_params.get("webhook_hmac")
if not hmac_key:
return True
hmac_signature = notification.get("additionalData", {}).get("hmacSignature")
if not hmac_signature and hmac_key:
return False
success = "true" if notification.get("success", "") else "false"
if notification.get("success", None) is None:
success = ""
payload_list = [
notification.get("pspReference", ""),
notification.get("originalReference", ""),
notification.get("merchantAccountCode", ""),
notification.get("merchantReference", ""),
notification.get("value", ""),
notification.get("currency", ""),
notification.get("eventCode", ""),
success,
]
payload = ":".join(payload_list)
hm = hmac.new(hmac_key, payload.encode("utf-8"), hashlib.sha256)
expected_merchant_sign = base64.b64encode(hm.digest())
return hmac_signature == expected_merchant_sign.decode("utf-8") | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):
mark_capture = gateway_config.auto_capture
if mark_capture:
# If we mark order as a capture by default we don't need to handle auth actions
return
payment = get_payment(notification.get("merchantReference"))
if not payment:
# We don't know anything about that payment
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.AUTH)
if transaction:
# We already marked it as Auth
return
transaction = create_new_transaction(notification, payment, TransactionKind.AUTH)
success_msg = "Adyen: The payment request was successful."
failed_msg = "Adyen: The payment request failed."
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.CAPTURE)
if transaction and transaction.is_success:
# it is already captured
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.CAPTURE
)
gateway_postprocess(new_transaction, payment)
success_msg = f"Adyen: The capture {transaction_id} request was successful."
failed_msg = f"Adyen: The capture {transaction_id} request failed."
create_payment_notification_for_order(
payment, success_msg, failed_msg, transaction.is_success
) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
mark_capture = gateway_config.auto_capture
if mark_capture:
# If we mark order as a capture by default we don't need to handle this action
return
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.PENDING)
if transaction and transaction.is_success:
# it is already pending
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.PENDING
)
gateway_postprocess(new_transaction, payment)
msg = f"Adyen: The transaction {transaction_id} is pending."
create_payment_notification_for_order(payment, msg, None, transaction.is_success) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_failed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
if transaction and not transaction.is_success:
# The refund is already saved
return
new_transaction = create_new_transaction(
notification, payment, TransactionKind.REFUND
)
gateway_postprocess(new_transaction, payment)
msg = (
f"The refund {transaction_id} failed due to a technical issue. If you receive "
f"more than two failures on the same refund, contact Adyen Support Team."
)
create_payment_notification_for_order(payment, msg, msg, transaction.is_success) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_transaction(
payment: Payment,
kind: str,
payment_information: Optional[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 | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def 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)
content = get_graphql_content(response)
data = content["data"]["requestPasswordReset"]
assert len(data["errors"]) == 1
assert data["errors"][0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name
assert not mocked_notify.called | 1 | 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 | safe |
def mutate(cls, root, info: ResolveInfo, **data):
disallow_replica_in_context(info.context)
try:
setup_context_user(info.context)
except jwt.InvalidTokenError:
return cls.handle_errors(
ValidationError(
"Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value
)
)
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) | 1 | 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 | safe |
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"] == INTERNAL_ERROR_MESSAGE | 1 | 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 | safe |
def test_format_error_prints_allowed_errors():
error_cls = ALLOWED_ERRORS[0]
error = error_cls("Example error")
result = format_error(error, ())
assert result["message"] == str(error) | 1 | 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 | safe |
def test_format_error_hides_internal_error_msg_in_production_mode():
error = ValueError("Example error")
result = format_error(error, ())
assert result["message"] == INTERNAL_ERROR_MESSAGE | 1 | 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 | safe |
def test_format_error_prints_internal_error_msg_in_debug_mode():
error = ValueError("Example error")
result = format_error(error, ())
assert result["message"] == str(error) | 1 | 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 | safe |
def format_error(error, handled_exceptions):
result: Dict[str, Any]
if isinstance(error, GraphQLError):
result = format_graphql_error(error)
else:
result = {"message": str(error)}
if "extensions" not in result:
result["extensions"] = {}
exc = error
while isinstance(exc, GraphQLError) and hasattr(exc, "original_error"):
exc = exc.original_error
if isinstance(exc, AssertionError):
exc = GraphQLError(str(exc))
if isinstance(exc, handled_exceptions):
handled_errors_logger.info("A query had an error", exc_info=exc)
else:
unhandled_errors_logger.error("A query failed unexpectedly", exc_info=exc)
# If DEBUG mode is disabled we allow only certain error messages to be returned in
# the API. This prevents from leaking internals that might be included in Python
# exceptions' error messages.
if type(exc) not in ALLOWED_ERRORS and not settings.DEBUG:
result["message"] = INTERNAL_ERROR_MESSAGE
result["extensions"]["exception"] = {"code": type(exc).__name__}
if settings.DEBUG:
lines = []
if isinstance(exc, BaseException):
for line in traceback.format_exception(type(exc), exc, exc.__traceback__):
lines.extend(line.rstrip().splitlines())
result["extensions"]["exception"]["stacktrace"] = lines
return result | 1 | 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 | safe |
def _raise_if_restricted_key(key):
# Prevent access to dunder-methods since this could expose access to globals through leaky
# attributes such as obj.__init__.__globals__.
if len(key) > 4 and key.isascii() and key.startswith("__") and key.endswith("__"):
raise KeyError(f"access to restricted key {key!r} is not allowed") | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def _raise_if_restricted_key(key):
# Prevent access to dunder-methods since this could expose access to globals through leaky
# attributes such as obj.__init__.__globals__.
if len(key) > 4 and key.isascii() and key.startswith("__") and key.endswith("__"):
raise KeyError(f"access to restricted key {key!r} is not allowed") | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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 _base_get_object(obj, key, default=UNSET):
value = _base_get_item(obj, key, default=UNSET)
if value is UNSET:
_raise_if_restricted_key(key)
value = default
try:
value = getattr(obj, key)
except Exception:
pass
return value | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def _base_get_object(obj, key, default=UNSET):
value = _base_get_item(obj, key, default=UNSET)
if value is UNSET:
_raise_if_restricted_key(key)
value = default
try:
value = getattr(obj, key)
except Exception:
pass
return value | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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 base_set(obj, key, value, allow_override=True):
"""
Set an object's `key` to `value`. If `obj` is a ``list`` and the `key` is the next available
index position, append to list; otherwise, pad the list of ``None`` and then append to the list.
Args:
obj (list|dict): Object to assign value to.
key (mixed): Key or index to assign to.
value (mixed): Value to assign.
allow_override (bool): Whether to allow overriding a previously set key.
"""
if isinstance(obj, dict):
if allow_override or key not in obj:
obj[key] = value
elif isinstance(obj, list):
key = int(key)
if key < len(obj):
if allow_override:
obj[key] = value
else:
if key > len(obj):
# Pad list object with None values up to the index key so we can append the value
# into the key index.
obj[:] = (obj + [None] * key)[:key]
obj.append(value)
elif (allow_override or not hasattr(obj, key)) and obj is not None:
_raise_if_restricted_key(key)
setattr(obj, key, value)
return obj | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def base_set(obj, key, value, allow_override=True):
"""
Set an object's `key` to `value`. If `obj` is a ``list`` and the `key` is the next available
index position, append to list; otherwise, pad the list of ``None`` and then append to the list.
Args:
obj (list|dict): Object to assign value to.
key (mixed): Key or index to assign to.
value (mixed): Value to assign.
allow_override (bool): Whether to allow overriding a previously set key.
"""
if isinstance(obj, dict):
if allow_override or key not in obj:
obj[key] = value
elif isinstance(obj, list):
key = int(key)
if key < len(obj):
if allow_override:
obj[key] = value
else:
if key > len(obj):
# Pad list object with None values up to the index key so we can append the value
# into the key index.
obj[:] = (obj + [None] * key)[:key]
obj.append(value)
elif (allow_override or not hasattr(obj, key)) and obj is not None:
_raise_if_restricted_key(key)
setattr(obj, key, value)
return obj | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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_get__does_not_raise_for_dict_or_list_when_path_restricted(obj, path):
assert _.get(obj, path) is None | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def test_get__does_not_raise_for_dict_or_list_when_path_restricted(obj, path):
assert _.get(obj, path) is None | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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_get__raises_for_objects_when_path_restricted(obj, path):
with pytest.raises(KeyError, match="access to restricted key"):
_.get(obj, path) | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def test_get__raises_for_objects_when_path_restricted(obj, path):
with pytest.raises(KeyError, match="access to restricted key"):
_.get(obj, path) | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product 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 is_activated(self) -> bool:
return self.state == SessionState.Activated | 1 | 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 | safe |
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)
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 | 1 | 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 | safe |
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:
# a packet should at least contain a header otherwise it is malformed (8 or 12 bytes)
logger.debug('Not enough data while parsing header from client, empty the buffer')
self.transport.close()
return
if header.header_size + header.body_size <= header.header_size:
# malformed header prevent invalid access of your buffer
logger.error(f'Got malformed header {header}')
self.transport.close()
else:
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 | 1 | 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 | safe |
async def test_dos_server(opc):
# See issue 1013 a crafted packet triggered dos
port = opc.server.endpoint.port
async with Client(f'opc.tcp://127.0.0.1:{port}') as c:
# craft invalid packet that trigger dos
message_type, chunk_type, packet_size = [ua.MessageType.SecureOpen, b'E', 0]
c.uaclient.protocol.transport.write(struct.pack("<3scI", message_type, chunk_type, packet_size))
# sleep to give the server time to handle the message because we bypass the asyncio
await asyncio.sleep(1.0)
with pytest.raises(ConnectionError):
# now try to read a value to see if server is still alive
server_time_node = c.get_node(ua.NodeId(ua.ObjectIds.Server_ServerStatus_CurrentTime))
await server_time_node.read_value() | 1 | 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 | safe |
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":
if token.children:
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 | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
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":
if token.children:
result += self.renderInlineAsText(token.children, options, env)
elif token.type == "softbreak":
result += "\n"
return result | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
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.
if token.children:
token.attrSet("alt", self.renderInlineAsText(token.children, options, env))
else:
token.attrSet("alt", "")
return self.renderToken(tokens, idx, options, env) | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def replace(state: StateCore) -> None:
if not state.md.options.typographer:
return
for token in state.tokens:
if token.type != "inline":
continue
if token.children is None:
continue
if SCOPED_ABBR_RE.search(token.content):
replace_scoped(token.children)
if RARE_RE.search(token.content):
replace_rare(token.children) | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
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
if token.children is not None:
process_inlines(token.children, state) | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def test_issue_fixes(line, title, input, expected):
md = MarkdownIt()
text = md.render(input)
print(text)
assert text.rstrip() == expected.rstrip() | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def convert_file(filename: str) -> None:
"""
Parse a Markdown file and dump the output to stdout.
"""
try:
with open(filename, "r", encoding="utf8", errors="ignore") as fin:
rendered = MarkdownIt().render(fin.read())
print(rendered, end="")
except OSError:
sys.stderr.write(f'Cannot open file "{filename}".\n')
sys.exit(1) | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def test_non_utf8():
with tempfile.TemporaryDirectory() as tempdir:
path = pathlib.Path(tempdir).joinpath("test.md")
path.write_bytes(b"\x80abc")
assert parse.main([str(path)]) == 0 | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
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("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:
LOGGER.error(f"ComponentRequestHandler: GET {path} read error", exc_info=e)
self.write("read error")
self.set_status(404)
return
self.write(contents)
self.set_header("Content-Type", self.get_content_type(abspath))
self.set_extra_headers(path) | 1 | 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 | safe |
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, "not found")
return absolute_path | 1 | 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 | safe |
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"read error",
response.body,
) | 1 | 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 | safe |
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"not found", response.body) | 1 | 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 | safe |
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"read error",
response.body,
) | 1 | 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 | safe |
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 external file access, 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() | 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 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.mkstemp()[1]
with open(tmp_file, "wb") as f:
http_get(url, f, proxies=proxies)
return tmp_file | 1 | 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 | safe |
def get_lm_corpus(datadir, dataset):
fn = os.path.join(datadir, "cache.pt")
fn_pickle = os.path.join(datadir, "cache.pkl")
if os.path.exists(fn):
logger.info("Loading cached dataset...")
corpus = torch.load(fn_pickle)
elif os.path.exists(fn):
logger.info("Loading cached dataset from pickle...")
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(fn, "rb") as fp:
corpus = pickle.load(fp)
else:
logger.info(f"Producing dataset {dataset}...")
kwargs = {}
if dataset in ["wt103", "wt2"]:
kwargs["special"] = ["<eos>"]
kwargs["lower_case"] = False
elif dataset == "ptb":
kwargs["special"] = ["<eos>"]
kwargs["lower_case"] = True
elif dataset == "lm1b":
kwargs["special"] = []
kwargs["lower_case"] = False
kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
elif dataset in ["enwik8", "text8"]:
pass
corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
torch.save(corpus, fn)
return corpus | 1 | 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 | safe |
def get_lm_corpus(datadir, dataset):
fn = os.path.join(datadir, "cache.pt")
fn_pickle = os.path.join(datadir, "cache.pkl")
if os.path.exists(fn):
logger.info("Loading cached dataset...")
corpus = torch.load(fn_pickle)
elif os.path.exists(fn):
logger.info("Loading cached dataset from pickle...")
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(fn, "rb") as fp:
corpus = pickle.load(fp)
else:
logger.info(f"Producing dataset {dataset}...")
kwargs = {}
if dataset in ["wt103", "wt2"]:
kwargs["special"] = ["<eos>"]
kwargs["lower_case"] = False
elif dataset == "ptb":
kwargs["special"] = ["<eos>"]
kwargs["lower_case"] = True
elif dataset == "lm1b":
kwargs["special"] = []
kwargs["lower_case"] = False
kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
elif dataset in ["enwik8", "text8"]:
pass
corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
torch.save(corpus, fn)
return corpus | 1 | 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 | safe |
def _load_passages(self):
logger.info(f"Loading passages from {self.index_path}")
passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(passages_path, "rb") as passages_file:
passages = pickle.load(passages_file)
return passages | 1 | 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 | safe |
def _load_passages(self):
logger.info(f"Loading passages from {self.index_path}")
passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(passages_path, "rb") as passages_file:
passages = pickle.load(passages_file)
return passages | 1 | 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 | safe |
def _deserialize_index(self):
logger.info(f"Loading index from {self.index_path}")
resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
self.index = faiss.read_index(resolved_index_path)
resolved_meta_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index_meta.dpr")
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(resolved_meta_path, "rb") as metadata_file:
self.index_id_to_db_id = pickle.load(metadata_file)
assert (
len(self.index_id_to_db_id) == self.index.ntotal
), "Deserialized index_id_to_db_id should match faiss index size" | 1 | 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 | safe |
def _deserialize_index(self):
logger.info(f"Loading index from {self.index_path}")
resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
self.index = faiss.read_index(resolved_index_path)
resolved_meta_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index_meta.dpr")
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(resolved_meta_path, "rb") as metadata_file:
self.index_id_to_db_id = pickle.load(metadata_file)
assert (
len(self.index_id_to_db_id) == self.index.ntotal
), "Deserialized index_id_to_db_id should match faiss index size" | 1 | 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 | safe |
def do_test(proto_ver):
rc = 1
connect_packet = mosq_test.gen_connect("03-pub-qos2-dup-test", proto_ver=proto_ver)
connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver)
mid = 1
publish_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="message", proto_ver=proto_ver, dup=1)
pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver)
disconnect_packet = mosq_test.gen_disconnect(reason_code=130, proto_ver=proto_ver)
port = mosq_test.get_port()
broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port)
try:
sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port)
mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec 1")
mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec 2")
if proto_ver == 5:
mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "disconnect")
rc = 0
else:
try:
mosq_test.do_send_receive(sock, publish_packet, b"", "disconnect1")
rc = 0
except BrokenPipeError:
rc = 0
sock.close()
except Exception as e:
print(e)
except mosq_test.TestError:
pass
finally:
broker.terminate()
broker.wait()
(stdo, stde) = broker.communicate()
if rc:
print(stde.decode('utf-8'))
print("proto_ver=%d" % (proto_ver))
exit(rc) | 1 | Python | CWE-401 | Missing Release of Memory after Effective Lifetime | The product does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
def all_tests():
rc = do_test(proto_ver=4)
if rc:
return rc;
rc = do_test(proto_ver=5)
if rc:
return rc;
return 0 | 1 | Python | CWE-401 | Missing Release of Memory after Effective Lifetime | The product does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
def get_mediastatic_content(url):
if url.startswith(settings.STATIC_URL):
local_path = settings.STATIC_ROOT / url[len(settings.STATIC_URL) :]
elif url.startswith(settings.MEDIA_URL):
local_path = settings.MEDIA_ROOT / url[len(settings.MEDIA_URL) :]
else:
raise FileNotFoundError()
# Prevent directory traversal, make sure the path is inside the media or static root
local_path = local_path.resolve(strict=True)
if not any(
path in local_path.parents
for path in (settings.MEDIA_ROOT, settings.STATIC_ROOT)
):
raise FileNotFoundError()
with open(local_path, "rb") as f:
return f.read() | 1 | 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 | safe |
def get_mediastatic_content(url):
if url.startswith(settings.STATIC_URL):
local_path = settings.STATIC_ROOT / url[len(settings.STATIC_URL) :]
elif url.startswith(settings.MEDIA_URL):
local_path = settings.MEDIA_ROOT / url[len(settings.MEDIA_URL) :]
else:
raise FileNotFoundError()
# Prevent directory traversal, make sure the path is inside the media or static root
local_path = local_path.resolve(strict=True)
if not any(
path in local_path.parents
for path in (settings.MEDIA_ROOT, settings.STATIC_ROOT)
):
raise FileNotFoundError()
with open(local_path, "rb") as f:
return f.read() | 1 | 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 | safe |
def dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = (Path(destination) / path.lstrip("/")).resolve()
if not Path(destination) in path.parents:
raise CommandError("Path traversal detected, aborting.")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
f.write(content)
return content | 1 | 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 | safe |
def dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = (Path(destination) / path.lstrip("/")).resolve()
if not Path(destination) in path.parents:
raise CommandError("Path traversal detected, aborting.")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
f.write(content)
return content | 1 | 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 | safe |
def _find_working_git(self):
test_cmd = 'version'
main_git = app.GIT_PATH or '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) | 1 | 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 | safe |
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.seek(0) | 1 | 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 | safe |
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.seek(0) | 1 | 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 | safe |
def _set_file_hash(self):
with self.open_file() as f:
self.file_hash = hash_filelike(f) | 1 | 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 | safe |
def _set_file_hash(self):
with self.open_file() as f:
self.file_hash = hash_filelike(f) | 1 | 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 | safe |
def get_file_hash(self):
if self.file_hash == "":
self._set_file_hash()
self.save(update_fields=["file_hash"])
return self.file_hash | 1 | 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 | safe |
def get_file_hash(self):
if self.file_hash == "":
self._set_file_hash()
self.save(update_fields=["file_hash"])
return self.file_hash | 1 | 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 | safe |
def test_file_hash(self):
self.assertEqual(
self.document.get_file_hash(), "7d8c4778b182e4f3bd442408c64a6e22a4b0ed85"
)
self.assertEqual(
self.pdf_document.get_file_hash(),
"7d8c4778b182e4f3bd442408c64a6e22a4b0ed85",
)
self.assertEqual(
self.extensionless_document.get_file_hash(),
"7d8c4778b182e4f3bd442408c64a6e22a4b0ed85",
) | 1 | 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 | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.