This rule helps prevent Server-Side Request Forgery (SSRF) attacks. SSRF attacks manipulate the server to make HTTP requests to an arbitrary domain of the attacker’s choosing. This can lead to unauthorized actions or access to data within the server, potentially exposing sensitive information.
This rule is important to enforce because SSRF attacks can cause significant damage, allowing attackers to bypass firewall protections, perform actions on behalf of the server, or gain unauthorized access to data. The impact of such an attack can be severe, leading to data breaches or server control takeover.
Good coding practices to avoid SSRF attacks include validating and sanitizing user inputs and limiting the server’s ability to initiate outbound requests.
@app.route("/cmd",methods=['POST'])defcmd():filename=request.form['filename']try:if"http"notinstr(urlparse(filename).scheme):host=request.url[:-4]filename=host+"/static/"+filenameresult=eval(requests.get(filename).text)returnrender_template("index.html",result=result)else:result=eval(requests.get(filename).text)returnrender_template("index.html",result=result)exceptException:returnrender_template("index.html",result="Unexpected error during the execution of the predefined command.")
Compliant Code Examples
importrequestsfromflaskimportrequest,render_templatefromurllib.parseimporturlparse@app.route("/cmd",methods=['POST'])defcmd():filename=request.form.get('filename')try:ifnotfilenameorlen(filename)>255:raiseValueError("Invalid filename")ifany(cinfilenameforcin[';','&','|','$','<','>','`']):raiseValueError("Invalid filename")parsed_url=urlparse(filename)ifparsed_url.schemenotin["http","https"]:host=request.url_root.rstrip('/')filename=f"{host}/static/{filename}"response=requests.get(filename)response.raise_for_status()result=response.textreturnrender_template("index.html",result=result)exceptExceptionase:returnrender_template("index.html",result="Unexpected error during the execution of the predefined command.")
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- python-flask # Rules to enforce Python flask.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines