환영합니다, 동료 개발자 여러분! 이 블로그 게시물에서는 특히 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.
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.
이 작업이 완료되면 저장소에 푸시할 때마다 Snyk 스캔이 실행되어 가능한 한 빨리 취약점을 찾아 수정하는 데 도움이 됩니다.
결론적으로 Snyk Open Source는 Python 프로젝트의 보안을 유지하는 데 유용한 도구입니다. 취약점을 검색하고, 프로젝트를 모니터링하고, Git 리포지토리와 통합함으로써 Snyk를 사용하면 강력하고 안전한 코드베이스를 유지할 수 있습니다. 아직 가입하지 않으셨다면 지금 무료 Snyk 계정에 가입하고 애플리케이션 보안을 시작하세요.
위 내용은 서비스 거부 Regex로 인해 FastAPI 보안이 손상됨의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

경치 좋은 스팟 댓글 분석에서 Jieba Word 세분화 문제를 해결하는 방법은 무엇입니까? 경치가 좋은 스팟 댓글 및 분석을 수행 할 때 종종 Jieba Word 세분화 도구를 사용하여 텍스트를 처리합니다 ...

정규 표현식을 사용하여 첫 번째 닫힌 태그와 정지와 일치하는 방법은 무엇입니까? HTML 또는 기타 마크 업 언어를 다룰 때는 정규 표현식이 종종 필요합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Dreamweaver Mac版
시각적 웹 개발 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
