>  기사  >  백엔드 개발  >  서비스 거부 Regex로 인해 FastAPI 보안이 손상됨

서비스 거부 Regex로 인해 FastAPI 보안이 손상됨

WBOY
WBOY원래의
2024-08-01 20:17:11980검색

환영합니다, 동료 개발자 여러분! 이 블로그 게시물에서는 특히 FastAPI 보안을 악화시킬 수 있는 취약성, 즉 안전하지 않은 정규식(regex)으로 인한 서비스 거부(DoS)에 초점을 맞춰 애플리케이션 보안의 세계를 깊이 탐구할 것입니다. 잘못 구성된 정규 표현식이 어떻게 DoS 공격의 한 형태인 정규식 서비스 거부(ReDoS)로 이어질 수 있는지, 그리고 강력한 개발자 보안 도구인 Snyk를 사용하여 이러한 취약점을 식별하고 완화할 수 있는 방법을 살펴보겠습니다.

Python의 FastAPI 보안에 대한 ReDoS의 영향 이해

가장 인기 있는 프로그래밍 언어 중 하나인 Python에는 패키지와 라이브러리로 구성된 방대한 생태계가 있습니다. 이러한 패키지는 개발자로서 우리의 삶을 더 쉽게 만들어 주지만 제대로 보호되지 않으면 잠재적인 위험을 초래할 수도 있습니다. 소프트웨어 개발 속도가 빨라짐에 따라 패키지가 자주 업데이트되고 새 버전이 출시되며 때로는 자신도 모르게 보안 위험이 발생합니다.

그러한 위험 중 하나는 공격자가 평가하는 데 매우 오랜 시간이 걸리는 정규 표현식에 악의적인 입력을 제공하는 DoS 공격의 한 형태인 ReDoS 공격의 가능성입니다. 이로 인해 애플리케이션이 응답하지 않거나 크게 느려지며, 이는 사용자 경험 저하부터 애플리케이션 전체 실패까지 심각한 영향을 미칠 수 있습니다.

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 

이 명령은 일반적으로 요구사항.txt 파일에서 타사 종속성 매니페스트를 검사하고 잠재적인 ReDoS 취약점을 포함하여 식별된 모든 취약점에 대한 보고서를 제공합니다. 지금 무료 Snyk 계정에 가입하여 Python 프로젝트에서 ReDoS 및 기타 취약점을 검색해 보세요.

이러한 취약점의 영향과 이를 완화하는 방법을 이해하는 것은 안전한 Python 애플리케이션을 유지하는 데 중요합니다. Snyk와 같은 도구가 유용한 곳입니다. Snyk Open Source는 ReDoS 공격으로 이어질 수 있는 안전하지 않은 정규 표현식을 포함하여 Python 패키지의 보안 취약성을 식별하고 수정하는 데 도움이 될 수 있습니다.

Snyk를 사용하여 FastAPI Python 웹 애플리케이션에서 이러한 취약점을 식별하고 완화하는 방법을 자세히 살펴보겠습니다.

CVE-2024-24762의 FastAPI 보안 취약점

FastAPI는 표준 Python 유형 힌트를 기반으로 Python으로 API를 구축하기 위한 최신 고성능 웹 프레임워크입니다. 주요 특징은 강력한 API를 빠르고 쉽게 구축할 수 있는 속도와 능력으로, 고성능 RESTful API를 구축해야 하는 Python 개발자에게 인기 있는 선택입니다.

FastAPI는 라우팅 메커니즘, 직렬화/역직렬화 및 검증을 즉시 제공하여 API 구축 프로세스를 단순화합니다. 이는 웹 파트용 Python 프로젝트 Starlette와 데이터 파트용 Pydantic을 기반으로 구축되었습니다. 이를 통해 개발자는 Python 3.6 이상에서 사용할 수 있는 비동기 기능을 활용할 수 있습니다.

예를 들어 FastAPI Python 웹 애플리케이션으로 간단한 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 계정에 가입하고 애플리케이션 보안을 시작하세요.

위 내용은 서비스 거부 Regex로 인해 FastAPI 보안이 손상됨의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:DevOps용 Python다음 기사:DevOps용 Python