AWS - API Gateway Enum

htARTE (HackTricks AWS Red Team 전문가)에서 **제로부터 영웅까지 AWS 해킹 배우기**!

다른 HackTricks 지원 방법:

API Gateway

기본 정보

AWS API Gateway는 개발자가 대규모로 API를 생성, 게시 및 관리할 수 있도록 설계된 Amazon Web Services (AWS)에서 제공하는 포괄적인 서비스입니다. 이는 응용 프로그램의 진입점으로 작동하여 개발자가 규칙 및 절차의 프레임워크를 설정할 수 있게 합니다. 이 프레임워크는 외부 사용자가 응용 프로그램 내의 특정 데이터 또는 기능에 액세스하는 방법을 규제합니다.

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

API 게이트웨이 유형

  • HTTP API: OIDC 및 OAuth2와 같은 내장 기능을 갖춘 저지연 및 비용 효율적인 REST API를 구축하고, 네이티브 CORS 지원을 제공합니다. 다음과 함께 작동: 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꺼져 있으며, 액세스 로깅꺼져 있으며, X-Ray 추적꺼져 있습니다.

열거

AWS API를 열거하는 데 필요한 유일한 권한 및 부여할 수 있는 유일한 읽기 권한은 **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

AWS API Gateway v2는 HTTP API를 제공합니다. 다음은 AWS API Gateway v2에서 사용할 수 있는 몇 가지 주요 기능입니다.

  1. Route: HTTP API 요청을 처리하는 데 사용되는 경로를 정의합니다.

  2. Integration: 다른 AWS 서비스 또는 사용자 지정 엔드포인트와의 통합을 설정합니다.

  3. Authorizers: 요청을 인증하고 권한 부여하는 데 사용됩니다.

  4. Deployments: API의 버전을 배포하고 관리합니다.

  5. Stages: API의 환경을 정의하고 관리합니다.

  6. Access Logging: API에 대한 액세스 로그를 활성화하고 구성합니다.

  7. Throttling: API 요청에 대한 쓰로틀링을 구성합니다.

  8. Monitoring: API의 성능을 모니터링하고 추적합니다.

  9. CORS: Cross-Origin Resource Sharing(CORS)를 구성하여 웹 애플리케이션 간의 리소스 공유를 관리합니다.

# Generic info
aws apigatewayv2 get-account --
aws apigatewayv2 get-domain-names
aws apigatewayv2 get-domain-name --domain-name <name>
aws apigatewayv2 get-usage-plans --
aws apigatewayv2 get-vpc-links
aws apigatewayv2 get-client-certificates --

# Enumerate APIs
aws apigatewayv2 get-apis # This will also show the resource policy (if any)
aws apigatewayv2 get-api --api-id <id>

## Get all the info from an api at once
aws apigatewayv2 export-api --api-id <id> --output-type YAML --specification OAS30 /tmp/api.yaml

## Get stages
aws apigatewayv2 get-stages --api-id <id>

## Get routes
aws apigatewayv2 get-routes --api-id <id>
aws apigatewayv2 get-route --api-id <id> --route-id <route-id>

## Get deployments
aws apigatewayv2 get-deployments --api-id <id>
aws apigatewayv2 get-deployment --api-id <id> --deployment-id <dep-id>

## Get integrations
aws apigatewayv2 get-integrations --api-id <id>

## Get authorizers
aws apigatewayv2 get-authorizers --api-id <id>
aws apigatewayv2 get-authorizer --api-id <id> --authorizer-id <uth-id>

## Get domain mappings
aws apigatewayv2 get-api-mappings --api-id <id> --domain-name <dom-name>
aws apigatewayv2 get-api-mapping --api-id <id> --api-mapping-id <map-id> --domain-name <dom-name>

## Get models
aws apigatewayv2 get-models --api-id <id>

## Call API
https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource>

API Gateway 엔드포인트에 액세스하는 다양한 권한 부여 방법

리소스 정책

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

IAM 인증자

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

이를 설정하면 권한 없이 엔드포인트에 액세스하려고 시도할 때 {"message":"Missing Authentication Token"} 오류가 발생합니다.

애플리케이션이 예상 토큰을 생성하는 간단한 방법은 Postman에서 AWS Signature 유형의 **Authorization**을 사용하는 것입니다.

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

다음과 같은 Authorization 헤더가 생성됩니다:

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

파이썬을 사용한 요청 서명

Authorizer잘못된 코드로 작성되어 있어 Authorization 헤더에 아무 값이나 보내면 숨겨진 콘텐츠를 볼 수 있게 될 수도 있습니다.


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)

사용자 정의 Lambda Authorizer

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

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

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

</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 Stage**에 추가되어야 하며, 연결된 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>

## Post Exploitation

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

<details>

<summary><strong>htARTE (HackTricks AWS Red Team Expert)</strong>를 통해 제로부터 AWS 해킹을 전문가로 배우세요!</summary>

HackTricks를 지원하는 다른 방법:

* **회사를 HackTricks에서 광고하거나 PDF로 다운로드하려면** [**구독 요금제**](https://github.com/sponsors/carlospolop)를 확인하세요!
* [**공식 PEASS & HackTricks 스왜그**](https://peass.creator-spring.com)를 구매하세요
* [**The PEASS Family**](https://opensea.io/collection/the-peass-family)를 발견하세요, 당사의 독점 [**NFTs**](https://opensea.io/collection/the-peass-family) 컬렉션
* 💬 [**디스코드 그룹**](https://discord.gg/hRep4RUj7f) 또는 [**텔레그램 그룹**](https://t.me/peass)에 **가입**하거나 **트위터** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)를 **팔로우**하세요.
* **HackTricks** 및 **HackTricks Cloud** 깃허브 저장소에 PR을 제출하여 **해킹 트릭을 공유**하세요.

</details>

最終更新