首頁 > 後端開發 > Python教學 > 拒絕服務正規表示式破壞了 FastAPI 安全性

拒絕服務正規表示式破壞了 FastAPI 安全性

WBOY
發布: 2024-08-01 20:17:11
原創
1345 人瀏覽過

歡迎各位開發者!在這篇文章中,我們將深入研究應用程式安全領域,特別關注可能惡化 FastAPI 安全性的漏洞:由不安全的正規表示式 (regex) 導致的拒絕服務 (DoS)。我們將探討建構不良的正規表示式如何導致所謂的正規表示式阻斷服務 (ReDoS)(一種 DoS 攻擊),以及如何使用強大的開發人員安全工具 Snyk 來識別和緩解這些漏洞。

了解 ReDoS 對 Python 中 FastAPI 安全性的影響

Python 是最受歡迎的程式語言之一,擁有龐大的套件和函式庫生態系統。雖然這些軟體包讓我們作為開發人員的生活變得更輕鬆,但如果沒有適當的保護,它們也會帶來潛在的風險。隨著軟體開發的快速發展,軟體包經常更新、新版本發布,有時會在不知不覺中引入安全風險。

其中一個風險是潛在的 ReDoS 攻擊,這是一種 DoS 攻擊,攻擊者向需要很長時間才能評估的正規表示式提供惡意輸入。這會導致應用程式變得無響應或顯著減慢,這可能會產生嚴重的影響,從用戶體驗下降到應用程式完全失敗。

import re
pattern = re.compile("^(a+)+$")
def check(input):
    return bool(pattern.match(input))
check("a" * 3000 + "!")
登入後複製

在上面的程式碼中,正規表示式^(a+)+$容易受到ReDoS攻擊。如果攻擊者提供一串「a」後面跟著一個非「a」字符,則正規表示式需要很長時間來評估,從而有效地導致 DoS。

Snyk 如何保護您的 FastAPI Python 應用程式

Snyk 是一款開發人員優先的安全工具,可以掃描您的 Python 程式碼以查找潛在的 ReDoS 漏洞。它提供已識別漏洞的詳細報告並推薦最合適的修復方案。

# After installing Snyk and setting up the Snyk CLI
# you can scan your project:
$ snyk test 
登入後複製

此命令將掃描您的第三方相依性清單(通常在requirements.txt 檔案中),並提供所有已識別漏洞的報告,包括潛在的ReDoS 漏洞。立即註冊免費的 Snyk 帳戶,開始掃描您的 Python 專案是否有 ReDoS 和其他漏洞。

了解此類漏洞的影響以及如何緩解它們對於維護安全的 Python 應用程式至關重要。這就是像 Snyk 這樣的工具派上用場的地方。 Snyk Open Source 可以協助識別和修復 Python 套件中的安全漏洞,包括可能導致 ReDoS 攻擊的不安全正規表示式。

讓我們仔細看看如何使用 Snyk 來識別和緩解 FastAPI Python Web 應用程式中的此類漏洞。

FastAPI 安全漏洞 CVE-2024-24762

FastAPI 是一個現代的高效能 Web 框架,用於基於標準 Python 類型提示使用 Python 建立 API。它的主要特點是速度以及快速、輕鬆地建立強大 API 的能力,使其成為需要建立高效能 RESTful API 的 Python 開發人員的熱門選擇。

FastAPI 透過提供開箱即用的路由機制、序列化/反序列化和驗證來簡化建置 API 的過程。它建構在用於 Web 部分的 Python 專案 Starlette 和用於資料部分的 Pydantic 之上。這允許開發人員利用 Python 3.6 及更高版本中提供的非同步功能。

作為範例,可以使用以下程式碼片段來完成使用 FastAPI Python Web 應用程式建立簡單的 API:

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}
登入後複製

雖然 FastAPI 是一個強大且敏捷的 API 開發工具,但它並非沒有漏洞。其中之一是 CVE-2024-24762 漏洞。這是一個拒絕服務漏洞,源自 Python 套件 python-multipart 使用的正規表示式。

python-multipart 依賴項是用於解析多部分/表單資料的 Python 函式庫。它通常用作 FastAPI 中的依賴項來管理表單資料。

當攻擊者傳送惡意字串,導致 python-multipart 中的正規表示式消耗大量 CPU,從而導致拒絕服務 (DoS) 時,就會出現該漏洞。這也稱為正規表示式阻斷服務 (ReDoS)。

Python 開發人員如何緩解此漏洞?第一步是識別專案中的漏洞。這可以使用 Snyk CLI 工具來完成。

$ snyk test
登入後複製

偵測此類漏洞需要掃描專案的依賴項,這將提供專案依賴項中所有漏洞的報告。

Snyk 測試指令的輸出發現了漏洞:

snyk test

Testing /Users/lirantal/projects/repos/fastapi-vulnerable-redos-app...

Tested 13 dependencies for known issues, found 1 issue, 1 vulnerable path.

Issues to fix by upgrading dependencies:

  Upgrade fastapi@0.109.0 to fastapi@0.109.1 to fix
  ✗ Regular Expression Denial of Service (ReDoS) (new) [High Severity][https://security.snyk.io/vuln/SNYK-PYTHON-FASTAPI-6228055] in fastapi@0.109.0
    introduced by fastapi@0.109.0

Organization:      liran.tal
Package manager:   pip
Target file:       requirements.txt
Project name:      fastapi-vulnerable-redos-app
登入後複製

要修復該漏洞,您可以升級到已修復該漏洞的 python-multipart 套件和 fastapi 的較新版本,這些版本是 Snyk 建議的。

Building and breaking FastAPI security: A step-by-step guide

Our first step is to set up a new Python project. We'll need to install FastAPI, along with a server to host it on. Uvicorn is a good choice for a server because it is lightweight and works well with FastAPI.

Start by installing FastAPI, python-multipart, and Uvicorn with pip:

pip install fastapi==0.109.0 uvicorn python-multipart==0.0.6
登入後複製

Next, create a new directory for your project, and inside that directory, create a new file for your FastAPI application. You can call it main.py.

Writing the FastAPI Python code

Now we're ready to write our FastAPI application code. Open main.py and add the following Python code:

from typing import Annotated
from fastapi.responses import HTMLResponse
from fastapi import FastAPI,Form
from pydantic import BaseModel

class Item(BaseModel):
    username: str

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def index():
    return HTMLResponse("Test", status_code=200)

@app.post("/submit/")
async def submit(username: Annotated[str, Form()]):
    return {"username": username}

@app.post("/submit_json/")
async def submit_json(item: Item):
    return {"username": item.username}
登入後複製

This simple FastAPI application has several routes (/), including /submit, which uses a multipart form. When a POST request is received, the submit route returns the username that was submitted.

Starting the server and running the application

With our FastAPI application code written, we can now start the Uvicorn server and run our application.

Use the following command to start the server:

uvicorn main:app --reload
登入後複製

You should see an output indicating that the server is running. You can test your application by navigating to http://localhost:8000 in your web browser. The message "Test" should be displayed on the page.

Breaking FastAPI security with a ReDoS attack

Now that our FastAPI application is running, we can test it for vulnerabilities. We'll use a ReDoS attack payload in the HTTP request to exploit the vulnerability in the python-multipart package that parses the content-type header value.

If you have the curl program installed, run the following command in your terminal:

curl -v -X 'POST' -H $'Content-Type: application/x-www-form-urlencoded; !=\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' --data-binary 'input=1' 'http://localhost:8000/submit/'
登入後複製

Securing your FastAPI application with Snyk

As you saw by now, open source dependencies play a key role in building Python applications. However, these third-party dependencies can sometimes be a breeding ground for vulnerabilities, thus posing significant security threats. In this context, Snyk Open Source emerges as a robust tool that helps developers identify and fix security issues effectively.

Imagine you could quickly find FastAPI security vulnerabilities already in the IDE panel when you write Python code instead of waiting until security scanners pick this up at a later stage.

The Snyk IDE extension is free, and if you’re using PyCharm, you can search for Snyk in the Plugins view and download it directly from there. If you’re using VS Code you can similarly find it in the Extensions marketplace right from the IDE.

A denial of service Regex breaks FastAPI security

Introduction to Snyk Open Source and its capabilities

Snyk Open Source is a powerful tool used for uncovering and addressing vulnerabilities in open source dependencies and container images. It is designed to integrate easily with the existing codebase and CI/CD systems, making it a handy tool for developers. It provides a comprehensive database of known vulnerabilities, enabling developers to proactively address potential breaches in security.

Step-by-step guide on how to scan Python dependencies for vulnerabilities with Snyk

To scan Python dependencies for vulnerabilities with Snyk, you first need to install the Snyk CLI. You can do this using one of the methods in the guide, or if you have a Node.js environment, you can quickly install Snyk with npm install -g snyk and then run snyk auth to authenticate.

Once installed, you can use the snyk test command to check your Python project for vulnerabilities:

snyk test --all-projects
登入後複製

Snyk will then scan all your dependencies and compare them against its vulnerability database. If any issues are found, Snyk will provide a detailed report with information about the vulnerability, its severity, and possible fixes.

Monitoring your projects with Snyk is crucial to maintain the security of your application. With Snyk, not only can you detect vulnerabilities, but you can also apply automated fixes, which can save you time and resources.

In addition, Snyk offers vulnerability alerts that notify you about new vulnerabilities that may affect your projects. This allows you to stay one step ahead and fix security issues before they can be exploited.

With the snyk monitor command, you can take a snapshot of your current project dependencies and monitor them for vulnerabilities:

snyk monitor
登入後複製

How to integrate Snyk with Git repositories

Integrating Snyk with your Git repositories allows you to automatically scan every commit for vulnerabilities. This can be done by adding Snyk as a webhook in your repository settings.

A denial of service Regex breaks FastAPI security
完成此操作後,每次推送到您的儲存庫都會觸發 Snyk 掃描,幫助您儘早擷取並修復漏洞。

總而言之,Snyk Open Source 是維護 Python 專案安全性的寶貴工具。透過掃描漏洞、監控專案以及與 Git 儲存庫集成,Snyk 使您能夠維護強大、安全的程式碼庫。如果您還沒有註冊免費的 Snyk 帳戶,請立即開始保護您的應用程式。

以上是拒絕服務正規表示式破壞了 FastAPI 安全性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板