AWS - API Gateway Enum

Tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

API Gateway

기본 정보

AWS API Gateway는 개발자가 대규모로 API를 생성, 게시 및 관리할 수 있도록 설계된 Amazon Web Services (AWS)에서 제공하는 종합 서비스입니다. 이는 애플리케이션의 진입점 역할을 하며, 개발자가 규칙 및 절차의 프레임워크를 설정할 수 있도록 허용합니다. 이 프레임워크는 외부 사용자가 애플리케이션 내의 특정 데이터나 기능에 접근하는 방식을 관리합니다.

API Gateway는 API에 대한 요청이 어떻게 처리되어야 하는지를 정의할 수 있게 해주며, 특정 메서드(예: GET, POST, PUT, DELETE) 및 리소스를 가진 사용자 정의 API 엔드포인트를 생성할 수 있습니다. 또한 개발자가 애플리케이션에서 API를 호출하기 쉽게 하기 위해 클라이언트 SDK(소프트웨어 개발 키트)를 생성할 수 있습니다.

API Gateway 유형

  • HTTP API: OIDC 및 OAuth2와 같은 내장 기능과 기본 CORS 지원을 갖춘 저지연 및 비용 효율적인 REST API를 구축합니다. 다음과 함께 작동합니다: Lambda, HTTP 백엔드.
  • WebSocket API: 채팅 애플리케이션이나 대시보드와 같은 실시간 사용 사례를 위해 지속적인 연결을 사용하는 WebSocket API를 구축합니다. 다음과 함께 작동합니다: Lambda, HTTP, AWS 서비스.
  • REST API: 요청 및 응답에 대한 완전한 제어와 API 관리 기능을 갖춘 REST API를 개발합니다. 다음과 함께 작동합니다: Lambda, HTTP, AWS 서비스.
  • REST API Private: VPC 내에서만 접근할 수 있는 REST API를 생성합니다.

API Gateway 주요 구성 요소

  1. 리소스: API Gateway에서 리소스는 API의 구조를 구성하는 요소입니다. 이들은 API의 다양한 경로 또는 엔드포인트를 나타내며, API가 지원하는 다양한 작업에 해당합니다. 리소스는 각 경로(/, 또는 /users, 또는 /user/{id}) 내의 각 메서드(예: GET, POST, PUT, DELETE)입니다.
  2. 단계: API Gateway의 단계는 개발, 스테이징 또는 프로덕션과 같은 API의 다양한 버전 또는 환경을 나타냅니다. 단계를 사용하여 API의 여러 버전을 동시에 관리 및 배포할 수 있으며, 이를 통해 프로덕션 환경에 영향을 주지 않고 새로운 기능이나 버그 수정을 테스트할 수 있습니다. 단계는 또한 현재 단계에 따라 API의 동작을 구성하는 데 사용할 수 있는 키-값 쌍인 단계 변수를 지원합니다. 예를 들어, 단계 변수를 사용하여 단계에 따라 API 요청을 다른 Lambda 함수나 기타 백엔드 서비스로 전달할 수 있습니다.
  • 단계는 API Gateway 엔드포인트의 URL 시작 부분에 표시됩니다.
  1. 인증자: API Gateway의 인증자는 요청이 진행되기 전에 호출자의 신원을 확인하여 API에 대한 접근을 제어하는 역할을 합니다. AWS Lambda 함수를 사용자 정의 인증자로 사용할 수 있으며, 이를 통해 자체 인증 및 권한 부여 로직을 구현할 수 있습니다. 요청이 들어오면 API Gateway는 요청의 인증 토큰을 Lambda 인증자에게 전달하고, 인증자는 토큰을 처리하여 호출자가 수행할 수 있는 작업을 결정하는 IAM 정책을 반환합니다. API Gateway는 AWS Identity and Access Management (IAM)Amazon Cognito와 같은 내장 인증자도 지원합니다.
  2. 리소스 정책: API Gateway의 리소스 정책은 API에 대한 접근 권한을 정의하는 JSON 문서입니다. 이는 IAM 정책과 유사하지만 API Gateway에 맞게 특별히 조정된 것입니다. 리소스 정책을 사용하여 누가 API에 접근할 수 있는지, 어떤 메서드를 호출할 수 있는지, 어떤 IP 주소나 VPC에서 연결할 수 있는지를 제어할 수 있습니다. 리소스 정책은 인증자와 함께 사용하여 API에 대한 세밀한 접근 제어를 제공할 수 있습니다.
  • 리소스 정책이 수정된 후에는 API를 다시 배포해야 효과가 발생합니다.

로깅

기본적으로 CloudWatch Logs꺼져 있으며, Access Logging꺼져 있고, X-Ray tracing꺼져 있습니다.

열거

Tip

리소스를 열거하기 위한 두 가지 AWS API(apigatewayapigatewayv2)에서 필요한 유일한 권한이자 유일한 읽기 권한은 **apigateway:GET**입니다. 이를 통해 모든 것을 열거할 수 있습니다.

# Generic info
aws apigateway get-account
aws apigateway get-domain-names
aws apigateway get-usage-plans
aws apigateway get-vpc-links
aws apigateway get-client-certificates

# Enumerate APIs
aws apigateway get-rest-apis # This will also show the resource policy (if any)
## Get stages
aws apigateway get-stages --rest-api-id <id>
## Get resources
aws apigateway get-resources --rest-api-id <id>
## Get API resource action per HTTP verb (check authorizers and api key required)
aws apigateway get-method --http-method GET --rest-api-id <api-id> --resource-id <resource-id>

## Call API
https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource>
## API authorizers
aws apigateway get-authorizers --rest-api-id <id>
## Models
aws apigateway get-models --rest-api-id <id>
## More info
aws apigateway get-gateway-responses --rest-api-id <id>
aws apigateway get-request-validators --rest-api-id <id>
aws apigateway get-deployments --rest-api-id <id>

# Get api keys generated
aws apigateway get-api-keys --include-value
aws apigateway get-api-key --api-key <id> --include-value # Get just 1
## Example use API key
curl -X GET -H "x-api-key: AJE&Ygenu4[..]" https://e83uuftdi8.execute-api.us-east-1.amazonaws.com/dev/test
## Usage plans
aws apigateway get-usage-plans #Get limit use info
aws apigateway get-usage-plan-keys --usage-plan-id <plan_id> #Get clear text values of api keys
aws apigateway get-usage-plan-key --usage-plan-id <plan_id> --key-id <key_id>
###Already consumed
aws apigateway get-usage --usage-plan-id <plan_id> --start-date 2023-07-01 --end-date 2023-07-12

API Gateway 엔드포인트에 접근하기 위한 다양한 권한

리소스 정책

리소스 정책을 사용하여 API 엔드포인트를 호출할 수 있는 대상을 정의할 수 있습니다.
다음 예제에서는 지정된 IP가 GET을 통해 /resource_policy 엔드포인트를 호출할 수 없음을 볼 수 있습니다.

IAM 인증자

경로(리소스) 내의 메서드가 호출하기 위해 IAM 인증을 요구하도록 설정할 수 있습니다.

이 설정이 되어 있을 때, 인증 없이 엔드포인트에 접근하려고 하면 {"message":"Missing Authentication Token"} 오류가 발생합니다.

애플리케이션에서 예상되는 토큰을 생성하는 쉬운 방법 중 하나는 curl을 사용하는 것입니다.

$ curl -X <method> https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource> --user <AWS_ACCESS_KEY>:<AWS_SECRET_KEY> --aws-sigv4 "aws:amz:<region>:execute-api"

또 다른 방법은 Postman 내에서 Authorization 유형 **AWS Signature**를 사용하는 것입니다.

사용하려는 계정의 accessKey와 SecretKey를 설정하면 API 엔드포인트에 대해 인증할 수 있습니다.

두 방법 모두 다음과 같은 Authorization header를 생성합니다:

AWS4-HMAC-SHA256 Credential=AKIAYY7XU6ECUDOTWB7W/20220726/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=9f35579fa85c0d089c5a939e3d711362e92641e8c14cc571df8c71b4bc62a5c2

다른 경우에는 Authorizer잘못 코딩되었을 수 있으며, Authorization header 안에 무엇이든 보내면 숨겨진 콘텐츠를 볼 수 있게 됩니다.

Python을 사용한 요청 서명


pip install requests
pip install requests-aws4auth
pip install boto3

import boto3
import requests
from requests_aws4auth import AWS4Auth

