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 serve_file_unauthed_from_token(
request: HttpRequest, token: str, filename: str
) -> HttpResponseBase:
path_id = get_file_path_id_from_token(token)
if path_id is None:
raise JsonableError(_("Invalid token"))
if path_id.split("/")[-1] != filename:
raise JsonableError(_("Invalid filename"))
mimetype, encoding = guess_type(path_id)
download = mimetype not in INLINE_MIME_TYPES
if settings.LOCAL_UPLOADS_DIR is not None:
return serve_local(request, path_id, download=download)
else:
return serve_s3(request, path_id, download=download) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def get_file_path_id_from_token(token: str) -> Optional[str]:
signer = TimestampSigner(salt=USER_UPLOADS_ACCESS_TOKEN_SALT)
try:
signed_data = base64.b16decode(token).decode()
path_id = signer.unsign(signed_data, max_age=timedelta(seconds=60))
except (BadSignature, binascii.Error):
return None
return path_id | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_local(request: HttpRequest, path_id: str, download: bool = False) -> HttpResponseBase:
assert settings.LOCAL_FILES_DIR is not None
local_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
assert_is_local_storage_path("files", local_path)
if not os.path.isfile(local_path):
return HttpResponseNotFound("<p>File not found</p>")
if settings.DEVELOPMENT:
# In development, we do not have the nginx server to offload
# the response to; serve it directly ourselves.
# FileResponse handles setting Content-Disposition, etc.
response: HttpResponseBase = FileResponse(open(local_path, "rb"), as_attachment=download)
patch_cache_control(response, private=True, immutable=True)
return response
response = internal_nginx_redirect(quote(f"/internal/local/uploads/{path_id}"))
patch_disposition_header(response, local_path, download)
patch_cache_control(response, private=True, immutable=True)
return response | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_local_avatar_unauthed(request: HttpRequest, path: str) -> HttpResponseBase:
"""Serves avatar images off disk, via nginx (or directly in dev), with no auth.
This is done unauthed because these need to be accessed from HTML
emails, where the client does not have any auth. We rely on the
URL being generated using the AVATAR_SALT secret.
"""
if settings.LOCAL_AVATARS_DIR is None:
# We do not expect clients to hit this URL when using the S3
# backend; however, there is no reason to not serve the
# redirect to S3 where the content lives.
return redirect(
get_public_upload_root_url() + path + "?" + request.GET.urlencode(), permanent=True
)
local_path = os.path.join(settings.LOCAL_AVATARS_DIR, path)
assert_is_local_storage_path("avatars", local_path)
if not os.path.isfile(local_path):
return HttpResponseNotFound("<p>File not found</p>")
if settings.DEVELOPMENT:
response: HttpResponseBase = FileResponse(open(local_path, "rb"))
else:
response = internal_nginx_redirect(quote(f"/internal/local/user_avatars/{path}"))
# We do _not_ mark the contents as immutable for caching purposes,
# since the path for avatar images is hashed only by their user-id
# and a salt, and as such are reused when a user's avatar is
# updated.
return response | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_file(
request: HttpRequest,
maybe_user_profile: Union[UserProfile, AnonymousUser],
realm_id_str: str,
filename: str,
url_only: bool = False,
download: bool = False,
) -> HttpResponseBase:
path_id = f"{realm_id_str}/{filename}"
realm = get_valid_realm_from_request(request)
is_authorized = validate_attachment_request(maybe_user_profile, path_id, realm)
if is_authorized is None:
return HttpResponseNotFound(_("<p>File not found.</p>"))
if not is_authorized:
return HttpResponseForbidden(_("<p>You are not authorized to view this file.</p>"))
if url_only:
url = generate_unauthed_file_access_url(path_id)
return json_success(request, data=dict(url=url))
mimetype, encoding = guess_type(path_id)
download = download or mimetype not in INLINE_MIME_TYPES
if settings.LOCAL_UPLOADS_DIR is not None:
return serve_local(request, path_id, download=download)
else:
return serve_s3(request, path_id, download=download) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def generate_unauthed_file_access_url(path_id: str) -> str:
signed_data = TimestampSigner(salt=USER_UPLOADS_ACCESS_TOKEN_SALT).sign(path_id)
token = base64.b16encode(signed_data.encode()).decode()
filename = path_id.split("/")[-1]
return reverse("file_unauthed_from_token", args=[token, filename]) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_s3(request: HttpRequest, path_id: str, download: bool = False) -> HttpResponse:
url = get_signed_upload_url(path_id)
assert url.startswith("https://")
if settings.DEVELOPMENT:
# In development, we do not have the nginx server to offload
# the response to; serve a redirect to the short-lived S3 URL.
# This means the content cannot be cached by the browser, but
# this is acceptable in development.
return redirect(url)
response = internal_nginx_redirect("/internal/s3/" + url[len("https://") :])
patch_disposition_header(response, path_id, download)
patch_cache_control(response, private=True, immutable=True)
return response | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def get_signed_upload_url(path: str, force_download: bool = False) -> str:
client = boto3.client(
"s3",
aws_access_key_id=settings.S3_KEY,
aws_secret_access_key=settings.S3_SECRET_KEY,
region_name=settings.S3_REGION,
endpoint_url=settings.S3_ENDPOINT_URL,
)
params = {
"Bucket": settings.S3_AUTH_UPLOADS_BUCKET,
"Key": path,
}
if force_download:
params["ResponseContentDisposition"] = "attachment"
return client.generate_presigned_url(
ClientMethod="get_object",
Params=params,
ExpiresIn=SIGNED_UPLOAD_URL_DURATION,
HttpMethod="GET",
) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_file_unauthed_from_token(
request: HttpRequest, token: str, filename: str
) -> HttpResponseBase:
path_id = get_file_path_id_from_token(token)
if path_id is None:
raise JsonableError(_("Invalid token"))
if path_id.split("/")[-1] != filename:
raise JsonableError(_("Invalid filename"))
if settings.LOCAL_UPLOADS_DIR is not None:
return serve_local(request, path_id)
else:
return serve_s3(request, path_id) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_local(
request: HttpRequest, path_id: str, force_download: bool = False
) -> HttpResponseBase:
assert settings.LOCAL_FILES_DIR is not None
local_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
assert_is_local_storage_path("files", local_path)
if not os.path.isfile(local_path):
return HttpResponseNotFound("<p>File not found</p>")
mimetype, encoding = guess_type(path_id)
download = force_download or mimetype not in INLINE_MIME_TYPES
if settings.DEVELOPMENT:
# In development, we do not have the nginx server to offload
# the response to; serve it directly ourselves.
# FileResponse handles setting Content-Disposition, etc.
response: HttpResponseBase = FileResponse(
open(local_path, "rb"), as_attachment=download # noqa: SIM115
)
patch_cache_control(response, private=True, immutable=True)
return response
response = internal_nginx_redirect(quote(f"/internal/local/uploads/{path_id}"))
patch_disposition_header(response, local_path, download)
patch_cache_control(response, private=True, immutable=True)
return response | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_s3(request: HttpRequest, path_id: str, force_download: bool = False) -> HttpResponse:
url = get_signed_upload_url(path_id, force_download=force_download)
assert url.startswith("https://")
if settings.DEVELOPMENT:
# In development, we do not have the nginx server to offload
# the response to; serve a redirect to the short-lived S3 URL.
# This means the content cannot be cached by the browser, but
# this is acceptable in development.
return redirect(url)
# We over-escape the path, to work around it being impossible to
# get the _unescaped_ new internal request URI in nginx.
parsed_url = urlparse(url)
assert parsed_url.hostname is not None
assert parsed_url.path is not None
assert parsed_url.query is not None
escaped_path_parts = parsed_url.hostname + quote(parsed_url.path) + "?" + parsed_url.query
response = internal_nginx_redirect("/internal/s3/" + escaped_path_parts)
# It is important that S3 generate both the Content-Type and
# Content-Disposition headers; when the file was uploaded, we
# stored the browser-provided value for the former, and set
# Content-Disposition according to if that was safe. As such,
# only S3 knows if a given attachment is safe to inline; we only
# override Content-Disposition to "attachment", and do so by
# telling S3 that is what we want in the signed URL.
patch_cache_control(response, private=True, immutable=True)
return response | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_file_download_backend(
request: HttpRequest, user_profile: UserProfile, realm_id_str: str, filename: str
) -> HttpResponseBase:
return serve_file(
request, user_profile, realm_id_str, filename, url_only=False, force_download=True
) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def serve_file(
request: HttpRequest,
maybe_user_profile: Union[UserProfile, AnonymousUser],
realm_id_str: str,
filename: str,
url_only: bool = False,
force_download: bool = False,
) -> HttpResponseBase:
path_id = f"{realm_id_str}/{filename}"
realm = get_valid_realm_from_request(request)
is_authorized = validate_attachment_request(maybe_user_profile, path_id, realm)
if is_authorized is None:
return HttpResponseNotFound(_("<p>File not found.</p>"))
if not is_authorized:
return HttpResponseForbidden(_("<p>You are not authorized to view this file.</p>"))
if url_only:
url = generate_unauthed_file_access_url(path_id)
return json_success(request, data=dict(url=url))
if settings.LOCAL_UPLOADS_DIR is not None:
return serve_local(request, path_id, force_download=force_download)
else:
return serve_s3(request, path_id, force_download=force_download) | 1 | Python | CWE-436 | Interpretation Conflict | Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. | https://cwe.mitre.org/data/definitions/436.html | safe |
def create(self, request, *args, **kwargs):
if User.objects.filter(is_superuser=True).exists() and not request.user.is_superuser:
return Response(status=status.HTTP_401_UNAUTHORIZED)
return super(UserViewSet, self).create(request, *args, **kwargs) | 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, request, format=None):
try:
return Response({"isFirstTimeSetup": not User.objects.filter(is_superuser=True).exists()})
except Exception as e:
logger.exception(str(e))
return Response({"message": str(e)}) | 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_permissions(self):
if self.action == "create":
self.permission_classes = [
IsRegistrationAllowed | FirstTimeSetupPermission | IsAdminUser
]
if self.request.method == "POST":
self.permission_classes = (AllowAny,)
return super(UserViewSet, self).get_permissions() | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
async def form(self) -> FormMultiDict:
"""Retrieve form data from the request. If the request is either a 'multipart/form-data' or an
'application/x-www-form- urlencoded', return a FormMultiDict instance populated with the values sent in the
request, otherwise, an empty instance.
Returns:
A FormMultiDict instance
"""
if self._form is Empty:
content_type, options = self.content_type
if content_type == RequestEncodingType.MULTI_PART:
self._form = self.scope["_form"] = form_values = parse_multipart_form( # type: ignore[typeddict-item]
body=await self.body(),
boundary=options.get("boundary", "").encode(),
multipart_form_part_limit=self.app.multipart_form_part_limit,
)
return FormMultiDict(form_values)
if content_type == RequestEncodingType.URL_ENCODED:
self._form = self.scope["_form"] = form_values = parse_url_encoded_form_data( # type: ignore[typeddict-item]
await self.body(),
)
return FormMultiDict(form_values)
return FormMultiDict()
return FormMultiDict(self._form) | 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 |
async def extract_multipart(
connection: "Request[Any, Any]",
) -> Any:
multipart_form_part_limit = (
body_kwarg_multipart_form_part_limit
if body_kwarg_multipart_form_part_limit is not None
else connection.app.multipart_form_part_limit
)
connection.scope["_form"] = form_values = ( # type: ignore[typeddict-item]
connection.scope["_form"] # type: ignore[typeddict-item]
if "_form" in connection.scope
else parse_multipart_form(
body=await connection.body(),
boundary=connection.content_type[-1].get("boundary", "").encode(),
multipart_form_part_limit=multipart_form_part_limit,
)
)
if signature_field.is_non_string_sequence:
return list(form_values.values())
if signature_field.is_simple_type and signature_field.field_type is UploadFile and form_values:
return [v for v in form_values.values() if isinstance(v, UploadFile)][0]
return form_values if form_values or not is_data_optional else None | 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 create_multipart_extractor(
signature_field: "SignatureField", is_data_optional: bool
) -> Callable[["ASGIConnection[Any, Any, Any]"], Coroutine[Any, Any, Any]]:
"""Create a multipart form-data extractor.
Args:
signature_field: A SignatureField instance.
is_data_optional: Boolean dictating whether the field is optional.
Returns:
An extractor function.
"""
body_kwarg_multipart_form_part_limit: Optional[int] = None
if signature_field.kwarg_model and isinstance(signature_field.kwarg_model, BodyKwarg):
body_kwarg_multipart_form_part_limit = signature_field.kwarg_model.multipart_form_part_limit
async def extract_multipart(
connection: "Request[Any, Any]",
) -> Any:
multipart_form_part_limit = (
body_kwarg_multipart_form_part_limit
if body_kwarg_multipart_form_part_limit is not None
else connection.app.multipart_form_part_limit
)
connection.scope["_form"] = form_values = ( # type: ignore[typeddict-item]
connection.scope["_form"] # type: ignore[typeddict-item]
if "_form" in connection.scope
else parse_multipart_form(
body=await connection.body(),
boundary=connection.content_type[-1].get("boundary", "").encode(),
multipart_form_part_limit=multipart_form_part_limit,
)
)
if signature_field.is_non_string_sequence:
return list(form_values.values())
if signature_field.is_simple_type and signature_field.field_type is UploadFile and form_values:
return [v for v in form_values.values() if isinstance(v, UploadFile)][0]
return form_values if form_values or not is_data_optional else None
return cast("Callable[[ASGIConnection[Any, Any, Any]], Coroutine[Any, Any, Any]]", extract_multipart) | 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 parse_body(body: bytes, boundary: bytes, multipart_form_part_limit: int) -> List[bytes]:
"""Split the body using the boundary
and validate the number of form parts is within the allowed limit.
:param body: The form body.
:param boundary: The boundary used to separate form components.
:param multipart_form_part_limit: The limit of allowed form components
:return:
A list of form components.
"""
if not (body and boundary):
return []
form_parts = body.split(boundary, multipart_form_part_limit + 3)[1:-1]
if len(form_parts) > multipart_form_part_limit:
raise ValidationException(
f"number of multipart components exceeds the allowed limit of {multipart_form_part_limit}, "
f"this potentially indicates a DoS attack"
)
return form_parts | 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 app_config_object() -> AppConfig:
return AppConfig(
after_exception=[],
after_request=None,
after_response=None,
after_shutdown=[],
after_startup=[],
allowed_hosts=[],
before_request=None,
before_send=[],
before_shutdown=[],
before_startup=[],
cache_config=DEFAULT_CACHE_CONFIG,
cache_control=None,
compression_config=None,
cors_config=None,
csrf_config=None,
debug=False,
dependencies={},
exception_handlers={},
guards=[],
initial_state={},
logging_config=None,
middleware=[],
multipart_form_part_limit=1000,
on_shutdown=[],
on_startup=[],
openapi_config=None,
opt={},
parameters={},
plugins=[],
response_class=None,
response_cookies=[],
response_headers={},
route_handlers=[],
security=[],
static_files_config=[],
tags=[],
template_config=None,
request_class=None,
websocket_class=None,
etag=None,
) | 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_multipart_form_part_limit(limit: int) -> None:
@post("/")
async def hello_world(data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART)) -> None:
assert len(data) == limit
with create_test_client(route_handlers=[hello_world], multipart_form_part_limit=limit) as client:
data = {str(i): "a" for i in range(limit)}
response = client.post("/", files=data)
assert response.status_code == HTTP_201_CREATED
data = {str(i): "a" for i in range(limit)}
data[str(limit + 1)] = "b"
response = client.post("/", files=data)
assert response.status_code == HTTP_400_BAD_REQUEST | 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 |
async def hello_world(
data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART, multipart_form_part_limit=route_limit)
) -> None:
assert len(data) == route_limit | 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_multipart_form_part_limit_body_param_precedence() -> None:
app_limit = 100
route_limit = 10
@post("/")
async def hello_world(
data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART, multipart_form_part_limit=route_limit)
) -> None:
assert len(data) == route_limit
with create_test_client(route_handlers=[hello_world], multipart_form_part_limit=app_limit) as client:
data = {str(i): "a" for i in range(route_limit)}
response = client.post("/", files=data)
assert response.status_code == HTTP_201_CREATED
data = {str(i): "a" for i in range(route_limit + 1)}
response = client.post("/", files=data)
assert response.status_code == HTTP_400_BAD_REQUEST | 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 |
async def hello_world(data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART)) -> None:
assert len(data) == limit | 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_safe_render(self):
"""Assert that safe Jinja rendering still works."""
site = Site.objects.filter(region__isnull=False).first()
template_code = "{{ obj.region.name }}"
try:
value = render_jinja2(template_code=template_code, context={"obj": site})
except SecurityError:
self.fail("SecurityError raised on safe Jinja template render")
else:
self.assertEqual(value, site.region.name) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def test_sandboxed_render(self):
"""Assert that Jinja template rendering is sandboxed."""
template_code = "{{ ''.__class__.__name__ }}"
with self.assertRaises(SecurityError):
render_jinja2(template_code=template_code, context={}) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def nested_serializer_factory(relation_info, nested_depth):
"""
Return a NestedSerializer representation of a serializer field.
This method should only be called in build_nested_field()
in which relation_info and nested_depth are already given.
"""
nested_serializer_name = f"Nested{nested_depth}{relation_info.related_model.__name__}"
# If we already have built a suitable NestedSerializer we return the cached serializer.
# else we build a new one and store it in the cache for future use.
if nested_serializer_name in NESTED_SERIALIZER_CACHE:
field_class = NESTED_SERIALIZER_CACHE[nested_serializer_name]
field_kwargs = get_nested_relation_kwargs(relation_info)
else:
base_serializer_class = get_serializer_for_model(relation_info.related_model)
class NautobotNestedSerializer(base_serializer_class):
class Meta(base_serializer_class.Meta):
is_nested = True
depth = nested_depth - 1
NautobotNestedSerializer.__name__ = nested_serializer_name
NESTED_SERIALIZER_CACHE[nested_serializer_name] = NautobotNestedSerializer
field_class = NautobotNestedSerializer
field_kwargs = get_nested_relation_kwargs(relation_info)
return field_class, field_kwargs | 1 | Python | CWE-312 | Cleartext Storage of Sensitive Information | The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere. | https://cwe.mitre.org/data/definitions/312.html | safe |
def assert_no_verboten_content(self, response):
"""
Check an API response for content that should not be exposed in the API.
If a specific API has a false failure here (maybe it has security-related strings as model flags or something?),
its test case should overload self.VERBOTEN_STRINGS appropriately.
"""
response_raw_content = response.content.decode(response.charset)
for verboten in self.VERBOTEN_STRINGS:
self.assertNotIn(verboten, response_raw_content) | 1 | Python | CWE-312 | Cleartext Storage of Sensitive Information | The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere. | https://cwe.mitre.org/data/definitions/312.html | safe |
def test_list_objects_depth_1(self):
"""
GET a list of objects using the "?depth=1" parameter.
"""
depth_fields = self.get_depth_fields()
self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
url = f"{self._get_list_url()}?depth=1"
response = self.client.get(url, **self.header)
self.assertHttpStatus(response, status.HTTP_200_OK)
self.assertIsInstance(response.data, dict)
self.assertIn("results", response.data)
self.assertEqual(len(response.data["results"]), self._get_queryset().count())
self.assert_no_verboten_content(response)
for response_data in response.data["results"]:
for field in depth_fields:
self.assertIn(field, response_data)
if isinstance(response_data[field], list):
for entry in response_data[field]:
self.assertIsInstance(entry, dict)
self.assertTrue(is_uuid(entry["id"]))
else:
if response_data[field] is not None:
self.assertIsInstance(response_data[field], dict)
self.assertTrue(is_uuid(response_data[field]["id"])) | 1 | Python | CWE-312 | Cleartext Storage of Sensitive Information | The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere. | https://cwe.mitre.org/data/definitions/312.html | safe |
def test_list_objects(self):
"""
GET a list of objects as an authenticated user with permission to view the objects.
"""
self.assertGreaterEqual(
self._get_queryset().count(),
3,
f"Test requires the creation of at least three {self.model} instances",
)
instance1, instance2 = self._get_queryset()[:2]
# Add object-level permission
obj_perm = users_models.ObjectPermission(
name="Test permission",
constraints={"pk__in": [instance1.pk, instance2.pk]},
actions=["view"],
)
obj_perm.save()
obj_perm.users.add(self.user)
obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
# Try GET to permitted objects
response = self.client.get(self._get_list_url(), **self.header)
self.assertHttpStatus(response, status.HTTP_200_OK)
self.assertIsInstance(response.data, dict)
self.assertIn("results", response.data)
self.assertEqual(len(response.data["results"]), 2)
self.assert_no_verboten_content(response) | 1 | Python | CWE-312 | Cleartext Storage of Sensitive Information | The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere. | https://cwe.mitre.org/data/definitions/312.html | safe |
def render(self, record, bound_column, value): # pylint: disable=arguments-differ
if value:
name = bound_column.name
css_class = getattr(record, f"get_{name}_class")()
label = getattr(record, f"get_{name}_display")()
return format_html('<span class="label label-{}">{}</span>', css_class, label)
return self.default | 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 render(self, value):
return format_html('<span class="label color-block" style="background-color: #{}"> </span>', value) | 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 render(self, record, value): # pylint: disable=arguments-differ
if value:
url = reverse(self.viewname, kwargs=self.view_kwargs)
if self.url_params:
url += "?" + "&".join([f"{k}={getattr(record, v)}" for k, v in self.url_params.items()])
return format_html('<a href="{}">{}</a>', url, value)
return value | 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 header(self):
return mark_safe('<input type="checkbox" class="toggle" title="Toggle all" />') # noqa: S308 | 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 add_html_id(element_str, id_str):
"""Add an HTML `id="..."` attribute to the given HTML element string.
Args:
element_str (str): String describing an HTML element.
id_str (str): String to add as the `id` attribute of the element_str.
Returns:
(str): HTML string with added `id`.
Example:
>>> add_html_id("<div></div>", "my-div")
'<div id="my-div"></div>'
>>> add_html_id('<a href="..." title="...">Hello!</a>', "my-a")
'<a id="my-a" href="..." title="...">Hello!</a>'
"""
match = re.match(r"^(.*?<\w+) ?(.*)$", element_str, flags=re.DOTALL)
if not match:
return element_str
return mark_safe(match.group(1) + format_html(' id="{}" ', id_str) + match.group(2)) # noqa: S308 | 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 render_boolean(value):
"""Render HTML from a computed boolean value.
Args:
value (any): Input value, can be any variable.
A truthy value (for example non-empty string / True / non-zero number) is considered True.
A falsey value other than None (for example "" or 0 or False) is considered False.
A value of None is considered neither True nor False.
Returns:
(str): HTML
'<span class="text-success"><i class="mdi mdi-check-bold" title="Yes"></i></span>' if True value
- or -
'<span class="text-muted">—</span>' if None value
- or -
'<span class="text-danger"><i class="mdi mdi-close-thick" title="No"></i></span>' if False value
Examples:
>>> render_boolean(None)
'<span class="text-muted">—</span>'
>>> render_boolean(True or "arbitrary string" or 1)
'<span class="text-success"><i class="mdi mdi-check-bold" title="Yes"></i></span>'
>>> render_boolean(False or "" or 0)
'<span class="text-danger"><i class="mdi mdi-close-thick" title="No"></i></span>'
"""
if value is None:
return HTML_NONE
if bool(value):
return HTML_TRUE
return HTML_FALSE | 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 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 | 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 placeholder(value):
"""Render a muted placeholder if value is falsey, else render the value.
Args:
value (any): Input value, can be any variable.
Returns:
(str): Placeholder in HTML, or the string representation of the value.
Example:
>>> placeholder("")
'<span class="text-muted">—</span>'
>>> placeholder("hello")
"hello"
"""
if value:
return value
return HTML_NONE | 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 render_jinja2(template_code, context):
"""
Render a Jinja2 template with the provided context. Return the rendered content.
"""
rendering_engine = engines["jinja"]
template = rendering_engine.from_string(template_code)
# For reasons unknown to me, django-jinja2 `template.render()` implicitly calls `mark_safe()` on the rendered text.
# This is a security risk in general, especially so in our case because we're often using this function to render
# a user-provided template and don't want to open ourselves up to script injection or similar issues.
# There's no `mark_unsafe()` function, but concatenating a SafeString to an ordinary string (even "") suffices.
return "" + template.render(context=context) | 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 successful_post(self, request, obj, created, logger):
"""Callback after the form is successfully saved but before redirecting the user."""
verb = "Created" if created else "Modified"
msg = f"{verb} {self.queryset.model._meta.verbose_name}"
logger.info(f"{msg} {obj} (PK: {obj.pk})")
if hasattr(obj, "get_absolute_url"):
msg = format_html('{} <a href="{}">{}</a>', msg, obj.get_absolute_url(), obj)
else:
msg = format_html("{} {}", msg, obj)
messages.success(request, msg) | 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 filter_queryset(self, queryset):
"""
Filter a query with request querystrings.
"""
if self.filterset_class is not None:
self.filter_params = self.get_filter_params(self.request)
self.filterset = self.filterset_class(self.filter_params, queryset)
queryset = self.filterset.qs
if not self.filterset.is_valid():
messages.error(
self.request,
format_html("Invalid filters were specified: {}", self.filterset.errors),
)
queryset = queryset.none()
return queryset | 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 _process_create_or_update_form(self, form):
"""
Helper method to create or update an object after the form is validated successfully.
"""
request = self.request
queryset = self.get_queryset()
with transaction.atomic():
object_created = not form.instance.present_in_database
obj = self.form_save(form)
# Check that the new object conforms with any assigned object-level permissions
queryset.get(pk=obj.pk)
if hasattr(form, "save_note") and callable(form.save_note):
form.save_note(instance=obj, user=request.user)
msg = f'{"Created" if object_created else "Modified"} {queryset.model._meta.verbose_name}'
self.logger.info(f"{msg} {obj} (PK: {obj.pk})")
if hasattr(obj, "get_absolute_url"):
msg = format_html('{} <a href="{}">{}</a>', msg, obj.get_absolute_url(), obj)
else:
msg = format_html("{} {}", msg, obj)
messages.success(request, msg)
if "_addanother" in request.POST:
# If the object has clone_fields, pre-populate a new instance of the form
if hasattr(obj, "clone_fields"):
url = f"{request.path}?{prepare_cloned_fields(obj)}"
self.success_url = url
self.success_url = request.get_full_path()
else:
return_url = form.cleaned_data.get("return_url")
if return_url is not None and is_safe_url(url=return_url, allowed_hosts=request.get_host()):
self.success_url = return_url
else:
self.success_url = self.get_return_url(request, obj) | 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 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 = format_html(
"Unable to delete <strong>{}</strong>. {} dependent objects were found: ",
", ".join(str(obj) for obj in obj_list),
protected_count,
)
# Append dependent objects to error message
err_message += format_html_join(
", ",
'<a href="{}">{}</a>',
((dependent.get_absolute_url(), dependent) for dependent in protected_objects[:50]),
)
messages.error(request, err_message) | 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 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 = format_html('Added member <a href="{}">{}</a>', device.get_absolute_url(), device)
messages.success(request, 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),
},
) | 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 render_description(self, record):
if record.description:
return render_markdown(record.description)
return self.default | 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 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 ""
return format_html_join(
"\n",
'<tr><td><span title="{}">{}</span></td><td>{}</td></tr>',
((label, label, value) for label, value in fields.items()),
) | 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 _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) # noqa: S308 | 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_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) | 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_view_object_with_computed_field(self):
"""Ensure that the computed field template is rendered."""
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertIn(f"FOO {self.location_type.name} BAR", content, content) | 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_view_object_with_unsafe_custom_link_name(self):
"""Ensure that custom links can't be used as a vector for injecting scripts or breaking HTML."""
customlink = CustomLink(
content_type=ContentType.objects.get_for_model(Location),
name='<script>alert("Hello World")</script>',
text="Hello",
target_url="http://example.com/?location={{ obj.name ", # intentionally bad jinja2 to trigger error case
new_window=False,
)
customlink.validated_save()
location_type = LocationType.objects.get(name="Campus")
status = Status.objects.get_for_model(Location).first()
location = Location(name="Test Location", location_type=location_type, status=status)
location.save()
response = self.client.get(location.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content) | 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_view_object_with_unsafe_name(self):
"""Ensure that JobButton names can't be used as a vector for XSS."""
self.job_button.text = "JobButton {{ obj"
self.job_button.name = '<script>alert("Yo")</script>'
self.job_button.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content) | 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_view_object_with_computed_field_unsafe_template(self):
"""Ensure that computed field templates can't be used as an XSS vector."""
self.computedfield.template = '<script>alert("Hello world!"</script>'
self.computedfield.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content) | 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_view_object_with_unsafe_custom_link_url(self):
"""Ensure that custom links can't be used as a vector for injecting scripts or breaking HTML."""
customlink = CustomLink(
content_type=ContentType.objects.get_for_model(Location),
name="Test",
text="Hello",
target_url='"><script>alert("Hello world!")</script><a href="',
new_window=False,
)
customlink.validated_save()
location_type = LocationType.objects.get(name="Campus")
status = Status.objects.get_for_model(Location).first()
location = Location(name="Test Location", location_type=location_type, status=status)
location.save()
response = self.client.get(location.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content)
self.assertIn(format_html('<a href="{}"', customlink.target_url), content, content) | 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_view_object_with_computed_field_unsafe_fallback_value(self):
"""Ensure that computed field fallback values can't be used as an XSS vector."""
self.computedfield.template = "FOO {{ obj."
self.computedfield.fallback_value = '<script>alert("Hello world!"</script>'
self.computedfield.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content) | 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 setUp(self):
super().setUp()
self.computedfield = ComputedField(
content_type=ContentType.objects.get_for_model(LocationType),
key="test",
label="Computed Field",
template="FOO {{ obj.name }} BAR",
fallback_value="Fallback Value",
weight=100,
)
self.computedfield.validated_save()
self.location_type = LocationType.objects.get(name="Campus") | 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_view_object_with_computed_field_fallback_value(self):
"""Ensure that the fallback_value is rendered if the template fails to render."""
# Make the template invalid to demonstrate the fallback value
self.computedfield.template = "FOO {{ obj."
self.computedfield.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertIn("Fallback Value", content, content) | 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_view_object_with_unsafe_text(self):
"""Ensure that JobButton text can't be used as a vector for XSS."""
self.job_button.text = '<script>alert("Hello world!")</script>'
self.job_button.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content)
# Make sure grouped rendering is safe too
self.job_button.group = '<script>alert("Goodbye")</script>'
self.job_button.validated_save()
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content) | 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_view_object_with_job_button(self):
"""Ensure that the job button is rendered."""
response = self.client.get(self.location_type.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertIn(f"JobButton {self.location_type.name}", content, content) | 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_view_object_with_unsafe_custom_link_text(self):
"""Ensure that custom links can't be used as a vector for injecting scripts or breaking HTML."""
customlink = CustomLink(
content_type=ContentType.objects.get_for_model(Location),
name="Test",
text='<script>alert("Hello world!")</script>',
target_url="http://example.com/?location=None",
new_window=False,
)
customlink.validated_save()
location_type = LocationType.objects.get(name="Campus")
status = Status.objects.get_for_model(Location).first()
location = Location(name="Test Location", location_type=location_type, status=status)
location.save()
response = self.client.get(location.get_absolute_url(), follow=True)
self.assertEqual(response.status_code, 200)
content = extract_page_body(response.content.decode(response.charset))
self.assertNotIn("<script>alert", content, content)
self.assertIn("<script>alert", content, content)
self.assertIn(format_html('<a href="{}"', customlink.target_url), content, content) | 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 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 = format_html('Job enqueued. <a href="{}">Click here for the results.</a>', result.get_absolute_url())
messages.info(request=request, message=msg)
return redirect(post_data["redirect_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 tests(context, lint_only=False, keepdb=False):
"""Run all linters and unit tests."""
black(context)
flake8(context)
prettier(context)
eslint(context)
hadolint(context)
markdownlint(context)
yamllint(context)
ruff(context)
pylint(context)
check_migrations(context)
check_schema(context)
build_and_check_docs(context)
if not lint_only:
unittest(context, keepdb=keepdb) | 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 ruff(context, output_format="text"):
"""Run ruff to perform static analysis and linting."""
command = f"ruff --output-format {output_format} development/ examples/ nautobot/ tasks.py"
run_command(context, command) | 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_get_file_anonymous(self):
self.client.logout()
for url in self.urls:
with self.subTest(url):
response = self.client.get(url)
self.assertHttpStatus(response, 403) | 1 | 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 | safe |
def test_get_file_without_permission(self):
for url in self.urls:
with self.subTest(url):
response = self.client.get(url)
self.assertHttpStatus(response, 403) | 1 | 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 | safe |
def setUp(self):
super().setUp()
self.test_file_1 = SimpleUploadedFile(name="test_file_1.txt", content=b"I am content.\n")
self.file_proxy_1 = FileProxy.objects.create(name=self.test_file_1.name, file=self.test_file_1)
self.test_file_2 = SimpleUploadedFile(name="test_file_2.txt", content=b"I am content.\n")
self.file_proxy_2 = FileProxy.objects.create(name=self.test_file_2.name, file=self.test_file_2)
self.urls = [
f"{reverse('db_file_storage.download_file')}?name={self.file_proxy_1.file.name}",
f"{reverse('db_file_storage.get_file')}?name={self.file_proxy_1.file.name}",
] | 1 | 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 | safe |
def test_get_object_with_permission(self):
self.add_permissions(get_permission_for_model(FileProxy, "view"))
for url in self.urls:
with self.subTest(url):
response = self.client.get(url)
self.assertHttpStatus(response, 200) | 1 | 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 | safe |
def test_get_object_with_constrained_permission(self):
obj_perm = ObjectPermission(
name="Test permission",
constraints={"pk": self.file_proxy_1.pk},
actions=["view"],
)
obj_perm.save()
obj_perm.users.add(self.user)
obj_perm.object_types.add(ContentType.objects.get_for_model(FileProxy))
for url in self.urls:
with self.subTest(url):
response = self.client.get(url)
self.assertHttpStatus(response, 200)
for url in [
f"{reverse('db_file_storage.download_file')}?name={self.file_proxy_2.file.name}",
f"{reverse('db_file_storage.get_file')}?name={self.file_proxy_2.file.name}",
]:
with self.subTest(url):
response = self.client.get(url)
self.assertHttpStatus(response, 404) | 1 | 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 | safe |
def get_file_with_authorization(request, *args, **kwargs):
"""Patch db_file_storage view with authentication."""
# Make sure user has permissions
queryset = FileProxy.objects.restrict(request.user, "view")
get_object_or_404(queryset, file=request.GET.get("name"))
return get_file(request, *args, **kwargs) | 1 | 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 | safe |
def default_helptext(self):
# TODO: Port Markdown cheat sheet to internal documentation
return format_html(
'<i class="mdi mdi-information-outline"></i> '
'<a href="https://www.markdownguide.org/cheat-sheet/#basic-syntax" rel="noopener noreferrer">Markdown</a> '
'syntax is supported, as well as <a href="{}#render_markdown">a limited subset of HTML</a>.',
static("docs/user-guide/platform-functionality/template-filters.html"),
) | 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 render_markdown(value):
"""
Render text as Markdown
Example:
{{ text | render_markdown }}
"""
# Render Markdown
html = markdown(value, extensions=["fenced_code", "tables"])
# Sanitize rendered HTML
html = nautobot_logging.clean_html(html)
return mark_safe(html) # noqa: S308 # suspicious-mark-safe-usage, OK here since we sanitized the string earlier | 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_render_markdown_security(self):
self.assertEqual(helpers.render_markdown('<script>alert("XSS")</script>'), "")
self.assertHTMLEqual(
helpers.render_markdown('[link](javascript:alert("XSS"))'),
'<p><a title="XSS" rel="noopener noreferrer">link</a>)</p>', # the trailing ) seems weird to me, but...
)
self.assertHTMLEqual(
helpers.render_markdown(
"[link\nJS]"
"(javascript:" # '(javascript:'
"alert('XSS'))" # 'alert("XSS"))'
),
'<p><a rel="noopener noreferrer">link JS</a></p>',
) | 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_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/" rel="noopener noreferrer">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>",
) | 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_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.assertHTMLEqual(
helpers.render_markdown("[I am a link](https://www.example.com)"),
'<p><a href="https://www.example.com" rel="noopener noreferrer">I am a link</a></p>',
) | 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_500_custom_support_message(self, mock_get):
"""Nautobot's custom 500 page should be used and should include a custom support message if defined."""
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) | 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_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/" rel="noopener noreferrer">Network to Code\'s '
"Slack community</a> and post your question.",
response_content,
) | 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_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/" rel="noopener noreferrer">Network to Code\'s '
"Slack community</a> and post your question.",
response_content,
) | 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 clean_html(html):
"""Use nh3/ammonia to strip out all HTML tags and attributes except those explicitly permitted."""
return nh3.clean(
html,
tags=constants.HTML_ALLOWED_TAGS,
attributes=constants.HTML_ALLOWED_ATTRIBUTES,
url_schemes=set(settings.ALLOWED_URL_SCHEMES),
) | 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 default_helptext(self):
return "Also used as the help text when editing models using this custom field.<br>" + super().default_helptext | 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 testConv3DTransposeZeroShapeDoNotRaiseError(self):
with self.cached_session():
x_value = np.zeros([10, 0, 2, 3, 3])
f_value = np.ones((3, 3, 3, 3, 3))
y_shape = np.stack([10, 0, 2, 3, 3])
output = nn_ops.conv3d_transpose(
x_value,
f_value,
y_shape,
strides=(1, 1, 1),
data_format="NDHWC",
padding="SAME",
)
_ = self.evaluate(output) | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
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") | 1 | Python | NVD-CWE-noinfo | null | null | null | safe |
def test_quantize_and_dequantize_v2():
gen_array_ops.quantize_and_dequantize_v2(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff) | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def test_quantize_and_dequantize_v2():
gen_array_ops.quantize_and_dequantize_v2(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff) | 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 testInvalidAxis(self):
@def_function.function
def test_quantize_and_dequantize_v2():
gen_array_ops.quantize_and_dequantize_v2(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v3():
gen_array_ops.quantize_and_dequantize_v3(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
num_bits=1,
signed_input=True,
range_given=True,
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v4():
gen_array_ops.quantize_and_dequantize_v4(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v4_grad():
gen_array_ops.quantize_and_dequantize_v4_grad(
gradients=[2.5],
input=[2.5],
input_min=[1.0],
input_max=[10.0],
axis=0x7fffffff)
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v2()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v3()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v4()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v4_grad() | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def testInvalidAxis(self):
@def_function.function
def test_quantize_and_dequantize_v2():
gen_array_ops.quantize_and_dequantize_v2(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v3():
gen_array_ops.quantize_and_dequantize_v3(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
num_bits=1,
signed_input=True,
range_given=True,
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v4():
gen_array_ops.quantize_and_dequantize_v4(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff)
@def_function.function
def test_quantize_and_dequantize_v4_grad():
gen_array_ops.quantize_and_dequantize_v4_grad(
gradients=[2.5],
input=[2.5],
input_min=[1.0],
input_max=[10.0],
axis=0x7fffffff)
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v2()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v3()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v4()
with self.assertRaisesRegex(
ValueError, "Axis cannot be >= kint32max value, got 2147483647"):
test_quantize_and_dequantize_v4_grad() | 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 test_quantize_and_dequantize_v4_grad():
gen_array_ops.quantize_and_dequantize_v4_grad(
gradients=[2.5],
input=[2.5],
input_min=[1.0],
input_max=[10.0],
axis=0x7fffffff) | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def test_quantize_and_dequantize_v4_grad():
gen_array_ops.quantize_and_dequantize_v4_grad(
gradients=[2.5],
input=[2.5],
input_min=[1.0],
input_max=[10.0],
axis=0x7fffffff) | 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 test_quantize_and_dequantize_v3():
gen_array_ops.quantize_and_dequantize_v3(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
num_bits=1,
signed_input=True,
range_given=True,
narrow_range=True,
axis=0x7fffffff) | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def test_quantize_and_dequantize_v3():
gen_array_ops.quantize_and_dequantize_v3(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
num_bits=1,
signed_input=True,
range_given=True,
narrow_range=True,
axis=0x7fffffff) | 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 test_quantize_and_dequantize_v4():
gen_array_ops.quantize_and_dequantize_v4(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff) | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def test_quantize_and_dequantize_v4():
gen_array_ops.quantize_and_dequantize_v4(
input=[2.5],
input_min=[1.0],
input_max=[10.0],
signed_input=True,
num_bits=1,
range_given=True,
round_mode="HALF_TO_EVEN",
narrow_range=True,
axis=0x7fffffff) | 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 testAvgPoolGradInvalidStrideRaiseErrorProperly(self):
with self.assertRaises(errors_impl.InvalidArgumentError):
with self.cached_session():
orig_input_shape = [11, 9, 78, 9]
grad = constant_op.constant(
0.1, shape=[16, 16, 16, 16], dtype=dtypes.float64)
t = gen_nn_ops.AvgPoolGrad(
orig_input_shape=orig_input_shape,
grad=grad,
ksize=[1, 40, 128, 1],
strides=[1, 128, 128, 30],
padding="SAME",
data_format="NHWC")
self.evaluate(t) | 1 | Python | CWE-120 | Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') | The product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. | https://cwe.mitre.org/data/definitions/120.html | safe |
def testAvgPoolGradInvalidStrideRaiseErrorProperly(self):
with self.assertRaises(errors_impl.InvalidArgumentError):
with self.cached_session():
orig_input_shape = [11, 9, 78, 9]
grad = constant_op.constant(
0.1, shape=[16, 16, 16, 16], dtype=dtypes.float64)
t = gen_nn_ops.AvgPoolGrad(
orig_input_shape=orig_input_shape,
grad=grad,
ksize=[1, 40, 128, 1],
strides=[1, 128, 128, 30],
padding="SAME",
data_format="NHWC")
self.evaluate(t) | 1 | Python | CWE-122 | Heap-based Buffer Overflow | A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). | https://cwe.mitre.org/data/definitions/122.html | safe |
def testPoolingRatioIllegalSmallValue(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) | 1 | 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 | safe |
def testPoolingIllegalRatioForBatch(self):
with self.cached_session() as _:
with self.assertRaises(errors.UnimplementedError):
result = nn_ops.gen_nn_ops.fractional_avg_pool(
np.zeros([3, 30, 50, 3]),
[2, 3, 1.5, 1],
True,
True)
self.evaluate(result) | 1 | 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 | safe |
def testPoolingRatioIllegalSmallValue(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) | 1 | 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 | safe |
def testPoolingIllegalRatioForBatch(self):
with self.cached_session() as _:
with self.assertRaises(errors.UnimplementedError):
result = nn_ops.fractional_max_pool(
np.zeros([3, 30, 50, 3]),
[2, 3, 1.5, 1],
True,
True)
self.evaluate(result) | 1 | 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 | safe |
def testInvalidSparseInputs(self):
with test_util.force_cpu():
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
".*Index rank .* and shape rank .* do not match.*",
):
self.evaluate(
gen_sparse_ops.sparse_sparse_maximum(
[[1]], [0], [2], [[]], [1], [2]
)
) | 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 testTensorArrayConcatFailsWhenMissingStepContainer(self):
@def_function.function
def func():
y = data_flow_ops.TensorArrayConcatV2(
handle=["a", "b"],
flow_in=0.1,
dtype=dtypes.int32,
element_shape_except0=1,
)
return y
with self.assertRaisesRegex(
errors.NotFoundError, "Container .* does not exist"
):
self.evaluate(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 func():
y = data_flow_ops.TensorArrayConcatV2(
handle=["a", "b"],
flow_in=0.1,
dtype=dtypes.int32,
element_shape_except0=1,
)
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.