-
Notifications
You must be signed in to change notification settings - Fork 1.3k
fix: validate region parameter before URL interpolation to prevent SSRF #5819
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lucasjia-aws
wants to merge
3
commits into
aws:master
Choose a base branch
from
lucasjia-aws:fix/validate-region-ssrf-prevention
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -483,6 +483,9 @@ def _retrieve_latest_pytorch_training_uri(region: str): | |
| version_config = config[image_scope]["versions"][latest_version] | ||
| py_version = _validate_py_version_and_set_if_needed(None, version_config, None) | ||
|
|
||
| from sagemaker.core.region_validation import validate_region | ||
|
|
||
| validate_region(region) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we add validate region to _botocore_resolver() instead? |
||
| endpoint_data = _botocore_resolver().construct_endpoint("ecr", region) | ||
| if region == "il-central-1" and not endpoint_data: | ||
| endpoint_data = {"hostname": "ecr.{}.amazonaws.com".format(region)} | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"). You | ||
| # may not use this file except in compliance with the License. A copy of | ||
| # the License is located at | ||
| # | ||
| # http://aws.amazon.com/apache2.0/ | ||
| # | ||
| # or in the "license" file accompanying this file. This file is | ||
| # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | ||
| # ANY KIND, either express or implied. See the License for the specific | ||
| # language governing permissions and limitations under the License. | ||
| """Region validation utilities to prevent SSRF via malicious region strings. | ||
|
|
||
| This module provides validation for AWS region parameters before they are | ||
| interpolated into endpoint URLs. Without validation, a crafted region value | ||
| (e.g., ``x@attacker.com:443/#``) could redirect SDK API calls — including | ||
| SigV4-signed requests — to non-AWS hosts. | ||
|
|
||
| See: CVE-2026-22611 (AWS SDK for .NET, same vulnerability class). | ||
| """ | ||
| from __future__ import absolute_import | ||
|
|
||
| import re | ||
| from urllib.parse import urlparse | ||
|
|
||
| # Regex for valid AWS region names (e.g., us-east-1, eu-west-2, cn-north-1, us-gov-west-1). | ||
| # Uses \A and \Z anchors to prevent newline injection bypass that $ allows. | ||
| _VALID_REGION_PATTERN = re.compile(r"\A[a-z]{2}(-[a-z]+)+-\d+\Z") | ||
|
|
||
| # Trusted AWS domain suffixes for endpoint URL validation (defense-in-depth). | ||
| _AWS_DOMAINS = ( | ||
| ".amazonaws.com", | ||
| ".amazonaws.com.cn", | ||
| ".api.aws", | ||
| ".sagemaker.aws", | ||
| ) | ||
|
|
||
|
|
||
| class InvalidRegionError(ValueError): | ||
| """Raised when an invalid AWS region string is provided. | ||
|
|
||
| This prevents SSRF attacks where a crafted region value | ||
| (e.g., ``x@attacker.com:443/#``) could redirect SDK API calls | ||
| to non-AWS hosts. | ||
| """ | ||
|
|
||
|
|
||
| def validate_region(region: str) -> str: | ||
| """Validate that a region string is a well-formed AWS region name. | ||
|
|
||
| Args: | ||
| region: The region string to validate. | ||
|
|
||
| Returns: | ||
| The validated region string (unchanged). | ||
|
|
||
| Raises: | ||
| InvalidRegionError: If the region does not match the expected pattern. | ||
| """ | ||
| if not isinstance(region, str) or not _VALID_REGION_PATTERN.match(region): | ||
| raise InvalidRegionError( | ||
| f"Invalid AWS region: {region!r}. " | ||
| "Region must match pattern like 'us-east-1', 'eu-west-2', 'cn-north-1'." | ||
| ) | ||
| return region | ||
|
|
||
|
|
||
| def validate_endpoint_url(url: str) -> str: | ||
| """Validate that a constructed endpoint URL resolves to an AWS host. | ||
|
|
||
| This is a defense-in-depth check that catches URL manipulation even if | ||
| the region regex is somehow bypassed. | ||
|
|
||
| Args: | ||
| url: The constructed endpoint URL. | ||
|
|
||
| Returns: | ||
| The validated URL (unchanged). | ||
|
|
||
| Raises: | ||
| InvalidRegionError: If the URL hostname does not end with a trusted AWS domain. | ||
| """ | ||
| parsed = urlparse(url) | ||
| hostname = parsed.hostname or "" | ||
| if not any(hostname.endswith(d) for d in _AWS_DOMAINS): | ||
| raise InvalidRegionError( | ||
| f"Constructed endpoint resolves to non-AWS host: {hostname!r}" | ||
| ) | ||
| return url |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is validate region scattered all over the place? Ideally it should only be checked before a request is sent ? Somewhere through the sagemaker client or in sagemaker core?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's no single chokepoint where all region-to-URL paths converge. Many of these URLs never go through a SageMaker client at all — telemetry uses raw requests.get(), Studio/Console URLs are returned to users as browser links, ECR image URIs are just strings passed to Docker/SageMaker APIs, and STS endpoints are passed as endpoint_url to boto3 (which doesn't validate it points to AWS). Validating once in Session.init() would only cover paths that obtain region from the session, but not paths where region is extracted from untrusted ARN strings (e.g., _parse_job_arn()) or passed directly as a function parameter (e.g., image_uris.retrieve(region=...)). The validation is placed at URL construction sites because that's where the region value actually becomes dangerous, and it's the only approach that covers all paths. This is consistent with how CVE-2026-22611 was fixed in other AWS SDKs — validate at endpoint construction, not at a single entry point.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add region validation to the Pydantic middleware or create a new middleware for sanitizing user inputs.
A middleware could ensure the region validation happens every time without us having to add it explicitly for every call?
Or a new datatype AwsRegion that can be instantiated like a string but throws an exception if the regex fails? So all uses of region: Optional[str] would be replaced with region: Optional[AwsRegion]
Devs might skip/forget adding region check in the future as this is an ever changing codebase.