region = 'us-east-1'  # Region
service = 'execute-api'
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'

url = 'https://<apiid>.execute-api.us-east-1.amazonaws.com/<stage>/<resource>'

session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
credentials = session.get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)

response = requests.get(url, auth=awsauth)

print(response.text)

커스텀 람다 인증자

주어진 토큰을 기반으로 하는 람다를 사용하여 IAM 정책을 반환하여 사용자가 API 엔드포인트를 호출할 수 있는 권한이 있는지 확인할 수 있습니다.
인증자를 사용할 각 리소스 메서드를 설정할 수 있습니다.

람다 인증자 코드 예제 ```python import json

def lambda_handler(event, context): token = event[‘authorizationToken’] method_arn = event[‘methodArn’]

if not token: return { ‘statusCode’: 401, ‘body’: ‘Unauthorized’ }

try:

Replace this with your own token validation logic

if token == “your-secret-token”: return generate_policy(‘user’, ‘Allow’, method_arn) else: return generate_policy(‘user’, ‘Deny’, method_arn) except Exception as e: print(e) return { ‘statusCode’: 500, ‘body’: ‘Internal Server Error’ }

def generate_policy(principal_id, effect, resource): policy = { ‘principalId’: principal_id, ‘policyDocument’: { ‘Version’: ‘2012-10-17’, ‘Statement’: [ { ‘Action’: ‘execute-api:Invoke’, ‘Effect’: effect, ‘Resource’: resource } ] } } return policy

</details>

다음과 같이 호출하세요:

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>curl "https://jhhqafgh6f.execute-api.eu-west-1.amazonaws.com/prod/custom_auth" -H 'Authorization: your-secret-token'
</strong></code></pre>

> [!WARNING]
> Lambda 코드에 따라 이 인증은 취약할 수 있습니다.

**거부 정책이 생성되어 반환되면** API Gateway에서 반환되는 오류는: `{"Message":"User is not authorized to access this resource with an explicit deny"}`입니다.

이렇게 하면 **이 인증이 존재함을 식별할 수 있습니다.**

### 필수 API 키

유효한 API 키가 필요하도록 설정된 API 엔드포인트를 만들 수 있습니다.

<figure><img src="../../../images/image (88).png" alt=""><figcaption></figcaption></figure>

API Gateway 포털에서 API 키를 생성할 수 있으며, 사용량(초당 요청 수 및 월간 요청 수)에 대한 제한을 설정할 수도 있습니다.

API 키를 작동시키려면 **사용 계획**에 추가해야 하며, 이 사용 계획은 **API 단계**에 추가되어야 하고, 관련된 API 단계는 API 키가 필요한 **엔드포인트**에 대해 **메서드 스로틀링**이 구성되어 있어야 합니다:

<figure><img src="../../../images/image (198).png" alt=""><figcaption></figcaption></figure>

## 인증되지 않은 접근

<a class="content_ref" href="../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum/index.html"><span class="content_ref_label">AWS - API Gateway Unauthenticated Enum</span></a>

## 권한 상승

<a class="content_ref" href="../aws-privilege-escalation/aws-apigateway-privesc/index.html"><span class="content_ref_label">AWS - Apigateway Privesc</span></a>

## 포스트 익스플로잇

<a class="content_ref" href="../aws-post-exploitation/aws-api-gateway-post-exploitation/index.html"><span class="content_ref_label">AWS - API Gateway Post Exploitation</span></a>

## 지속성

<a class="content_ref" href="../aws-persistence/aws-api-gateway-persistence/index.html"><span class="content_ref_label">AWS - API Gateway Persistence</span></a>

> [!TIP]
> AWS 해킹 배우기 및 연습하기:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> GCP 해킹 배우기 및 연습하기: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Azure 해킹 배우기 및 연습하기: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>HackTricks 지원하기</summary>
>
> - [**구독 계획**](https://github.com/sponsors/carlospolop) 확인하기!
> - **💬 [**Discord 그룹**](https://discord.gg/hRep4RUj7f) 또는 [**텔레그램 그룹**](https://t.me/peass)에 참여하거나 **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**를 팔로우하세요.**
> - **[**HackTricks**](https://github.com/carlospolop/hacktricks) 및 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.**
>
> </details>