AWS - API Gateway Enum

Support HackTricks

API Gateway

Basic Information

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

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

API Gateways Types

  • 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 Main Components

  1. Resources: API Gateway에서 리소스는 API의 구조를 구성하는 요소입니다. 이들은 API의 다양한 경로 또는 엔드포인트를 나타내며, API가 지원하는 다양한 작업에 해당합니다. 리소스는 각 경로(/, 또는 /users, 또는 /user/{id}) 내의 각 메서드(예: GET, POST, PUT, DELETE)입니다.

  2. Stages: API Gateway의 스테이지는 개발, 스테이징 또는 프로덕션과 같은 API의 다양한 버전 또는 환경을 나타냅니다. 스테이지를 사용하여 API의 여러 버전을 동시에 관리 및 배포할 수 있으며, 이를 통해 프로덕션 환경에 영향을 주지 않고 새로운 기능이나 버그 수정을 테스트할 수 있습니다. 스테이지는 또한 현재 스테이지에 따라 API의 동작을 구성하는 데 사용할 수 있는 키-값 쌍인 스테이지 변수를 지원합니다. 예를 들어, 스테이지 변수를 사용하여 스테이지에 따라 API 요청을 다른 Lambda 함수나 기타 백엔드 서비스로 유도할 수 있습니다.

  • 스테이지는 API Gateway 엔드포인트의 URL 시작 부분에 표시됩니다.

  1. Authorizers: API Gateway의 인증자는 요청이 진행되기 전에 호출자의 신원을 확인하여 API에 대한 접근을 제어하는 역할을 합니다. AWS Lambda 함수를 사용자 정의 인증자로 사용할 수 있으며, 이를 통해 자체 인증 및 권한 부여 논리를 구현할 수 있습니다. 요청이 들어오면 API Gateway는 요청의 인증 토큰을 Lambda 인증자에게 전달하고, 인증자는 토큰을 처리하여 호출자가 수행할 수 있는 작업을 결정하는 IAM 정책을 반환합니다. API Gateway는 또한 AWS Identity and Access Management (IAM)Amazon Cognito와 같은 내장 인증자를 지원합니다.

  2. Resource Policy: API Gateway의 리소스 정책은 API에 대한 접근 권한을 정의하는 JSON 문서입니다. 이는 IAM 정책과 유사하지만 API Gateway에 맞게 특별히 조정된 것입니다. 리소스 정책을 사용하여 API에 접근할 수 있는 사람, 호출할 수 있는 메서드, 연결할 수 있는 IP 주소 또는 VPC를 제어할 수 있습니다. 리소스 정책은 인증자와 함께 사용하여 API에 대한 세밀한 접근 제어를 제공할 수 있습니다.

  • 리소스 정책이 수정된 후 API가 다시 배포되어야 효과가 발생합니다.

Logging

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

Enumeration

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"} 오류가 발생합니다.

애플리케이션에서 예상되는 토큰을 생성하는 쉬운 방법은 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 안에 무엇이든 보내면 숨겨진 콘텐츠를 볼 수 있습니다.

Request Signing Using 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)

Custom Lambda Authorizer

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

Lambda Authorizer Code Example

```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>

<div data-gb-custom-block data-tag="hint" data-style='warning'>

Lambda 코드에 따라 이 인증은 취약할 수 있습니다.

</div>

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

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

### 필수 API 키

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

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

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

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

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

## 인증되지 않은 접근

<div data-gb-custom-block data-tag="content-ref" data-url='../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md'>

[aws-api-gateway-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md)

</div>

## 권한 상승

<div data-gb-custom-block data-tag="content-ref" data-url='../aws-privilege-escalation/aws-apigateway-privesc.md'>

[aws-apigateway-privesc.md](../aws-privilege-escalation/aws-apigateway-privesc.md)

</div>

## 포스트 익스플로잇

<div data-gb-custom-block data-tag="content-ref" data-url='../aws-post-exploitation/aws-api-gateway-post-exploitation.md'>

[aws-api-gateway-post-exploitation.md](../aws-post-exploitation/aws-api-gateway-post-exploitation.md)

</div>

## 지속성

<div data-gb-custom-block data-tag="content-ref" data-url='../aws-persistence/aws-api-gateway-persistence.md'>

[aws-api-gateway-persistence.md](../aws-persistence/aws-api-gateway-persistence.md)

</div>

<div data-gb-custom-block data-tag="hint" data-style='success'>

AWS 해킹 배우기 및 연습하기:<img src="/.gitbook/assets/image.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/image.png" alt="" data-size="line">\
GCP 해킹 배우기 및 연습하기: <img src="/.gitbook/assets/image (2).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/image (2).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)

<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>

</div>

Last updated