AWS - API Gateway Enum

Support HackTricks

API Gateway

Basic Information

AWS API Gateway ni huduma kamili inayotolewa na Amazon Web Services (AWS) iliyoundwa kwa ajili ya waendelezaji kuunda, kuchapisha, na kusimamia APIs kwa kiwango kikubwa. Inafanya kazi kama lango la kuingia kwenye programu, ikiruhusu waendelezaji kuanzisha mfumo wa sheria na taratibu. Mfumo huu unadhibiti ufikiaji wa watumiaji wa nje kwa data au kazi fulani ndani ya programu.

API Gateway inakuwezesha kufafanua jinsi maombi kwa APIs zako yanapaswa kushughulikiwa, na inaweza kuunda mwisho wa API maalum kwa mbinu maalum (mfano, GET, POST, PUT, DELETE) na rasilimali. Pia inaweza kuunda SDKs za mteja (Software Development Kits) ili kurahisisha waendelezaji kuita APIs zako kutoka kwenye programu zao.

API Gateways Types

  • HTTP API: Jenga REST APIs zenye latency ya chini na gharama nafuu zikiwa na vipengele vilivyojumuishwa kama OIDC na OAuth2, na msaada wa asili wa CORS. Inafanya kazi na yafuatayo: Lambda, HTTP backends.

  • WebSocket API: Jenga API ya WebSocket kwa kutumia muunganisho endelevu kwa matumizi ya wakati halisi kama vile programu za mazungumzo au dashibodi. Inafanya kazi na yafuatayo: Lambda, HTTP, AWS Services.

  • REST API: Tengeneza REST API ambapo unapata udhibiti kamili juu ya ombi na jibu pamoja na uwezo wa usimamizi wa API. Inafanya kazi na yafuatayo: Lambda, HTTP, AWS Services.

  • REST API Private: Unda REST API ambayo inapatikana tu kutoka ndani ya VPC.

API Gateway Main Components

  1. Resources: Katika API Gateway, rasilimali ni vipengele ambavyo vinaunda muundo wa API yako. Zinawakilisha njia au mwisho tofauti wa API yako na zinahusiana na vitendo mbalimbali ambavyo API yako inasaidia. Rasilimali ni kila mbinu (mfano, GET, POST, PUT, DELETE) ndani ya kila njia (/, au /users, au /user/{id}).

  2. Stages: Hatua katika API Gateway zinawakilisha matoleo au mazingira tofauti ya API yako, kama vile maendeleo, hatua, au uzalishaji. Unaweza kutumia hatua kusimamia na kupeleka matoleo mengi ya API yako kwa wakati mmoja, ikiruhusu kujaribu vipengele vipya au marekebisho ya makosa bila kuathiri mazingira ya uzalishaji. Hatua pia zinasaidia mabadiliko ya hatua, ambayo ni jozi za funguo-thamani ambazo zinaweza kutumika kubadilisha tabia ya API yako kulingana na hatua ya sasa. Kwa mfano, unaweza kutumia mabadiliko ya hatua kuelekeza maombi ya API kwa kazi tofauti za Lambda au huduma nyingine za nyuma kulingana na hatua.

  • Hatua inaonyeshwa mwanzoni mwa URL ya mwisho wa API Gateway.

  1. Authorizers: Waandishi katika API Gateway wana jukumu la kudhibiti ufikiaji wa API yako kwa kuthibitisha utambulisho wa mpiga simu kabla ya kuruhusu ombi kuendelea. Unaweza kutumia AWS Lambda functions kama waandishi maalum, ambayo inakuwezesha kutekeleza mantiki yako mwenyewe ya uthibitishaji na idhini. Wakati ombi linapokuja, API Gateway inapeleka tokeni ya uthibitishaji wa ombi kwa waandishi wa Lambda, ambaye anashughulikia tokeni hiyo na kurudisha sera ya IAM inayotambua ni vitendo gani mpiga simu anaruhusiwa kufanya. API Gateway pia inasaidia waandishi wa ndani, kama vile AWS Identity and Access Management (IAM) na Amazon Cognito.

  2. Resource Policy: Sera ya rasilimali katika API Gateway ni hati ya JSON ambayo inafafanua ruhusa za kufikia API yako. Ni sawa na sera ya IAM lakini imeandaliwa mahsusi kwa API Gateway. Unaweza kutumia sera ya rasilimali kudhibiti nani anaweza kufikia API yako, ni mbinu zipi wanaweza kuita, na kutoka kwenye anwani zipi za IP au VPC wanaweza kuungana. Sera za rasilimali zinaweza kutumika kwa pamoja na waandishi ili kutoa udhibiti wa ufikiaji wa kina kwa API yako.

  • Ili kufanya kazi, API inahitaji kupelekwa tena baada ya sera ya rasilimali kubadilishwa.

Logging

Kwa kawaida, CloudWatch Logs ziko zimemwishwa, Access Logging iko zimemwishwa, na X-Ray tracing pia iko zimemwishwa.

Enumeration

Kumbuka kwamba katika APIs zote za AWS za kuorodhesha rasilimali (apigateway na apigatewayv2) ruhusa pekee unayohitaji na ruhusa pekee ya kusoma inayoweza kutolewa ni apigateway:GET, kwa hiyo unaweza kuorodhesha kila kitu.

# 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

Mamlaka tofauti za kufikia mwisho wa API Gateway

Sera ya Rasilimali

Inawezekana kutumia sera za rasilimali kufafanua nani anaweza kuita mwisho wa API. Katika mfano ufuatao unaweza kuona kwamba IP iliyoonyeshwa haiwezi kuita mwisho wa /resource_policy kupitia GET.

IAM Authorizer

Inawezekana kuweka kwamba mbinu ndani ya njia (rasilimali) inahitaji uthibitisho wa IAM ili kuitwa.

Wakati hii imewekwa utapokea kosa {"message":"Missing Authentication Token"} unapojaribu kufikia mwisho bila mamlaka yoyote.

Njia rahisi ya kuzalisha token inayotarajiwa na programu ni kutumia aina ya Authorization AWS Signature ndani ya Postman.

Weka accessKey na SecretKey za akaunti unayotaka kutumia na unaweza kuthibitisha dhidi ya mwisho wa API.

Itazalisha Authorization header kama:

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

Kumbuka kwamba katika hali nyingine Authorizer inaweza kuwa imeandikwa vibaya na kutuma chochote ndani ya Authorization header kutaruhusu kuona maudhui yaliyofichwa.

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

Inawezekana kutumia lambda ambayo kwa msingi wa token iliyotolewa it arejeshe sera ya IAM ikionyesha kama mtumiaji ameidhinishwa kuita kiunganishi cha API. Unaweza kuweka kila njia ya rasilimali ambayo itakuwa ikitumia mthibitishaji.

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>

Call it with something like:

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

Kulingana na msimbo wa Lambda, ruhusa hii inaweza kuwa hatarini

</div>

Note that if a **deny policy is generated and returned** the error returned by API Gateway is: `{"Message":"User is not authorized to access this resource with an explicit deny"}`

This way you could **identify this authorization** being in place.

### Required API Key

It's possible to set API endpoints that **require a valid API key** to contact it.

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

It's possible to generate API keys in the API Gateway portal and even set how much it can be used (in terms of requests per second and in terms of requests per month).

To make an API key work, you need to add it to a **Usage Plan**, this usage plan must be added to the **API Stage** and the associated API stage needs to have a configured **method throttling** to the **endpoint** requiring the API key:

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

## Unauthenticated Access

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

## Privesc

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

## Persistence

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

Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <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>Support HackTricks</summary>

* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.

</details>

</div>

Last updated