-
Notifications
You must be signed in to change notification settings - Fork 0
Sandboxed URL creation to prevent SSRF attacks #6
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
Sandboxed URL creation to prevent SSRF attacks #6
Conversation
<artifactId>mockito-core</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
<dependency> |
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.
This library holds security tools for protecting Java API calls.
License: MIT ✅ | Open source ✅ | More facts
<artifactId>system-lambda</artifactId> | ||
<version>${system-lambda.version}</version> | ||
<scope>test</scope> | ||
</dependency> |
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.
This library holds security tools for protecting Java API calls.
License: MIT ✅ | Open source ✅ | More facts
You’ve installed Korbit to your Github repository but you haven’t created a Korbit account yet! To create your Korbit account and get your PR scans, please visit here |
Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information |
The files' contents are under analysis for test generation. |
Micro-Learning Topic: Server-side request forgery (Detected by phrase)Matched on "Server-Side Request Forgery"Server-Side Request Forgery (SSRF) vulnerabilities are caused when an attacker can supply or modify a URL that reads or sends data to the server. The attacker can create a malicious request with a manipulated URL, when this request reaches the server, the server-side code executes the exploit URL causing the attacker to be able to read data from services that shouldn't be exposed. Try a challenge in Secure Code Warrior |
Processing PR updates... |
Review changes with SemanticDiff. Analyzed 1 of 3 files. Overall, the semantic diff is 12% smaller than the GitHub diff.
|
Thanks @pixeebot[bot] for opening this PR! For COLLABORATOR only :
|
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.
@pixeebot[bot]
Thank you for your contribution to this repository! We appreciate your effort in opening pull request.
Happy coding!
Important Review skippedBot user detected. To trigger a single review, invoke the You can disable this status message by setting the Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File (
|
Server-Side Request Forgery
DescriptionServer-Side Request Forgery (SSRF) attacks are a type of security vulnerability wherein a malicious actor can manipulate a parameter on the web application to create or control requests from a vulnerable server. These attacks are often used by attackers to target internal systems that are inaccessible from the external network due to the use of a firewall. The most common case is a server application that, to implement a feature, performs HTTPS requests to a third-party server. This request may be needed to: consume an Internet API, download a package or retrieve user information via a social account (e.g., Facebook, Gravatar). An attacker might abuse the feature to perform requests to another third party or profit from the server's privileges regarding the original third-party system (e.g., to exfiltrate data). In essence, SSRF attacks exploit one of the foundations of robust security, trust, by exploiting existing trust relationships to escalate attacks from applications against other back-end systems or even the server itself. Read moreImpactA successful SSRF attack can enable a malicious attacker to escalate and laterally move their way behind the firewall in the back-end web server without restriction, leading to the potential full compromise of confidentiality, integrity, and availability of the application. The fallout from attacks that have successfully executed SSRF as part of their toolkit will be as extreme as the amount of data at risk. In the case of the infamous 2019 Capital One hack, the numbers speak for themselves: the compromised data included names, addresses, phone numbers, self-reported income, credit scores, and payment histories, among other personal information belonging to approximately 100 million customers in the United States (that is roughly 1/3 of the population) and 6 million customers in Canada. As with so many issues in security, human error undoubtedly played a part in the above example, as the genesis of the breach entry was a misconfigured firewall. ScenariosUsually, client web requests are performed through language functions that support defined classes of protocols, such as HTTP, and make their use very simple for the developer. According to the way the vulnerable request is implemented on the server side, the attacker might be able to reach another website. An attacker can even change the protocol and, for example, use the SSRF attacks remain quite powerful due to firewalls and network security; an attacker able to forge an arbitrary request through the server will benefit from the server's physical/logical position and the active firewall rules. A network resource that is invisible and forbidden to the attacker might be available when the request is executed from the server. A common example is a management server hidden to the outside world but allowed from the server, as it might manage its updates or monitor its usage. Lastly, attackers can monitor the average elapsed time for SSRF directed to open TCP ports and compare it to requests directed to closed or filtered TCP ports. By submitting a fairly small amount of requests, an attacker can map the network and discover open and closed ports that could be the target of further attacks. PreventionIf a list of permitted URLs is known, developers should implement a hostname or IP address allow list for the application. The URLs should never be validated against a deny list; this approach is prone to get easily circumvented using a number of well-known techniques. Developers should disable unused URL schemas if HTTP and HTTPS are the only active protocols the application utilizes to make requests. To reduce the risk of an attacker taking advantage of response data leakage, the developer must ensure that, when sending a request to another server, the raw response is never returned as-is to the client application. When SSRF happens, the main defense-in-depth approach is to lower the trust in the server. This can usually be implemented through firewall rules at the inbound end (e.g., the other server receiving the request), but it's much harder to implement firewall rules at the outbound end due to the nature of TCP. TestingVerify that the application protects against SSRF attacks by validating or sanitizing untrusted data or HTTP file metadata, such as filenames and URL input fields, and that it uses allow lists for protocols, domains, paths, and ports.
|
Hi there! 👋 Thanks for opening a PR. It looks like you've already reached the 5 review limit on our Basic Plan for the week. If you still want a review, feel free to upgrade your subscription in the Web App and then reopen the PR |
👋 Hi there!Everything looks good!
|
Potential issues, bugs, and flaws that can introduce unwanted behavior:
Code suggestions and improvements for better exception handling, logic, standardization, and consistency:
|
PR Details of @pixeebot[bot] in java-design-patterns :
|
public static String downloadFile(String urlString) throws IOException { | ||
LOGGER.info("Downloading contents from url: {}", urlString); | ||
var url = new URL(urlString); | ||
var url = Urls.create(urlString, Urls.HTTP_PROTOCOLS, HostValidator.DENY_COMMON_INFRASTRUCTURE_TARGETS); | ||
var file = File.createTempFile("promise_pattern", null); | ||
try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); | ||
var writer = new FileWriter(file)) { |
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.
The downloadFile
method does not handle potential exceptions that could be thrown by Urls.create
or File.createTempFile
. If either of these methods throws an exception, it will not be caught, and the method will fail without providing a meaningful error message or performing any cleanup.
Recommended Solution:
Add appropriate exception handling for Urls.create
and File.createTempFile
to ensure that any exceptions are caught and handled gracefully, possibly logging the error and providing a meaningful message to the caller.
Feedback
|
</dependency> | ||
</dependencies> | ||
</dependencyManagement> | ||
<dependencies> |
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.
Code Review:
-
Bug Risks:
- The addition of
<versions.java-security-toolkit>1.1.3</versions.java-security-toolkit>
in properties but referencing${versions.java-security-toolkit}
without defining it may lead to build failures or unexpected behavior.
- The addition of
-
Improvement Suggestions:
- Ensure that all placeholders, like
${versions.java-security-toolkit}
, are defined and resolved correctly. - Consider adding comments where necessary to explain the purpose of these changes for better code maintainability.
- Run a full build and test cycle to ensure this patch does not introduce any unintended side effects.
- Check if the versions being used are compatible with other dependencies in the project.
- Consider documenting why the
java-security-toolkit
version was updated to1.1.3
.
- Ensure that all placeholders, like
-
Additional Remarks:
- Review how this change fits into the overall architecture and design of the project.
- Make sure your IDE or build system resolves and uses the correct values for variables like
${versions.java-security-toolkit}
. - Verify if this updated version has any breaking changes compared to the previous version used in the project.
Summary:
The code patch introduces a new dependency on java-security-toolkit
, updating its version to 1.1.3
. Ensure that placeholder values are correctly resolved and that all dependencies are compatible with this newer version. Add comments for clarity and test thoroughly to prevent build issues.
Summary of Incoming Changes➕ New Feature: Added Identified Issues
Proposed Fixes1. Make Protocol List Configurable
2. Add Inline Comments
General ReviewThe code changes introduce a new feature to enhance security by preventing SSRF attacks through sandboxed URL creation. The addition of the Yours, Gooroo.dev |
</dependency> | ||
</dependencies> | ||
<build> | ||
<plugins> |
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.
From the provided code patch, here is a brief code review:
-
Bug Risks:
- Missing Version: The
<dependency>
block forio.github.pixee:java-security-toolkit
lacks a version. This may lead to dependency resolution issues or potential mismatches. - Scope: It's essential to determine if
io.github.pixee:java-security-toolkit
should be included as a test dependency or a regular dependency based on its usage.
- Missing Version: The
-
Improvement Suggestions:
- Version Specification: Add a specific version to the
io.github.pixee:java-security-toolkit
dependency to ensure consistent and predictable builds. - Consistency: Ensure that dependencies are managed consistently throughout the project. If most dependencies include versions, follow the same convention here.
- Version Specification: Add a specific version to the
Consider the context of your project and determine the appropriate version and scope for the io.github.pixee:java-security-toolkit
dependency to avoid runtime issues and maintain a consistent and manageable build configuration.
var url = Urls.create(urlString, Urls.HTTP_PROTOCOLS, HostValidator.DENY_COMMON_INFRASTRUCTURE_TARGETS); | ||
var file = File.createTempFile("promise_pattern", null); | ||
try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); | ||
var writer = new FileWriter(file)) { |
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.
Code Review Summary:
Bug Risks:
- Missing Exception Handling: Consider adding proper exception handling for potential errors that could arise during URL creation and file operations.
Improvements:
- Variable Naming and Clarity: Improve naming conventions for better code readability and maintenance.
- Security Concerns: Ensure the security implementation is thorough and covers all necessary aspects.
- Resource Management: Consider closing resources appropriately, especially when dealing with IO operations.
- Testing: Implement robust testing for this code patch to cover multiple scenarios.
Detailed Analysis:
-
Exception Handling in
downloadFile
method:- Add proper error handling mechanisms for potential exceptions that might occur during URL creation and file operations.
-
Variable Naming and Clarity:
- Consider using more descriptive names for variables like
urlString
,url
,file
,bufferedReader
, andwriter
to enhance code readability.
- Consider using more descriptive names for variables like
-
Security Concerns:
- Verify the adequacy of the security implementation, specifically pertaining to the HostValidator and URL creation process.
-
Resource Management:
- Ensure proper resource management by closing resources appropriately, possibly in a
finally
block or by utilizing try-with-resources where applicable.
- Ensure proper resource management by closing resources appropriately, possibly in a
-
Testing:
- Develop robust test cases to validate behavior under various conditions, ensuring the reliability and correctness of the methods.
By addressing these points, you can enhance the overall quality and maintainability of the codebase.
Vulnerable Libraries (2)
More info on how to fix Vulnerable Libraries in Java. 👉 Go to the dashboard for detailed results. 📥 Happy? Share your feedback with us. |
Micro-Learning Topic: Vulnerable library (Detected by phrase)Matched on "Vulnerable Libraries"Use of vulnerable components will introduce weaknesses into the application. Components with published vulnerabilities will allow easy exploitation as resources will often be available to automate the process. Try a challenge in Secure Code Warrior |
Check out the playback for this Pull Request here. |
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
4 similar comments
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
I'm confident in this change, but I'm not a maintainer of this project. Do you see any reason not to merge it? If this change was not helpful, or you have suggestions for improvements, please let me know! |
Besides the SSRF risks described above, a control like the one I suggested will also help protect against URL parsing bugs where attackers can present a URL that looks like one thing, but ends up being acted on as something else. A leading hacker in this space, Orange Tsai, has a nice visual of showing how humans and parsers will see the same URL differently in his legendary BlackHat talk: This is why I wanted to introduce an API that forces you to provide the expectations of the URL at parsing time. There's really no downside, and this code will leave practically no opportunity of ending up in a confused and possibly vulnerable state. The code will be more clear and more safe. If there are other concerns about this change, I'd love to hear about them! |
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
1 similar comment
Hello @Sowhat999. The PR is blocked on your approval. Please review it ASAP. |
This change may not be a priority right now, so I'll close it. If there was something I could have done better, please let me know! You can also customize me to make sure I'm working with you in the way you want. |
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.
@pixeebot[bot]
Thank you for your contribution to this repository! We appreciate your effort in closing pull request.
Happy coding!
User description
This change sandboxes the creation of
java.net.URL
objects so they will be more resistant to Server-Side Request Forgery (SSRF) attacks.Most of the time when you create a URL, you're intending to reference an HTTP endpoint, like an internal microservice. However, URLs can point to local file system files, a Gopher stream in your local network, a JAR file on a remote Internet site, and all kinds of other unexpected and undesirable stuff. When the URL values are influenced by attackers, they can trick your application into fetching internal resources, running malicious code, or otherwise harming the system. Consider the following code:
In this case, an attacker could supply a value like
jar:file:/path/to/appserver/lib.jar
and attempt to read the contents of your application's code.Our changes introduce sandboxing around URL creation that force the developers to specify some boundaries on the types of URLs they expect to create:
This change alone reduces attack surface significantly, but can be enhanced to create even more security by specifying some controls around the hosts we expect to connect with:
Note: Beware temptation to write some validation on your own. Parsing URLs is difficult and differences between parsers in validation and execution will certainly lead to exploits as attackers have repeatedly proven.
More reading
I have additional improvements ready for this repo! If you want to see them, leave the comment:
... and I will open a new PR right away!
🧚🤖 Powered by Pixeebot
Feedback | Community | Docs | Codemod ID: pixee:java/sandbox-url-creation
Description
Utility.java
to mitigate SSRF attacks by usingUrls.create
with security checks.java-security-toolkit
as a dependency in the project's mainpom.xml
and the promise module'spom.xml
.Changes walkthrough
Utility.java
Enhance URL Creation Security in Utility.java
promise/src/main/java/com/iluwatar/promise/Utility.java
io.github.pixee.security.HostValidator
andio.github.pixee.security.Urls
.downloadFile
method to useUrls.create
for URL creation withsecurity checks.
pom.xml
Add Java Security Toolkit Dependency to pom.xml
pom.xml
java-security-toolkit
version property.java-security-toolkit
dependency in the dependencyManagementsection.
pom.xml
Include Java Security Toolkit in Promise Module
promise/pom.xml
java-security-toolkit
dependency to the promise module.💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.