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 test_it_ignores_bad_tz(self):
form = {"identity": "[email protected]", "tz": "Foo/Bar"}
r = self.client.post("/accounts/signup/", form)
self.assertContains(r, "Account created")
self.assertIn("auto-login", r.cookies)
profile = Profile.objects.get()
self.assertEqual(profile.tz, "UTC") | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def test_it_works(self):
form = {"identity": "[email protected]", "tz": "Europe/Riga"}
r = self.client.post("/accounts/signup/", form)
self.assertContains(r, "Account created")
self.assertIn("auto-login", r.cookies)
# An user should have been created
user = User.objects.get()
# A profile should have been created
profile = Profile.objects.get()
self.assertEqual(profile.check_limit, 10000)
self.assertEqual(profile.sms_limit, 10000)
self.assertEqual(profile.call_limit, 10000)
self.assertEqual(profile.tz, "Europe/Riga")
# And email sent
self.assertEqual(len(mail.outbox), 1)
subject = "Log in to %s" % settings.SITE_NAME
self.assertEqual(mail.outbox[0].subject, subject)
# A project should have been created
project = Project.objects.get()
self.assertEqual(project.owner, user)
self.assertEqual(project.badge_key, user.username)
# And check should be associated with the new user
check = Check.objects.get()
self.assertEqual(check.name, "My First Check")
self.assertEqual(check.slug, "my-first-check")
self.assertEqual(check.project, project)
# A channel should have been created
channel = Channel.objects.get()
self.assertEqual(channel.project, project) | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def login(request):
form = forms.PasswordLoginForm()
magic_form = forms.EmailLoginForm()
if request.method == "POST":
if request.POST.get("action") == "login":
form = forms.PasswordLoginForm(request.POST)
if form.is_valid():
return _check_2fa(request, form.user)
else:
magic_form = forms.EmailLoginForm(request.POST)
if magic_form.is_valid():
redirect_url = request.GET.get("next")
if not _allow_redirect(redirect_url):
redirect_url = None
profile = Profile.objects.for_user(magic_form.user)
profile.send_instant_login_link(redirect_url=redirect_url)
response = redirect("hc-login-link-sent")
# check_token looks for this cookie to decide if
# it needs to do the extra POST step.
response.set_cookie("auto-login", "1", max_age=300, httponly=True)
return response
if request.user.is_authenticated:
return _redirect_after_login(request)
bad_link = request.session.pop("bad_link", None)
ctx = {
"page": "login",
"form": form,
"magic_form": magic_form,
"bad_link": bad_link,
"registration_open": settings.REGISTRATION_OPEN,
"support_email": settings.SUPPORT_EMAIL,
}
return render(request, "accounts/login.html", ctx) | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def signup(request):
if not settings.REGISTRATION_OPEN:
return HttpResponseForbidden()
ctx = {}
form = forms.SignupForm(request.POST)
if form.is_valid():
email = form.cleaned_data["identity"]
tz = form.cleaned_data["tz"]
user = _make_user(email, tz)
profile = Profile.objects.for_user(user)
profile.send_instant_login_link()
ctx["created"] = True
else:
ctx = {"form": form}
response = render(request, "accounts/signup_result.html", ctx)
if ctx.get("created"):
response.set_cookie("auto-login", "1", max_age=300, httponly=True)
return response | 0 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | vulnerable |
def _validate_source(source: str, run_id: str) -> None:
if not is_local_uri(source):
return
if run_id:
store = _get_tracking_store()
run = store.get_run(run_id)
source = pathlib.Path(local_file_uri_to_path(source)).resolve()
run_artifact_dir = pathlib.Path(local_file_uri_to_path(run.info.artifact_uri)).resolve()
if run_artifact_dir in [source, *source.parents]:
return
raise MlflowException(
f"Invalid source: '{source}'. To use a local path as source, the run_id request parameter "
"has to be specified and the local path has to be contained within the artifact directory "
"of the run specified by the run_id.",
INVALID_PARAMETER_VALUE,
) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def is_local_uri(uri):
"""Returns true if this is a local file path (/foo or file:/foo)."""
if uri == "databricks":
return False
if is_windows() and uri.startswith("\\\\"):
# windows network drive path looks like: "\\<server name>\path\..."
return False
parsed_uri = urllib.parse.urlparse(uri)
if parsed_uri.hostname:
return False
scheme = parsed_uri.scheme
if scheme == "" or scheme == "file":
return True
if is_windows() and len(scheme) == 1 and scheme.lower() == pathlib.Path(uri).drive.lower()[0]:
return True
return False | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def _init_server(backend_uri, root_artifact_uri):
"""
Launch a new REST server using the tracking store specified by backend_uri and root artifact
directory specified by root_artifact_uri.
:returns A tuple (url, process) containing the string URL of the server and a handle to the
server process (a multiprocessing.Process object).
"""
mlflow.set_tracking_uri(None)
server_port = get_safe_port()
process = Popen(
[
sys.executable,
"-c",
f'from mlflow.server import app; app.run("{LOCALHOST}", {server_port})',
],
env={
**os.environ,
BACKEND_STORE_URI_ENV_VAR: backend_uri,
ARTIFACT_ROOT_ENV_VAR: root_artifact_uri,
},
)
_await_server_up_or_die(server_port)
url = f"http://{LOCALHOST}:{server_port}"
_logger.info(f"Launching tracking server against backend URI {backend_uri}. Server URL: {url}")
return url, process | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_create_model_version_with_path_source(mlflow_client):
name = "mode"
mlflow_client.create_registered_model(name)
exp_id = mlflow_client.create_experiment("test")
run = mlflow_client.create_run(experiment_id=exp_id)
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
"run_id": run.info.run_id,
},
)
assert response.status_code == 200
# run_id is not specified
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": run.info.artifact_uri[len("file://") :],
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"]
# run_id is specified but source is not in the run's artifact directory
response = requests.post(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/model-versions/create",
json={
"name": name,
"source": "/tmp",
"run_id": run.info.run_id,
},
)
assert response.status_code == 400
assert "To use a local path as a model version" in response.json()["message"] | 0 | Python | CWE-23 | Relative Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/23.html | vulnerable |
def predict(self, model_uri, input_path, output_path, content_type):
"""
Generate predictions using generic python model saved with MLflow. The expected format of
the input JSON is the Mlflow scoring format.
Return the prediction results as a JSON.
"""
local_path = _download_artifact_from_uri(model_uri)
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
local_uri = path_to_local_file_uri(local_path)
if self._env_manager != _EnvManager.LOCAL:
command = (
'python -c "from mlflow.pyfunc.scoring_server import _predict; _predict('
"model_uri={model_uri}, "
"input_path={input_path}, "
"output_path={output_path}, "
"content_type={content_type})"
'"'
).format(
model_uri=repr(local_uri),
input_path=repr(input_path),
output_path=repr(output_path),
content_type=repr(content_type),
)
return self.prepare_env(local_path).execute(command)
else:
scoring_server._predict(local_uri, input_path, output_path, content_type) | 0 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | vulnerable |
def predict(self, model_uri, input_path, output_path, content_type):
"""
Generate predictions using generic python model saved with MLflow. The expected format of
the input JSON is the Mlflow scoring format.
Return the prediction results as a JSON.
"""
local_path = _download_artifact_from_uri(model_uri)
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
local_uri = path_to_local_file_uri(local_path)
if self._env_manager != _EnvManager.LOCAL:
command = (
'python -c "from mlflow.pyfunc.scoring_server import _predict; _predict('
"model_uri={model_uri}, "
"input_path={input_path}, "
"output_path={output_path}, "
"content_type={content_type})"
'"'
).format(
model_uri=repr(local_uri),
input_path=repr(input_path),
output_path=repr(output_path),
content_type=repr(content_type),
)
return self.prepare_env(local_path).execute(command)
else:
scoring_server._predict(local_uri, input_path, output_path, content_type) | 0 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
def get_cmd(
model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None
) -> Tuple[str, Dict[str, str]]:
local_uri = path_to_local_file_uri(model_uri)
timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get()
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
if os.name != "nt":
args = [f"--timeout={timeout}"]
if port and host:
args.append(f"-b {host}:{port}")
elif host:
args.append(f"-b {host}")
if nworkers:
args.append(f"-w {nworkers}")
command = (
f"gunicorn {' '.join(args)} ${{GUNICORN_CMD_ARGS}}"
" -- mlflow.pyfunc.scoring_server.wsgi:app"
)
else:
args = []
if host:
args.append(f"--host={host}")
if port:
args.append(f"--port={port}")
command = (
f"waitress-serve {' '.join(args)} "
"--ident=mlflow mlflow.pyfunc.scoring_server.wsgi:app"
)
command_env = os.environ.copy()
command_env[_SERVER_MODEL_PATH] = local_uri
return command, command_env | 0 | Python | CWE-36 | Absolute Path Traversal | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/36.html | vulnerable |
def get_cmd(
model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None
) -> Tuple[str, Dict[str, str]]:
local_uri = path_to_local_file_uri(model_uri)
timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get()
# NB: Absolute windows paths do not work with mlflow apis, use file uri to ensure
# platform compatibility.
if os.name != "nt":
args = [f"--timeout={timeout}"]
if port and host:
args.append(f"-b {host}:{port}")
elif host:
args.append(f"-b {host}")
if nworkers:
args.append(f"-w {nworkers}")
command = (
f"gunicorn {' '.join(args)} ${{GUNICORN_CMD_ARGS}}"
" -- mlflow.pyfunc.scoring_server.wsgi:app"
)
else:
args = []
if host:
args.append(f"--host={host}")
if port:
args.append(f"--port={port}")
command = (
f"waitress-serve {' '.join(args)} "
"--ident=mlflow mlflow.pyfunc.scoring_server.wsgi:app"
)
command_env = os.environ.copy()
command_env[_SERVER_MODEL_PATH] = local_uri
return command, command_env | 0 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
def create_user():
content_type = request.headers.get("Content-Type")
if content_type == "application/x-www-form-urlencoded":
username = request.form["username"]
password = request.form["password"]
if store.has_user(username):
flash(f"Username has already been taken: {username}")
return alert(href=SIGNUP)
store.create_user(username, password)
flash(f"Successfully signed up user: {username}")
return alert(href=HOME)
elif content_type == "application/json":
username = _get_request_param("username")
password = _get_request_param("password")
user = store.create_user(username, password)
return make_response({"user": user.to_json()})
else:
return make_response(f"Invalid content type: '{content_type}'", 400) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def to_html(self) -> str:
"""
Returns a rendered HTML representing the content of the tab.
:return: a HTML string
"""
import jinja2
j2_env = jinja2.Environment(loader=jinja2.BaseLoader()).from_string(self.template)
return j2_env.render({**self._context}) | 0 | Python | CWE-1336 | Improper Neutralization of Special Elements Used in a Template Engine | The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine. | https://cwe.mitre.org/data/definitions/1336.html | vulnerable |
def is_local_uri(uri, is_tracking_or_registry_uri=True):
"""
Returns true if the specified URI is a local file path (/foo or file:/foo).
:param uri: The URI.
:param is_tracking_uri: Whether or not the specified URI is an MLflow Tracking or MLflow
Model Registry URI. Examples of other URIs are MLflow artifact URIs,
filesystem paths, etc.
"""
if uri == "databricks" and is_tracking_or_registry_uri:
return False
if is_windows() and uri.startswith("\\\\"):
# windows network drive path looks like: "\\<server name>\path\..."
return False
parsed_uri = urllib.parse.urlparse(uri)
if parsed_uri.hostname and not (
parsed_uri.hostname == "."
or parsed_uri.hostname.startswith("localhost")
or parsed_uri.hostname.startswith("127.0.0.1")
):
return False
scheme = parsed_uri.scheme
if scheme == "" or scheme == "file":
return True
if is_windows() and len(scheme) == 1 and scheme.lower() == pathlib.Path(uri).drive.lower()[0]:
return True
return False | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def validate_path_is_safe(path):
"""
Validates that the specified path is safe to join with a trusted prefix. This is a security
measure to prevent path traversal attacks.
A valid path should:
not contain separators other than '/'
not contain .. to navigate to parent dir in path
not be an absolute path
"""
from mlflow.utils.file_utils import local_file_uri_to_path
exc = MlflowException(f"Invalid path: {path}", error_code=INVALID_PARAMETER_VALUE)
if any((s in path) for s in ("#", "%23")):
raise exc
if is_file_uri(path):
path = local_file_uri_to_path(path)
if (
any((s in path) for s in _OS_ALT_SEPS)
or ".." in path.split("/")
or pathlib.PureWindowsPath(path).is_absolute()
or pathlib.PurePosixPath(path).is_absolute()
or (is_windows() and len(path) >= 2 and path[1] == ":")
):
raise exc | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def validate_path_is_safe(path):
"""
Validates that the specified path is safe to join with a trusted prefix. This is a security
measure to prevent path traversal attacks.
A valid path should:
not contain separators other than '/'
not contain .. to navigate to parent dir in path
not be an absolute path
"""
from mlflow.utils.file_utils import local_file_uri_to_path
exc = MlflowException(f"Invalid path: {path}", error_code=INVALID_PARAMETER_VALUE)
if any((s in path) for s in ("#", "%23")):
raise exc
if is_file_uri(path):
path = local_file_uri_to_path(path)
if (
any((s in path) for s in _OS_ALT_SEPS)
or ".." in path.split("/")
or pathlib.PureWindowsPath(path).is_absolute()
or pathlib.PurePosixPath(path).is_absolute()
or (is_windows() and len(path) >= 2 and path[1] == ":")
):
raise exc | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_list_artifacts_malicious_path(http_artifact_repo, path):
with mock.patch(
"mlflow.store.artifact.http_artifact_repo.http_request",
return_value=MockResponse(
{
"files": [
{"path": path, "is_dir": False, "file_size": 1},
]
},
200,
),
):
with pytest.raises(MlflowException, match=f"Invalid path: {path}"):
http_artifact_repo.list_artifacts() | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_list_artifacts_malicious_path(http_artifact_repo, path):
with mock.patch(
"mlflow.store.artifact.http_artifact_repo.http_request",
return_value=MockResponse(
{
"files": [
{"path": path, "is_dir": False, "file_size": 1},
]
},
200,
),
):
with pytest.raises(MlflowException, match=f"Invalid path: {path}"):
http_artifact_repo.list_artifacts() | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_validate_path_is_safe_windows_good(path):
validate_path_is_safe(path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_validate_path_is_safe_windows_good(path):
validate_path_is_safe(path) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": f"Invalid path: {invalid_path}",
} | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": f"Invalid path: {invalid_path}",
} | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_path_validation(mlflow_client):
experiment_id = mlflow_client.create_experiment("tags validation")
created_run = mlflow_client.create_run(experiment_id)
run_id = created_run.info.run_id
invalid_path = "../path"
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": f"Invalid path: {invalid_path}",
}
response = requests.get(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/artifacts/list",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}/get-artifact",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}//model-versions/get-artifact",
params={"name": "model", "version": 1, "path": invalid_path},
)
assert_response(response) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_path_validation(mlflow_client):
experiment_id = mlflow_client.create_experiment("tags validation")
created_run = mlflow_client.create_run(experiment_id)
run_id = created_run.info.run_id
invalid_path = "../path"
def assert_response(resp):
assert resp.status_code == 400
assert response.json() == {
"error_code": "INVALID_PARAMETER_VALUE",
"message": f"Invalid path: {invalid_path}",
}
response = requests.get(
f"{mlflow_client.tracking_uri}/api/2.0/mlflow/artifacts/list",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}/get-artifact",
params={"run_id": run_id, "path": invalid_path},
)
assert_response(response)
response = requests.get(
f"{mlflow_client.tracking_uri}//model-versions/get-artifact",
params={"name": "model", "version": 1, "path": invalid_path},
)
assert_response(response) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_validate_path_is_safe_windows_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_validate_path_is_safe_windows_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_validate_path_is_safe_good(path):
validate_path_is_safe(path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_validate_path_is_safe_good(path):
validate_path_is_safe(path) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def test_validate_path_is_safe_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def test_validate_path_is_safe_bad(path):
with pytest.raises(MlflowException, match="Invalid path"):
validate_path_is_safe(path) | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def load(self, dst_path=None) -> str:
"""
Downloads the dataset source to the local filesystem.
:param dst_path: Path of the local filesystem destination directory to which to download the
dataset source. If the directory does not exist, it is created. If
unspecified, the dataset source is downloaded to a new uniquely-named
directory on the local filesystem.
:return: The path to the downloaded dataset source on the local filesystem.
"""
resp = cloud_storage_http_request(
method="GET",
url=self.url,
stream=True,
)
augmented_raise_for_status(resp)
path = urlparse(self.url).path
content_disposition = resp.headers.get("Content-Disposition")
if content_disposition is not None and (
file_name := next(re.finditer(r"filename=(.+)", content_disposition), None)
):
# NB: If the filename is quoted, unquote it
basename = file_name[1].strip("'\"")
if _is_path(basename):
raise MlflowException.invalid_parameter_value(
f"Invalid filename in Content-Disposition header: {basename}. "
"It must be a file name, not a path."
)
elif path is not None and len(posixpath.basename(path)) > 0:
basename = posixpath.basename(path)
else:
basename = "dataset_source"
if dst_path is None:
dst_path = create_tmp_dir()
dst_path = os.path.join(dst_path, basename)
with open(dst_path, "wb") as f:
chunk_size = 1024 * 1024 # 1 MB
for chunk in resp.iter_content(chunk_size=chunk_size):
f.write(chunk)
return dst_path | 0 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
def list_artifacts(self, path=None):
with self.get_ftp_client() as ftp:
artifact_dir = self.path
list_dir = posixpath.join(artifact_dir, path) if path else artifact_dir
if not self._is_dir(ftp, list_dir):
return []
artifact_files = ftp.nlst(list_dir)
artifact_files = list(filter(lambda x: x != "." and x != "..", artifact_files))
# Make sure artifact_files is a list of file names because ftp.nlst
# may return absolute paths.
artifact_files = [os.path.basename(f) for f in artifact_files]
infos = []
for file_name in artifact_files:
file_path = file_name if path is None else posixpath.join(path, file_name)
full_file_path = posixpath.join(list_dir, file_name)
if self._is_dir(ftp, full_file_path):
infos.append(FileInfo(file_path, True, None))
else:
size = self._size(ftp, full_file_path)
infos.append(FileInfo(file_path, False, size))
return infos | 0 | Python | CWE-29 | Path Traversal: '\..\filename' | The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. | https://cwe.mitre.org/data/definitions/29.html | vulnerable |
def _create_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/create` to create a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
request_message = _get_request_message(
CreateMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"num_parts": [_assert_intlike],
},
)
path = request_message.path
num_parts = request_message.num_parts
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
create_response = artifact_repo.create_multipart_upload(
path,
num_parts,
artifact_path,
)
response_message = create_response.to_proto()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def get_artifact_handler():
from querystring_parser import parser
query_string = request.query_string.decode("utf-8")
request_dict = parser.parse(query_string, normalized=True)
run_id = request_dict.get("run_id") or request_dict.get("run_uuid")
path = request_dict["path"]
validate_path_is_safe(path)
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_path = _get_proxied_run_artifact_destination_path(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_repo = _get_artifact_repo(run)
artifact_path = path
return _send_artifact(artifact_repo, artifact_path) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _delete_artifact_mlflow_artifacts(artifact_path):
"""
A request handler for `DELETE /mlflow-artifacts/artifacts?path=<value>` to delete artifacts in
`path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
_get_request_message(DeleteArtifact())
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_repo.delete_artifacts(artifact_path)
response_message = DeleteArtifact.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _list_artifacts():
request_message = _get_request_message(
ListArtifacts(),
schema={
"run_id": [_assert_string, _assert_required],
"path": [_assert_string],
"page_token": [_assert_string],
},
)
response_message = ListArtifacts.Response()
if request_message.HasField("path"):
path = request_message.path
validate_path_is_safe(path)
else:
path = None
run_id = request_message.run_id or request_message.run_uuid
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_entities = _list_artifacts_for_proxied_run_artifact_root(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_entities = _get_artifact_repo(run).list_artifacts(path)
response_message.files.extend([a.to_proto() for a in artifact_entities])
response_message.root_uri = run.info.artifact_uri
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _abort_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/abort` to abort a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
request_message = _get_request_message(
AbortMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"upload_id": [_assert_string],
},
)
path = request_message.path
upload_id = request_message.upload_id
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
artifact_repo.abort_multipart_upload(
path,
upload_id,
artifact_path,
)
return _wrap_response(AbortMultipartUpload.Response()) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def get_model_version_artifact_handler():
from querystring_parser import parser
query_string = request.query_string.decode("utf-8")
request_dict = parser.parse(query_string, normalized=True)
name = request_dict.get("name")
version = request_dict.get("version")
path = request_dict["path"]
validate_path_is_safe(path)
artifact_uri = _get_model_registry_store().get_model_version_download_uri(name, version)
if _is_servable_proxied_run_artifact_root(artifact_uri):
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_path = _get_proxied_run_artifact_destination_path(
proxied_artifact_root=artifact_uri,
relative_path=path,
)
else:
artifact_repo = get_artifact_repository(artifact_uri)
artifact_path = path
return _send_artifact(artifact_repo, artifact_path) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _download_artifact(artifact_path):
"""
A request handler for `GET /mlflow-artifacts/artifacts/<artifact_path>` to download an artifact
from `artifact_path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
tmp_dir = tempfile.TemporaryDirectory()
artifact_repo = _get_artifact_repo_mlflow_artifacts()
dst = artifact_repo.download_artifacts(artifact_path, tmp_dir.name)
# Ref: https://stackoverflow.com/a/24613980/6943581
file_handle = open(dst, "rb") # noqa: SIM115
def stream_and_remove_file():
yield from file_handle
file_handle.close()
tmp_dir.cleanup()
file_sender_response = current_app.response_class(stream_and_remove_file())
return _response_with_file_attachment_headers(artifact_path, file_sender_response) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _complete_multipart_upload_artifact(artifact_path):
"""
A request handler for `POST /mlflow-artifacts/mpu/complete` to complete a multipart upload
to `artifact_path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
request_message = _get_request_message(
CompleteMultipartUpload(),
schema={
"path": [_assert_required, _assert_string],
"upload_id": [_assert_string],
"parts": [_assert_required],
},
)
path = request_message.path
upload_id = request_message.upload_id
parts = [MultipartUploadPart.from_proto(part) for part in request_message.parts]
artifact_repo = _get_artifact_repo_mlflow_artifacts()
_validate_support_multipart_upload(artifact_repo)
artifact_repo.complete_multipart_upload(
path,
upload_id,
parts,
artifact_path,
)
return _wrap_response(CompleteMultipartUpload.Response()) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _list_artifacts_mlflow_artifacts():
"""
A request handler for `GET /mlflow-artifacts/artifacts?path=<value>` to list artifacts in `path`
(a relative path from the root artifact directory).
"""
request_message = _get_request_message(ListArtifactsMlflowArtifacts())
if request_message.HasField("path"):
validate_path_is_safe(request_message.path)
path = request_message.path
else:
path = None
artifact_repo = _get_artifact_repo_mlflow_artifacts()
files = []
for file_info in artifact_repo.list_artifacts(path):
basename = posixpath.basename(file_info.path)
new_file_info = FileInfo(basename, file_info.is_dir, file_info.file_size)
files.append(new_file_info.to_proto())
response_message = ListArtifacts.Response()
response_message.files.extend(files)
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _upload_artifact(artifact_path):
"""
A request handler for `PUT /mlflow-artifacts/artifacts/<artifact_path>` to upload an artifact
to `artifact_path` (a relative path from the root artifact directory).
"""
validate_path_is_safe(artifact_path)
head, tail = posixpath.split(artifact_path)
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, tail)
with open(tmp_path, "wb") as f:
chunk_size = 1024 * 1024 # 1 MB
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
break
f.write(chunk)
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_repo.log_artifact(tmp_path, artifact_path=head or None)
return _wrap_response(UploadArtifact.Response()) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def list_artifacts(self, path=None):
endpoint = "/mlflow-artifacts/artifacts"
url, tail = self.artifact_uri.split(endpoint, maxsplit=1)
root = tail.lstrip("/")
params = {"path": posixpath.join(root, path) if path else root}
host_creds = _get_default_host_creds(url)
resp = http_request(host_creds, endpoint, "GET", params=params)
augmented_raise_for_status(resp)
file_infos = []
for f in resp.json().get("files", []):
validate_path_is_safe(f["path"])
file_info = FileInfo(
posixpath.join(path, f["path"]) if path else f["path"],
f["is_dir"],
int(f["file_size"]) if ("file_size" in f) else None,
)
file_infos.append(file_info)
return sorted(file_infos, key=lambda f: f.path) | 0 | Python | CWE-434 | Unrestricted Upload of File with Dangerous Type | The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
def _get_http_response_with_retries(
method,
url,
max_retries,
backoff_factor,
backoff_jitter,
retry_codes,
raise_on_status=True,
**kwargs,
):
"""
Performs an HTTP request using Python's `requests` module with an automatic retry policy.
:param method: a string indicating the method to use, e.g. "GET", "POST", "PUT".
:param url: the target URL address for the HTTP request.
:param max_retries: Maximum total number of retries.
:param backoff_factor: a time factor for exponential backoff. e.g. value 5 means the HTTP
request will be retried with interval 5, 10, 20... seconds. A value of 0 turns off the
exponential backoff.
:param backoff_jitter: A random jitter to add to the backoff interval.
:param retry_codes: a list of HTTP response error codes that qualifies for retry.
:param raise_on_status: whether to raise an exception, or return a response, if status falls
in retry_codes range and retries have been exhausted.
:param kwargs: Additional keyword arguments to pass to `requests.Session.request()`
:return: requests.Response object.
"""
session = _get_request_session(
max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status
)
return session.request(method, url, **kwargs) | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def test_log_artifact_gcp_with_headers(
databricks_artifact_repo, test_file, artifact_path, expected_location
):
expected_headers = {header.name: header.value for header in MOCK_HEADERS}
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_GCP_SIGNED_URL,
type=ArtifactCredentialType.GCP_SIGNED_URL,
headers=MOCK_HEADERS,
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_GCP_SIGNED_URL, data=ANY, headers=expected_headers, timeout=None
) | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def test_log_artifact_aws_with_headers(
databricks_artifact_repo, test_file, artifact_path, expected_location
):
expected_headers = {header.name: header.value for header in MOCK_HEADERS}
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_AWS_SIGNED_URI,
type=ArtifactCredentialType.AWS_PRESIGNED_URL,
headers=MOCK_HEADERS,
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_AWS_SIGNED_URI, data=ANY, headers=expected_headers, timeout=None
) | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def test_log_artifact_aws(databricks_artifact_repo, test_file, artifact_path, expected_location):
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_AWS_SIGNED_URI, type=ArtifactCredentialType.AWS_PRESIGNED_URL
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_AWS_SIGNED_URI, data=ANY, headers={}, timeout=None
) | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def test_log_artifact_gcp(databricks_artifact_repo, test_file, artifact_path, expected_location):
mock_response = Response()
mock_response.status_code = 200
mock_response.close = lambda: None
mock_credential_info = ArtifactCredentialInfo(
signed_uri=MOCK_GCP_SIGNED_URL, type=ArtifactCredentialType.GCP_SIGNED_URL
)
with mock.patch(
f"{DATABRICKS_ARTIFACT_REPOSITORY}._get_credential_infos",
return_value=[mock_credential_info],
) as get_credential_infos_mock, mock.patch(
"requests.Session.request", return_value=mock_response
) as request_mock:
databricks_artifact_repo.log_artifact(test_file, artifact_path)
get_credential_infos_mock.assert_called_with(
GetCredentialsForWrite, MOCK_RUN_ID, [expected_location]
)
request_mock.assert_called_with(
"put", MOCK_GCP_SIGNED_URL, data=ANY, headers={}, timeout=None
) | 0 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
def run_as_real_user(args: list[str]) -> None:
"""Call subprocess.run as real user if called via sudo/pkexec.
If we are called through pkexec/sudo, determine the real user ID and
run the command with it to get the user's web browser settings.
"""
uid = _get_env_int("SUDO_UID", _get_env_int("PKEXEC_UID"))
if uid is None or not get_process_user_and_group().is_root():
subprocess.run(args, check=False)
return
pwuid = pwd.getpwuid(uid)
gid = _get_env_int("SUDO_GID")
if gid is None:
gid = pwuid.pw_gid
env = {
k: v
for k, v in os.environ.items()
if not k.startswith("SUDO_") and k != "PKEXEC_UID"
} | _get_users_environ(uid)
env["HOME"] = pwuid.pw_dir
subprocess.run(
args,
check=False,
env=env,
user=uid,
group=gid,
extra_groups=os.getgrouplist(pwuid.pw_name, gid),
) | 0 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | vulnerable |
def open_url(self, url):
"""Open the given URL in a new browser window.
Display an error dialog if everything fails.
"""
(r, w) = os.pipe()
if os.fork() > 0:
os.close(w)
status = os.wait()[1]
if status:
title = _("Unable to start web browser")
error = _("Unable to start web browser to open %s." % url)
message = os.fdopen(r).readline()
if message:
error += "\n" + message
self.ui_error_message(title, error)
try:
os.close(r)
except OSError:
pass
return
os.setsid()
os.close(r)
try:
try:
run_as_real_user(["xdg-open", url])
except OSError:
# fall back to webbrowser
webbrowser.open(url, new=True, autoraise=True)
sys.exit(0)
except Exception as error: # pylint: disable=broad-except
os.write(w, str(error))
sys.exit(1)
os._exit(0) # pylint: disable=protected-access | 0 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | vulnerable |
def test_run_as_real_user_no_gvfsd(
self, getpwuid_mock: unittest.mock.MagicMock
) -> None:
"""Test run_as_real_user() without no gvfsd process."""
getpwuid_mock.return_value = pwd.struct_passwd(
(
"testuser",
"x",
1337,
42,
"Test user,,,",
"/home/testuser",
"/bin/bash",
)
)
with unittest.mock.patch(
"subprocess.run", side_effect=mock_run_calls_except_pgrep
) as run_mock:
run_as_real_user(["/bin/true"])
run_mock.assert_called_with(
["/bin/true"],
check=False,
env={"HOME": "/home/testuser"},
user=1337,
group=42,
extra_groups=[42],
)
self.assertEqual(run_mock.call_count, 2) | 0 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | vulnerable |
def test_run_as_real_user(self) -> None:
"""Test run_as_real_user() with SUDO_UID set."""
pwuid = pwd.getpwuid(int(os.environ["SUDO_UID"]))
with tempfile.TemporaryDirectory() as tmpdir:
# rename test program to fake gvfsd
gvfsd_mock = os.path.join(tmpdir, "gvfsd")
shutil.copy(self.TEST_EXECUTABLE, gvfsd_mock)
gvfsd_env = {
"XDG_DATA_DIRS": "mocked XDG data dir",
"DBUS_SESSION_BUS_ADDRESS": "/fake/dbus/path",
}
with self._run_test_executable(gvfsd_mock, env=gvfsd_env):
with unittest.mock.patch(
"subprocess.run", side_effect=mock_run_calls_except_pgrep
) as run_mock:
run_as_real_user(["/bin/true"])
run_mock.assert_called_with(
["/bin/true"],
check=False,
env={
"DBUS_SESSION_BUS_ADDRESS": "/fake/dbus/path",
"XDG_DATA_DIRS": "mocked XDG data dir",
"HOME": pwuid.pw_dir,
},
user=int(os.environ["SUDO_UID"]),
group=pwuid.pw_gid,
extra_groups=os.getgrouplist(pwuid.pw_name, pwuid.pw_gid),
)
self.assertEqual(run_mock.call_count, 2) | 0 | Python | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | vulnerable |
def _get_data(self):
LOG.debug("Machine is a Vultr instance")
# Fetch metadata
self.metadata = self.get_metadata()
self.userdata_raw = self.metadata["user-data"]
# Generate config and process data
self.get_datasource_data(self.metadata)
# Dump some data so diagnosing failures is manageable
LOG.debug("Vultr Vendor Config:")
LOG.debug(util.json_dumps(self.metadata["vendor-data"]))
LOG.debug("SUBID: %s", self.metadata["instance-id"])
LOG.debug("Hostname: %s", self.metadata["local-hostname"])
if self.userdata_raw is not None:
LOG.debug("User-Data:")
LOG.debug(self.userdata_raw)
return True | 0 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | vulnerable |
def redact_sensitive_keys(metadata, redact_value=REDACT_SENSITIVE_VALUE):
"""Redact any sensitive keys from to provided metadata dictionary.
Replace any keys values listed in 'sensitive_keys' with redact_value.
"""
if not metadata.get("sensitive_keys", []):
return metadata
md_copy = copy.deepcopy(metadata)
for key_path in metadata.get("sensitive_keys"):
path_parts = key_path.split("/")
obj = md_copy
for path in path_parts:
if isinstance(obj[path], dict) and path != path_parts[-1]:
obj = obj[path]
obj[path] = redact_value
return md_copy | 0 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | vulnerable |
def process_instance_metadata(metadata, key_path="", sensitive_keys=()):
"""Process all instance metadata cleaning it up for persisting as json.
Strip ci-b64 prefix and catalog any 'base64_encoded_keys' as a list
@return Dict copy of processed metadata.
"""
md_copy = copy.deepcopy(metadata)
base64_encoded_keys = []
sens_keys = []
for key, val in metadata.items():
if key_path:
sub_key_path = key_path + "/" + key
else:
sub_key_path = key
if key in sensitive_keys or sub_key_path in sensitive_keys:
sens_keys.append(sub_key_path)
if isinstance(val, str) and val.startswith("ci-b64:"):
base64_encoded_keys.append(sub_key_path)
md_copy[key] = val.replace("ci-b64:", "")
if isinstance(val, dict):
return_val = process_instance_metadata(
val, sub_key_path, sensitive_keys
)
base64_encoded_keys.extend(return_val.pop("base64_encoded_keys"))
sens_keys.extend(return_val.pop("sensitive_keys"))
md_copy[key] = return_val
md_copy["base64_encoded_keys"] = sorted(base64_encoded_keys)
md_copy["sensitive_keys"] = sorted(sens_keys)
return md_copy | 0 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | vulnerable |
def _initialize_filesystem(self):
util.ensure_dirs(self._initial_subdirs())
log_file = util.get_cfg_option_str(self.cfg, "def_log_file")
if log_file:
util.ensure_file(log_file, mode=0o640, preserve_mode=True)
perms = self.cfg.get("syslog_fix_perms")
if not perms:
perms = {}
if not isinstance(perms, list):
perms = [perms]
error = None
for perm in perms:
u, g = util.extract_usergroup(perm)
try:
util.chownbyname(log_file, u, g)
return
except OSError as e:
error = e
LOG.warning(
"Failed changing perms on '%s'. tried: %s. %s",
log_file,
",".join(perms),
error,
) | 0 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | vulnerable |
def test_existing_file_permissions_are_not_modified(self, init, tmpdir):
"""If the log file already exists, we should not modify its permissions
See https://bugs.launchpad.net/cloud-init/+bug/1900837.
"""
# Use a mode that will never be made the default so this test will
# always be valid
mode = 0o606
log_file = tmpdir.join("cloud-init.log")
log_file.ensure()
log_file.chmod(mode)
init._cfg = {"def_log_file": str(log_file)}
init._initialize_filesystem()
assert mode == stat.S_IMODE(log_file.stat().mode) | 0 | Python | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | vulnerable |
def test_regular_user_cant_add_users(self):
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code)
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-regular-user",
"password1": "xo-xo-xo",
"password2": "xo-xo-xo",
},
follow=True,
)
self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code)
self.assertFalse(
get_user_model().objects.filter(username="added-by-regular-user").exists()
) | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def test_moderator_can_add_users(self):
user_should_have_perm(self.moderator, "auth.add_user")
user_should_have_perm(self.moderator, "auth.change_user")
# test for https://github.com/kiwitcms/Kiwi/issues/642
self.client.login( # nosec:B106:hardcoded_password_funcarg
username=self.moderator.username, password="admin-password"
)
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.OK, response.status_code)
# only these fields can be edited
self.assertContains(response, "id_username")
self.assertContains(response, "id_password1")
self.assertContains(response, "id_password2")
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-moderator",
"password1": "xo-xo-xo",
"password2": "xo-xo-xo",
},
follow=True,
)
self.assertEqual(HTTPStatus.OK, response.status_code)
self.assertTrue(
get_user_model().objects.filter(username="added-by-moderator").exists()
) | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def test_superuser_can_add_users(self):
# test for https://github.com/kiwitcms/Kiwi/issues/642
self.client.login( # nosec:B106:hardcoded_password_funcarg
username=self.admin.username, password="admin-password"
)
response = self.client.get("/admin/auth/user/add/")
self.assertEqual(HTTPStatus.OK, response.status_code)
response = self.client.post(
"/admin/auth/user/add/",
{
"username": "added-by-admin",
"password1": "xo-xo-xo",
"password2": "xo-xo-xo",
},
follow=True,
)
self.assertEqual(HTTPStatus.OK, response.status_code)
self.assertTrue(
get_user_model().objects.filter(username="added-by-admin").exists()
) | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def setUp(self):
self.data = {
"username": "test_user",
"password1": "password",
"password2": "password",
"email": "[email protected]",
} | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def test_invalid_form(self):
response = self.client.post(
self.register_url,
{
"username": "kiwi-tester",
"password1": "password-1",
"password2": "password-2",
"email": "[email protected]",
},
follow=False,
)
self.assertContains(response, _("The two password fields didn’t match."))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "registration/registration_form.html") | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def assert_user_registration(self, username, follow=False):
with patch("tcms.kiwi_auth.models.secrets") as _secrets:
_secrets.token_hex.return_value = self.fake_activate_key
try:
# https://github.com/mbi/django-simple-captcha/issues/84
# pylint: disable=import-outside-toplevel
from captcha.conf import settings as captcha_settings
captcha_settings.CAPTCHA_TEST_MODE = True
response = self.client.post(
self.register_url,
{
"username": username,
"password1": "password",
"password2": "password",
"email": "[email protected]",
"captcha_0": "PASSED",
"captcha_1": "PASSED",
},
follow=follow,
)
finally:
captcha_settings.CAPTCHA_TEST_MODE = False
user = User.objects.get(username=username)
self.assertEqual("[email protected]", user.email)
if User.objects.filter(is_superuser=True).count() == 1 and user.is_superuser:
self.assertTrue(user.is_active)
else:
self.assertFalse(user.is_active)
key = UserActivationKey.objects.get(user=user)
self.assertEqual(self.fake_activate_key, key.activation_key)
return response, user | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def test_register_user_already_registered(self):
User.objects.create_user("kiwi-tester", "[email protected]", "password")
response = self.client.post(
self.register_url,
{
"username": "test_user",
"password1": "password",
"password2": "password",
"email": "[email protected]",
},
follow=False,
)
self.assertContains(response, _("A user with that email already exists."))
user = User.objects.filter(username="test_user")
self.assertEqual(user.count(), 0) | 0 | Python | CWE-521 | Weak Password Requirements | The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. | https://cwe.mitre.org/data/definitions/521.html | vulnerable |
def test_send_mail_for_password_reset(self, mail_sent):
user = User.objects.create_user("kiwi-tester", "[email protected]", "password")
user.is_active = True
user.save()
data = {"email": "[email protected]"}
response = self.client.post(self.password_reset_url, data, follow=True)
self.assertContains(response, _("Password reset email was sent"))
# Verify mail is sent
mail_sent.assert_called_once() | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
def render_GET(self, request):
template = env.get_template('generate_new.html')
sites_len = len(get_all_canary_sites())
now = datetime.datetime.now()
return template.render(settings=settings, sites_len=sites_len, now=now).encode('utf8') | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def get_signed_upload_url(path: str, 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 download:
params["ResponseContentDisposition"] = "attachment"
return client.generate_presigned_url(
ClientMethod="get_object",
Params=params,
ExpiresIn=SIGNED_UPLOAD_URL_DURATION,
HttpMethod="GET",
) | 0 | 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 | vulnerable |
def check_xsend_links(
name: str,
name_str_for_test: str,
content_disposition: str = "",
download: bool = False,
) -> None:
self.login("hamlet")
fp = StringIO("zulip!")
fp.name = name
result = self.client_post("/json/user_uploads", {"file": fp})
uri = self.assert_json_success(result)["uri"]
fp_path_id = re.sub("/user_uploads/", "", uri)
fp_path = os.path.split(fp_path_id)[0]
if download:
uri = uri.replace("/user_uploads/", "/user_uploads/download/")
with self.settings(DEVELOPMENT=False):
response = self.client_get(uri)
assert settings.LOCAL_UPLOADS_DIR is not None
test_run, worker = os.path.split(os.path.dirname(settings.LOCAL_UPLOADS_DIR))
self.assertEqual(
response["X-Accel-Redirect"],
"/internal/uploads/" + fp_path + "/" + name_str_for_test,
)
if content_disposition != "":
self.assertIn("attachment;", response["Content-disposition"])
self.assertIn(content_disposition, response["Content-disposition"])
else:
self.assertIn("inline;", response["Content-disposition"])
self.assertEqual(set(response["Cache-Control"].split(", ")), {"private", "immutable"}) | 0 | 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 | vulnerable |
def test_avatar_url_local(self) -> None:
self.login("hamlet")
with get_test_image_file("img.png") as image_file:
result = self.client_post("/json/users/me/avatar", {"file": image_file})
response_dict = self.assert_json_success(result)
self.assertIn("avatar_url", response_dict)
base = "/user_avatars/"
url = self.assert_json_success(result)["avatar_url"]
self.assertEqual(base, url[: len(base)])
# That URL is accessible when logged out
self.logout()
result = self.client_get(url)
self.assertEqual(result.status_code, 200)
# We get a resized avatar from it
image_data = read_test_image_file("img.png")
resized_avatar = resize_avatar(image_data)
assert isinstance(result, StreamingHttpResponse)
self.assertEqual(resized_avatar, b"".join(result.streaming_content))
with self.settings(DEVELOPMENT=False):
# In production, this is an X-Accel-Redirect to the
# on-disk content, which nginx serves
result = self.client_get(url)
self.assertEqual(result.status_code, 200)
internal_redirect_path = urlparse(url).path.replace(
"/user_avatars/", "/internal/user_avatars/"
)
self.assertEqual(result["X-Accel-Redirect"], internal_redirect_path)
self.assertEqual(b"", result.content) | 0 | 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 | vulnerable |
def serve_local(
request: HttpRequest, path_id: str, url_only: bool, 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 url_only:
url = generate_unauthed_file_access_url(path_id)
return json_success(request, data=dict(url=url))
mimetype, encoding = guess_type(local_path)
attachment = 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=attachment)
patch_cache_control(response, private=True, immutable=True)
return response
response = internal_nginx_redirect(quote(f"/internal/uploads/{path_id}"))
patch_disposition_header(response, local_path, attachment)
patch_cache_control(response, private=True, immutable=True)
return response | 0 | 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 | vulnerable |
def get_local_file_path_id_from_token(token: str) -> Optional[str]:
signer = TimestampSigner(salt=LOCAL_FILE_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 | 0 | 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 | vulnerable |
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/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 | 0 | 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 | vulnerable |
def serve_s3(
request: HttpRequest, url_path: str, url_only: bool, download: bool = False
) -> HttpResponse:
url = get_signed_upload_url(url_path, download=download)
if url_only:
return json_success(request, data=dict(url=url))
return redirect(url) | 0 | 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 | vulnerable |
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 settings.LOCAL_UPLOADS_DIR is not None:
return serve_local(request, path_id, url_only, download=download)
return serve_s3(request, path_id, url_only, download=download) | 0 | 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 | vulnerable |
def generate_unauthed_file_access_url(path_id: str) -> str:
signed_data = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT).sign(path_id)
token = base64.b16encode(signed_data.encode()).decode()
filename = path_id.split("/")[-1]
return reverse("local_file_unauthed", args=[token, filename]) | 0 | 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 | vulnerable |
def serve_local_file_unauthed(request: HttpRequest, token: str, filename: str) -> HttpResponseBase:
path_id = get_local_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"))
return serve_local(request, path_id, url_only=False) | 0 | 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 | vulnerable |
def get_signed_upload_url(path: str) -> 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,
)
return client.generate_presigned_url(
ClientMethod="get_object",
Params={
"Bucket": settings.S3_AUTH_UPLOADS_BUCKET,
"Key": path,
},
ExpiresIn=SIGNED_UPLOAD_URL_DURATION,
HttpMethod="GET",
) | 0 | 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 | vulnerable |
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) | 0 | 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 | vulnerable |
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 # 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 | 0 | 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 | vulnerable |
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) | 0 | 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 | vulnerable |
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, download=True) | 0 | 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 | vulnerable |
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)
# 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)
patch_disposition_header(response, path_id, download)
patch_cache_control(response, private=True, immutable=True)
return response | 0 | 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 | vulnerable |
def get_permissions(self):
if self.action == "create":
self.permission_classes = [
IsRegistrationAllowed | FirstTimeSetupPermission | IsAdminUser
]
elif self.action == "list":
self.permission_classes = (AllowAny,)
elif self.request.method == "GET" or self.request.method == "POST":
self.permission_classes = (AllowAny,)
else:
self.permission_classes = (IsUserOrReadOnly,)
return super(UserViewSet, self).get_permissions() | 0 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
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()
)
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) | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
async def extract_multipart(
connection: "Request[Any, Any]",
) -> Any:
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()
)
)
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 | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
def 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.
"""
async def extract_multipart(
connection: "Request[Any, Any]",
) -> Any:
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()
)
)
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) | 0 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
def 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:
model = relation_info.related_model
is_nested = True
depth = nested_depth - 1
if hasattr(base_serializer_class.Meta, "fields"):
fields = base_serializer_class.Meta.fields
if hasattr(base_serializer_class.Meta, "exclude"):
exclude = base_serializer_class.Meta.exclude
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 | 0 | 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 | vulnerable |
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 mark_safe(f'<span class="label label-{css_class}">{label}</span>')
return self.default | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def render(self, value):
return mark_safe(f'<span class="label color-block" style="background-color: #{value}"> </span>') | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def render(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 mark_safe(f'<a href="{url}">{value}</a>')
return value | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def header(self):
return mark_safe('<input type="checkbox" class="toggle" title="Toggle all" />') | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def 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)) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def render_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 mark_safe(HTML_NONE)
if bool(value):
return mark_safe(HTML_TRUE)
return mark_safe(HTML_FALSE) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def render_markdown(value):
"""
Render text as Markdown
Example:
{{ text | render_markdown }}
"""
# Strip HTML tags
value = strip_tags(value)
# Sanitize Markdown links
schemes = "|".join(settings.ALLOWED_URL_SCHEMES)
pattern = rf"\[(.+)\]\((?!({schemes})).*:(.+)\)"
value = re.sub(pattern, "[\\1](\\3)", value, flags=re.IGNORECASE)
# Render Markdown
html = markdown(value, extensions=["fenced_code", "tables"])
return mark_safe(html) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def 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 mark_safe(HTML_NONE) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def render_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)
return template.render(context=context) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def 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 = f'{msg} <a href="{obj.get_absolute_url()}">{escape(obj)}</a>'
else:
msg = f"{msg} {escape(obj)}"
messages.success(request, mark_safe(msg)) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def 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,
mark_safe(f"Invalid filters were specified: {self.filterset.errors}"),
)
queryset = queryset.none()
return queryset | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
def _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 = f'{msg} <a href="{obj.get_absolute_url()}">{escape(obj)}</a>'
else:
msg = f"{msg} { escape(obj)}"
messages.success(request, mark_safe(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) | 0 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.