AWS - API Gateway Enum

ゼロからヒーローまでAWSハッキングを学ぶ htARTE(HackTricks AWS Red Team Expert)

HackTricksをサポートする他の方法:

API Gateway

基本情報

AWS API Gatewayは、開発者が大規模なAPIを作成、公開、監視するために設計されたAmazon Web Services(AWS)が提供する包括的なサービスです。これはアプリケーションへのエントリーポイントとして機能し、開発者がルールと手順のフレームワークを確立できるようにします。このフレームワークは、外部ユーザーがアプリケーション内の特定のデータや機能にアクセスする方法を規定します。

API Gatewayを使用すると、APIへのリクエストの処理方法を定義でき、特定のメソッド(例:GET、POST、PUT、DELETE)とリソースを持つカスタムAPIエンドポイントを作成できます。また、クライアントSDK(ソフトウェア開発キット)を生成して、開発者がアプリケーションからAPIを呼び出しやすくすることもできます。

API Gatewayの種類

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

Supported Protocols

  • HTTP

  • WEBSOCKET

Integration Types

  • AWS_PROXY

  • HTTP_PROXY

  • HTTP

  • AWS

  • MOCK

Payload Encoding

  • 1.0

  • 2.0

Route Key Types

  • METHOD

  • PATH

Security Types

  • NONE

  • AWS_IAM

  • CUSTOM

Authorization Types

  • NONE

  • AWS_IAM

  • CUSTOM

Connection Types

  • INTERNET

  • VPC_LINK

API Endpoint Types

  • REGIONAL

  • PRIVATE

  • EDGE

Route Selection Expressions

  • $request.method

  • $request.path

  • $request.header

  • $request.querystring

  • $request.body

  • $context.authorizer.claims

  • $context.authorizer.principalId

  • $context.authorizer.integrationLatency

  • $context.identity.sourceIp -json:api-gateway-v2-enum.md

# 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内で**AuthorizationタイプをAWS Signature**に設定することです。

使用したいアカウントの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ヘッダー何でも送信するだけで非表示コンテンツを見ることができる可能性があります。

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)

カスタムLambda認証者

特定のトークンに基づいてIAMポリシーを返すLambdaを使用して、ユーザーがAPIエンドポイントを呼び出す権限があるかどうかを示すことができます。 認証者を使用するリソースメソッドを設定できます。

Lambda認証者のコード例

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

<details>

<summary><strong>htARTE(HackTricks AWS Red Team Expert)</strong>でAWSハッキングをゼロからヒーローまで学びましょう!</summary>

HackTricksをサポートする他の方法:

* **HackTricksで企業を宣伝したい**場合や**HackTricksをPDFでダウンロード**したい場合は、[**SUBSCRIPTION PLANS**](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)のコレクションを見つける
* 💬 [**Discordグループ**](https://discord.gg/hRep4RUj7f)に参加するか、[**telegramグループ**](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)のGitHubリポジトリにPRを提出する

</details>

最終更新