Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/

This commit is contained in:
Translator
2024-12-31 20:29:08 +00:00
parent 2753c75e8b
commit 396dbafaf2
245 changed files with 9878 additions and 12609 deletions

View File

@@ -4,31 +4,30 @@
## Cognito
Amazon Cognito is utilized for **authentication, authorization, and user management** in web and mobile applications. It allows users the flexibility to sign in either directly using a **user name and password** or indirectly through a **third party**, including Facebook, Amazon, Google, or Apple.
Amazon Cognito word gebruik vir **authentisering, autorisering, en gebruikersbestuur** in web- en mobiele toepassings. Dit bied gebruikers die buigsaamheid om in te teken of direk met 'n **gebruikersnaam en wagwoord** of indirek deur 'n **derde party**, insluitend Facebook, Amazon, Google, of Apple.
Central to Amazon Cognito are two primary components:
Sentraal tot Amazon Cognito is twee primêre komponente:
1. **User Pools**: These are directories designed for your app users, offering **sign-up and sign-in functionalities**.
2. **Identity Pools**: These pools are instrumental in **authorizing users to access different AWS services**. They are not directly involved in the sign-in or sign-up process but are crucial for resource access post-authentication.
1. **Gebruikerspoele**: Dit is gidse wat ontwerp is vir jou app-gebruikers, wat **aanmeld- en registrasiefunksies** bied.
2. **Identiteitspoele**: Hierdie poele is instrumenteel in **die autorisering van gebruikers om toegang tot verskillende AWS-dienste te verkry**. Hulle is nie direk betrokke by die aanmeld- of registrasieproses nie, maar is van kardinale belang vir hulpbron toegang na authentisering.
### **User pools**
### **Gebruikerspoele**
To learn what is a **Cognito User Pool check**:
Om te leer wat 'n **Cognito Gebruikerspoel kontroleer**:
{{#ref}}
cognito-user-pools.md
{{#endref}}
### **Identity pools**
### **Identiteitspoele**
The learn what is a **Cognito Identity Pool check**:
Om te leer wat 'n **Cognito Identiteitspoel kontroleer**:
{{#ref}}
cognito-identity-pools.md
{{#endref}}
## Enumeration
## Enumerasie
```bash
# List Identity Pools
aws cognito-identity list-identity-pools --max-results 60
@@ -72,14 +71,13 @@ aws cognito-idp get-user-pool-mfa-config --user-pool-id <user-pool-id>
## Get risk configuration
aws cognito-idp describe-risk-configuration --user-pool-id <user-pool-id>
```
### Identiteit Pools - Ongeauthentiseerde Enumerasie
### Identity Pools - Unauthenticated Enumeration
Net **om die Identiteit Pool ID** te weet, mag jy in staat wees om **akkrediteer te verkry van die rol wat aan ongeauthentiseerde** gebruikers gekoppel is (indien enige). [**Kyk hoe hier**](cognito-identity-pools.md#accessing-iam-roles).
Just **knowing the Identity Pool ID** you might be able **get credentials of the role associated to unauthenticated** users (if any). [**Check how here**](cognito-identity-pools.md#accessing-iam-roles).
### Gebruiker Pools - Ongeauthentiseerde Enumerasie
### User Pools - Unauthenticated Enumeration
Even if you **don't know a valid username** inside Cognito, you might be able to **enumerate** valid **usernames**, **BF** the **passwords** of even **register a new user** just **knowing the App client ID** (which is usually found in source code). [**Check how here**](cognito-user-pools.md#registration)**.**
Selfs as jy **nie 'n geldige gebruikersnaam** binne Cognito weet nie, mag jy in staat wees om **te enumereer** geldige **gebruikersname**, **BF** die **wagwoorde** of selfs **'n nuwe gebruiker te registreer** net **om die App kliënt ID** te weet (wat gewoonlik in die bronkode gevind word). [**Kyk hoe hier**](cognito-user-pools.md#registration)**.**
## Privesc
@@ -87,20 +85,16 @@ Even if you **don't know a valid username** inside Cognito, you might be able to
../../aws-privilege-escalation/aws-cognito-privesc.md
{{#endref}}
## Unauthenticated Access
## Ongeauthentiseerde Toegang
{{#ref}}
../../aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md
{{#endref}}
## Persistence
## Volharding
{{#ref}}
../../aws-persistence/aws-cognito-persistence.md
{{#endref}}
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -4,14 +4,13 @@
## Basic Information
Identity pools serve a crucial role by enabling your users to **acquire temporary credentials**. These credentials are essential for accessing various AWS services, including but not limited to Amazon S3 and DynamoDB. A notable feature of identity pools is their support for both anonymous guest users and a range of identity providers for user authentication. The supported identity providers include:
- Amazon Cognito user pools
- Social sign-in options such as Facebook, Google, Login with Amazon, and Sign in with Apple
- Providers compliant with OpenID Connect (OIDC)
- SAML (Security Assertion Markup Language) identity providers
- Developer authenticated identities
Identiteitspoele speel 'n belangrike rol deur jou gebruikers in staat te stel om **tydelike geloofsbriewe** te **verkry**. Hierdie geloofsbriewe is noodsaaklik vir toegang tot verskeie AWS-dienste, insluitend maar nie beperk tot Amazon S3 en DynamoDB nie. 'n Opmerkelijke kenmerk van identiteitspoele is hul ondersteuning vir beide anonieme gasgebruikers en 'n verskeidenheid identiteitsverskaffers vir gebruikersverifikasie. Die ondersteunde identiteitsverskaffers sluit in:
- Amazon Cognito gebruikerspoele
- Sosiale aanmeldopsies soos Facebook, Google, Aanmeld met Amazon, en Meld aan met Apple
- Verskaffers wat voldoen aan OpenID Connect (OIDC)
- SAML (Security Assertion Markup Language) identiteitsverskaffers
- Ontwikkelaar geverifieerde identiteite
```python
# Sample code to demonstrate how to integrate an identity provider with an identity pool can be structured as follows:
import boto3
@@ -24,74 +23,64 @@ identity_pool_id = 'your-identity-pool-id'
# Add an identity provider to the identity pool
response = client.set_identity_pool_roles(
IdentityPoolId=identity_pool_id,
Roles={
'authenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/AuthenticatedRole',
'unauthenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/UnauthenticatedRole',
}
IdentityPoolId=identity_pool_id,
Roles={
'authenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/AuthenticatedRole',
'unauthenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/UnauthenticatedRole',
}
)
# Print the response from AWS
print(response)
```
### Cognito Sync
To generate Identity Pool sessions, you first need to **generate and Identity ID**. This Identity ID is the **identification of the session of that user**. These identifications can have up to 20 datasets that can store up to 1MB of key-value pairs.
Om Identiteit Pool sessies te genereer, moet jy eers **'n Identiteit ID genereer**. Hierdie Identiteit ID is die **identifikasie van die sessie van daardie gebruiker**. Hierdie identifikasies kan tot 20 datasets hê wat tot 1MB van sleutel-waarde pare kan stoor.
This is **useful to keep information of a user** (who will be always using the same Identity ID).
Dit is **nuttig om inligting van 'n gebruiker te hou** (wat altyd dieselfde Identiteit ID sal gebruik).
Moreover, the service **cognito-sync** is the service that allow to **manage and syncronize this information** (in the datasets, sending info in streams and SNSs msgs...).
Boonop is die diens **cognito-sync** die diens wat toelaat om **hierdie inligting te bestuur en te sinkroniseer** (in die datasets, inligting in strome en SNS boodskappe te stuur...).
### Tools for pentesting
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc.
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), die AWS eksploitering raamwerk, sluit nou die "cognito\_\_enum" en "cognito\_\_attack" modules in wat die enumerasie van alle Cognito bates in 'n rekening outomatiseer en swak konfigurasies, gebruikersattributen wat vir toegangbeheer gebruik word, ens., merk, en outomatiseer ook gebruikersskepping (insluitend MFA-ondersteuning) en privilige-eskalasie gebaseer op aanpasbare pasattributen, bruikbare identiteits pool akkrediteer, aanneembare rolle in id tokens, ens.
For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page.
Vir 'n beskrywing van die modules se funksies, sien deel 2 van die [blog pos](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Vir installasie instruksies, sien die hoof [Pacu](https://github.com/RhinoSecurityLabs/pacu) bladsy.
#### Usage
Sample cognito\_\_attack usage to attempt user creation and all privesc vectors against a given identity pool and user pool client:
Voorbeeld van cognito\_\_attack gebruik om te probeer om 'n gebruiker te skep en alle privesc vektore teen 'n gegewe identiteits pool en gebruikerspool kliënt:
```bash
Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools
us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients
59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX
```
Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account:
Voorbeeld cognito\_\_enum gebruik om al die gebruikerspoele, gebruikerspoel kliënte, identiteitspoele, gebruikers, ens. wat sigbaar is in die huidige AWS-rekening, te versamel:
```bash
Pacu (new:test) > run cognito__enum
```
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is 'n CLI-gereedskap in python wat verskillende aanvalle op Cognito implementeer, insluitend ongewenste rekening skep en identiteitspoel eskalasie.
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and identity pool escalation.
#### Installation
#### Installasie
```bash
$ pip install cognito-scanner
```
#### Usage
#### Gebruik
```bash
$ cognito-scanner --help
```
For more information check https://github.com/padok-team/cognito-scanner
## Accessing IAM Roles
## Toegang tot IAM Rolle
### Unauthenticated
### Ongeoutentiseerde
The only thing an attacker need to know to **get AWS credentials** in a Cognito app as unauthenticated user is the **Identity Pool ID**, and this **ID must be hardcoded** in the web/mobile **application** for it to use it. An ID looks like this: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (it's not bruteforceable).
Die enigste ding wat 'n aanvaller moet weet om **AWS kredensiale** in 'n Cognito-toepassing as 'n ongeoutentiseerde gebruiker te **kry**, is die **Identiteit Pool ID**, en hierdie **ID moet hardgecodeer** wees in die web/mobiele **toepassing** sodat dit dit kan gebruik. 'n ID lyk soos volg: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (dit is nie bruteforceerbaar nie).
> [!TIP]
> The **IAM Cognito unathenticated role created via is called** by default `Cognito_<Identity Pool name>Unauth_Role`
If you find an Identity Pools ID hardcoded and it allows unauthenticated users, you can get AWS credentials with:
> Die **IAM Cognito ongeoutentiseerde rol wat via geskep is, word** standaard `Cognito_<Identiteit Pool naam>Unauth_Role` genoem.
As jy 'n Identiteit Pools ID hardgecodeer vind en dit ongeoutentiseerde gebruikers toelaat, kan jy AWS kredensiale kry met:
```python
import requests
@@ -105,8 +94,8 @@ r = requests.post(url, json=params, headers=headers)
json_resp = r.json()
if not "IdentityId" in json_resp:
print(f"Not valid id: {id_pool_id}")
exit
print(f"Not valid id: {id_pool_id}")
exit
IdentityId = r.json()["IdentityId"]
@@ -117,23 +106,19 @@ r = requests.post(url, json=params, headers=headers)
print(r.json())
```
Or you could use the following **aws cli commands**:
Of jy kan die volgende **aws cli commands** gebruik:
```bash
aws cognito-identity get-id --identity-pool-id <identity_pool_id> --no-sign
aws cognito-identity get-credentials-for-identity --identity-id <identity_id> --no-sign
```
> [!WARNING]
> Note that by default an unauthenticated cognito **user CANNOT have any permission, even if it was assigned via a policy**. Check the followin section.
> Let daarop dat 'n nie-geverifieerde cognito **gebruiker GEEN toestemming kan hê nie, selfs al is dit via 'n beleid toegeken**. Kontroleer die volgende afdeling.
### Enhanced vs Basic Authentication flow
### Verbeterde vs Basiese Verifikasievloei
The previous section followed the **default enhanced authentication flow**. This flow sets a **restrictive** [**session policy**](../../aws-basic-information/#session-policies) to the IAM role session generated. This policy will only allow the session to [**use the services from this list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (even if the role had access to other services).
However, there is a way to bypass this, if the **Identity pool has "Basic (Classic) Flow" enabled**, the user will be able to obtain a session using that flow which **won't have that restrictive session policy**.
Die vorige afdeling het die **standaard verbeterde verifikasievloei** gevolg. Hierdie vloei stel 'n **beperkende** [**sessiebeleid**](../../aws-basic-information/#session-policies) in vir die IAM rol sessie wat gegenereer is. Hierdie beleid sal slegs toelaat dat die sessie [**die dienste van hierdie lys gebruik**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (selfs al het die rol toegang tot ander dienste).
Daar is egter 'n manier om dit te omseil; as die **Identiteitspoel "Basiese (Klassieke) Vloei" geaktiveer het**, sal die gebruiker in staat wees om 'n sessie te verkry met behulp van daardie vloei wat **nie daardie beperkende sessiebeleid sal hê nie**.
```bash
# Get auth ID
aws cognito-identity get-id --identity-pool-id <identity_pool_id> --no-sign
@@ -145,51 +130,46 @@ aws cognito-identity get-open-id-token --identity-id <identity_id> --no-sign
## If you don't know the role_arn use the previous enhanced flow to get it
aws sts assume-role-with-web-identity --role-arn "arn:aws:iam::<acc_id>:role/<role_name>" --role-session-name sessionname --web-identity-token <token> --no-sign
```
> [!WARNING]
> If you receive this **error**, it's because the **basic flow is not enabled (default)**
> As jy hierdie **fout** ontvang, is dit omdat die **basiese vloei nie geaktiveer is nie (standaard)**
> `An error occurred (InvalidParameterException) when calling the GetOpenIdToken operation: Basic (classic) flow is not enabled, please use enhanced flow.`
Having a set of IAM credentials you should check [which access you have](../../#whoami) and try to [escalate privileges](../../aws-privilege-escalation/).
As jy 'n stel IAM-akkrediteerings het, moet jy [kontroleer watter toegang jy het](../../#whoami) en probeer om [privileges te verhoog](../../aws-privilege-escalation/).
### Authenticated
### Geverifieer
> [!NOTE]
> Remember that **authenticated users** will be probably granted **different permissions**, so if you can **sign up inside the app**, try doing that and get the new credentials.
> Onthou dat **geverifieerde gebruikers** waarskynlik **verskillende toestemmings** toegeken sal word, so as jy kan **aanmeld binne die app**, probeer dit en kry die nuwe akkrediteerings.
There could also be **roles** available for **authenticated users accessing the Identity Poo**l.
Daar kan ook **rolle** beskikbaar wees vir **geverifieerde gebruikers wat toegang tot die Identiteitspoel** het.
For this you might need to have access to the **identity provider**. If that is a **Cognito User Pool**, maybe you can abuse the default behaviour and **create a new user yourself**.
Hiervoor mag jy toegang tot die **identiteitsverskaffer** nodig hê. As dit 'n **Cognito-gebruikerspoel** is, kan jy dalk die standaardgedrag misbruik en **self 'n nuwe gebruiker skep**.
> [!TIP]
> The **IAM Cognito athenticated role created via is called** by default `Cognito_<Identity Pool name>Auth_Role`
> Die **IAM Cognito geverifieerde rol wat via geskep is, word standaard** `Cognito_<Identiteitspoel naam>Auth_Role` genoem.
Anyway, the **following example** expects that you have already logged in inside a **Cognito User Pool** used to access the Identity Pool (don't forget that other types of identity providers could also be configured).
In elk geval, die **volgende voorbeeld** verwag dat jy reeds binne 'n **Cognito-gebruikerspoel** aangemeld het wat gebruik word om toegang tot die Identiteitspoel te verkry (moet nie vergeet dat ander tipes identiteitsverskaffers ook gekonfigureer kan word nie).
<pre class="language-bash"><code class="lang-bash">aws cognito-identity get-id \
--identity-pool-id &#x3C;identity_pool_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
--identity-pool-id &#x3C;identity_pool_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
# Get the identity_id from the previous commnad response
# Kry die identity_id van die vorige opdrag se antwoord
aws cognito-identity get-credentials-for-identity \
--identity-id &#x3C;identity_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
--identity-id &#x3C;identity_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
# In the IdToken you can find roles a user has access because of User Pool Groups
# User the --custom-role-arn to get credentials to a specific role
# In die IdToken kan jy rolle vind waartoe 'n gebruiker toegang het as gevolg van Gebruikerspoel Groepe
# Gebruik die --custom-role-arn om akkrediteerings vir 'n spesifieke rol te kry
aws cognito-identity get-credentials-for-identity \
--identity-id &#x3C;identity_id> \
--identity-id &#x3C;identity_id> \
<strong> --custom-role-arn &#x3C;role_arn> \
</strong> --logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
</code></pre>
> [!WARNING]
> It's possible to **configure different IAM roles depending on the identity provide**r the user is being logged in or even just depending **on the user** (using claims). Therefore, if you have access to different users through the same or different providers, if might be **worth it to login and access the IAM roles of all of them**.
> Dit is moontlik om **verskillende IAM rolle te konfigureer afhangende van die identiteitsverskaffer** waar die gebruiker aangemeld is of selfs net afhangende **van die gebruiker** (met behulp van aansprake). Daarom, as jy toegang tot verskillende gebruikers het deur dieselfde of verskillende verskaffers, kan dit **die moeite werd wees om aan te meld en toegang te verkry tot die IAM rolle van al hulle**.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -2,32 +2,31 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Basic Information
## Basiese Inligting
A user pool is a user directory in Amazon Cognito. With a user pool, your users can **sign in to your web or mobile app** through Amazon Cognito, **or federate** through a **third-party** identity provider (IdP). Whether your users sign in directly or through a third party, all members of the user pool have a directory profile that you can access through an SDK.
'n Gebruikerspoel is 'n gebruikersgids in Amazon Cognito. Met 'n gebruikerspoel kan jou gebruikers **aanmeld by jou web- of mobiele toepassing** deur Amazon Cognito, **of federate** deur 'n **derdeparty** identiteitsverskaffer (IdP). Of jou gebruikers nou direk of deur 'n derdeparty aanmeld, alle lede van die gebruikerspoel het 'n gidsprofiel wat jy deur 'n SDK kan toegang.
User pools provide:
Gebruikerspoele bied:
- Sign-up and sign-in services.
- A built-in, customizable web UI to sign in users.
- Social sign-in with Facebook, Google, Login with Amazon, and Sign in with Apple, and through SAML and OIDC identity providers from your user pool.
- User directory management and user profiles.
- Security features such as multi-factor authentication (MFA), checks for compromised credentials, account takeover protection, and phone and email verification.
- Customized workflows and user migration through AWS Lambda triggers.
- Registrasie- en aanmelddienste.
- 'n Ingeboude, aanpasbare web UI om gebruikers aan te meld.
- Sosiale aanmelding met Facebook, Google, Login with Amazon, en Sign in with Apple, en deur SAML en OIDC identiteitsverskaffers van jou gebruikerspoel.
- Gebruikersgidsbestuur en gebruikersprofiele.
- Sekuriteitskenmerke soos multi-faktor verifikasie (MFA), kontrole vir gecompromitteerde geloofsbriewe, rekening oorname beskerming, en telefoon- en e-posverifikasie.
- Aangepaste werksvloeie en gebruikersmigrasie deur AWS Lambda triggers.
**Source code** of applications will usually also contain the **user pool ID** and the **client application ID**, (and some times the **application secret**?) which are needed for a **user to login** to a Cognito User Pool.
**Bronkode** van toepassings sal gewoonlik ook die **gebruikerspoel ID** en die **klienttoepassing ID** bevat, (en soms die **toepassing geheim**?) wat nodig is vir 'n **gebruiker om aan te meld** by 'n Cognito Gebruikerspoel.
### Potential attacks
### Potensiële aanvalle
- **Registration**: By default a user can register himself, so he could create a user for himself.
- **User enumeration**: The registration functionality can be used to find usernames that already exists. This information can be useful for the brute-force attack.
- **Login brute-force**: In the [**Authentication**](cognito-user-pools.md#authentication) section you have all the **methods** that a user have to **login**, you could try to brute-force them **find valid credentials**.
- **Registrasie**: Standaard kan 'n gebruiker homself registreer, so hy kan 'n gebruiker vir homself skep.
- **Gebruikersenumerasie**: Die registrasiefunksionaliteit kan gebruik word om gebruikersname te vind wat reeds bestaan. Hierdie inligting kan nuttig wees vir die brute-force aanval.
- **Aanmeld brute-force**: In die [**Verifikasie**](cognito-user-pools.md#authentication) afdeling het jy al die **metodes** wat 'n gebruiker het om te **aanmeld**, jy kan probeer om hulle te brute-force **geldige geloofsbriewe te vind**.
### Tools for pentesting
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), now includes the `cognito__enum` and `cognito__attack` modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc.\
For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page.
### Gereedskap vir pentesting
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), sluit nou die `cognito__enum` en `cognito__attack` modules in wat die enumerasie van alle Cognito bates in 'n rekening outomatiseer en swak konfigurasies, gebruikersattribuut wat vir toegangbeheer gebruik word, ens., merk, en outomatiseer ook gebruikersskepping (insluitend MFA-ondersteuning) en voorregverhoging gebaseer op aanpasbare aangepaste attribuut, bruikbare identiteitspoel geloofsbriewe, aanneembare rolle in id tokens, ens.\
Vir 'n beskrywing van die modules se funksies, sien deel 2 van die [blogpos](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Vir installasie-instruksies, sien die hoof [Pacu](https://github.com/RhinoSecurityLabs/pacu) bladsy.
```bash
# Run cognito__enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account
Pacu (new:test) > run cognito__enum
@@ -37,201 +36,169 @@ Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gma
us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients
59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX
```
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and account oracle. Check [this link](https://github.com/padok-team/cognito-scanner) for more info.
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is 'n CLI-gereedskap in python wat verskillende aanvalle op Cognito implementeer, insluitend ongewenste rekening skep en rekening oracle. Kyk na [hierdie skakel](https://github.com/padok-team/cognito-scanner) vir meer inligting.
```bash
# Install
pip install cognito-scanner
# Run
cognito-scanner --help
```
- [CognitoAttributeEnum](https://github.com/punishell/CognitoAttributeEnum): This script allows to enumerate valid attributes for users.
- [CognitoAttributeEnum](https://github.com/punishell/CognitoAttributeEnum): Hierdie skrip maak dit moontlik om geldige eienskappe vir gebruikers te enumereer.
```bash
python cognito-attribute-enu.py -client_id 16f1g98bfuj9i0g3f8be36kkrl
```
## Registrasie
## Registration
User Pools allows by **default** to **register new users**.
User Pools laat **per standaard** toe om **nuwe gebruikers te registreer**.
```bash
aws cognito-idp sign-up --client-id <client-id> \
--username <username> --password <password> \
--region <region> --no-sign-request
--username <username> --password <password> \
--region <region> --no-sign-request
```
#### As iemand kan registreer
#### If anyone can register
You might find an error indicating you that you need to **provide more details** of abut the user:
Jy mag 'n fout vind wat aandui dat jy **meer besonderhede** oor die gebruiker moet verskaf:
```
An error occurred (InvalidParameterException) when calling the SignUp operation: Attributes did not conform to the schema: address: The attribute is required
```
You can provide the needed details with a JSON such as:
U kan die nodige besonderhede met 'n JSON soos:
```json
--user-attributes '[{"Name": "email", "Value": "carlospolop@gmail.com"}, {"Name":"gender", "Value": "M"}, {"Name": "address", "Value": "street"}, {"Name": "custom:custom_name", "Value":"supername&\"*$"}]'
```
You could use this functionality also to **enumerate existing users.** This is the error message when a user already exists with that name:
U kan hierdie funksionaliteit ook gebruik om **bestaande gebruikers te enumereer.** Dit is die foutboodskap wanneer 'n gebruiker reeds met daardie naam bestaan:
```
An error occurred (UsernameExistsException) when calling the SignUp operation: User already exists
```
> [!NOTE]
> Note in the previous command how the **custom attributes start with "custom:"**.\
> Also know that when registering you **cannot create for the user new custom attributes**. You can only give value to **default attributes** (even if they aren't required) and **custom attributes specified**.
Or just to test if a client id exists. This is the error if the client-id doesn't exist:
> Let op in die vorige opdrag hoe die **aangepaste eienskappe begin met "custom:"**.\
> Weet ook dat wanneer jy registreer jy **nie nuwe aangepaste eienskappe vir die gebruiker kan skep nie**. Jy kan net waarde gee aan **standaard eienskappe** (selfs al is hulle nie vereis nie) en **aangepaste eienskappe wat gespesifiseer is**.
Of net om te toets of 'n kliënt-id bestaan. Dit is die fout as die kliënt-id nie bestaan nie:
```
An error occurred (ResourceNotFoundException) when calling the SignUp operation: User pool client 3ig612gjm56p1ljls1prq2miut does not exist.
```
#### As slegs admin gebruikers kan registreer
#### If only admin can register users
You will find this error and you own't be able to register or enumerate users:
Jy sal hierdie fout vind en jy sal nie in staat wees om gebruikers te registreer of te enumereer nie:
```
An error occurred (NotAuthorizedException) when calling the SignUp operation: SignUp is not permitted for this user pool
```
### Verifying Registration
Cognito allows to **verify a new user by verifying his email or phone number**. Therefore, when creating a user usually you will be required at least the username and password and the **email and/or telephone number**. Just set one **you control** so you will receive the code to **verify your** newly created user **account** like this:
Cognito laat toe om **'n nuwe gebruiker te verifieer deur sy e-pos of telefoonnommer te verifieer**. Daarom, wanneer jy 'n gebruiker skep, sal jy gewoonlik ten minste die gebruikersnaam en wagwoord en die **e-pos en/of telefoonnommer** benodig. Stel net een **wat jy beheer** sodat jy die kode sal ontvang om **jou** nuut geskepte gebruiker **rekening** te verifieer soos volg:
```bash
aws cognito-idp confirm-sign-up --client-id <cliet_id> \
--username aasdasd2 --confirmation-code <conf_code> \
--no-sign-request --region us-east-1
--username aasdasd2 --confirmation-code <conf_code> \
--no-sign-request --region us-east-1
```
> [!WARNING]
> Even if **looks like you can use the same email** and phone number, when you need to verify the created user Cognito will complain about using the same info and **won't let you verify the account**.
> Selfs al **lyk dit of jy dieselfde e-pos** en telefoonnommer kan gebruik, wanneer jy die geskepte gebruiker moet verifieer, sal Cognito kla oor die gebruik van dieselfde inligting en **sal nie toelaat dat jy die rekening verifieer** nie.
### Privilege Escalation / Updating Attributes
By default a user can **modify the value of his attributes** with something like:
Standaard kan 'n gebruiker **die waarde van sy eienskappe verander** met iets soos:
```bash
aws cognito-idp update-user-attributes \
--region us-east-1 --no-sign-request \
--user-attributes Name=address,Value=street \
--access-token <access token>
--region us-east-1 --no-sign-request \
--user-attributes Name=address,Value=street \
--access-token <access token>
```
#### Custom attribute privesc
#### Aangepaste attribuut privesc
> [!CAUTION]
> You might find **custom attributes** being used (such as `isAdmin`), as by default you can **change the values of your own attributes** you might be able to **escalate privileges** changing the value yourself!
> Jy mag **aangepaste attribuute** vind wat gebruik word (soos `isAdmin`), aangesien jy standaard **die waardes van jou eie attribuute kan verander** kan jy dalk **privileges eskaleer** deur die waarde self te verander!
#### Email/username modification privesc
#### E-pos/gebruikersnaam wysiging privesc
You can use this to **modify the email and phone number** of a user, but then, even if the account remains as verified, those attributes are **set in unverified status** (you need to verify them again).
Jy kan dit gebruik om **die e-pos en telefoonnommer** van 'n gebruiker te **wysig**, maar dan, selfs al bly die rekening as geverifieer, is daardie attribuute **in 'n ongeverifieerde status** (jy moet hulle weer verifieer).
> [!WARNING]
> You **won't be able to login with email or phone number** until you verify them, but you will be **able to login with the username**.\
> Note that even if the email was modified and not verified it will appear in the ID Token inside the **`email`** **field** and the filed **`email_verified`** will be **false**, but if the app **isn't checking that you might impersonate other users**.
> Jy **sal nie in staat wees om in te log met e-pos of telefoonnommer** totdat jy hulle verifieer nie, maar jy sal **in staat wees om in te log met die gebruikersnaam**.\
> Let daarop dat selfs al is die e-pos gewysig en nie geverifieer nie, dit sal verskyn in die ID Token binne die **`email`** **veld** en die veld **`email_verified`** sal **vals** wees, maar as die app **nie nagaan nie, kan jy ander gebruikers naboots**.
> Moreover, note that you can put anything inside the **`name`** field just modifying the **name attribute**. If an app is **checking** **that** field for some reason **instead of the `email`** (or any other attribute) you might be able to **impersonate other users**.
Anyway, if for some reason you changed your email for example to a new one you can access you can **confirm the email with the code you received in that email address**:
> Boonop, let daarop dat jy enigiets in die **`name`** veld kan plaas deur net die **naam attribuut** te wysig. As 'n app **nagaan** **daardie** veld om een of ander rede **in plaas van die `email`** (of enige ander attribuut) kan jy dalk **ander gebruikers naboots**.
In elk geval, as jy om een of ander rede jou e-pos verander het, byvoorbeeld na 'n nuwe een wat jy kan toegang, kan jy **die e-pos bevestig met die kode wat jy in daardie e-posadres ontvang het**:
```bash
aws cognito-idp verify-user-attribute \
--access-token <access_token> \
--attribute-name email --code <code> \
--region <region> --no-sign-request
--access-token <access_token> \
--attribute-name email --code <code> \
--region <region> --no-sign-request
```
Use **`phone_number`** instead of **`email`** to change/verify a **new phone number**.
Gebruik **`phone_number`** in plaas van **`email`** om 'n **nuwe telefoonnommer** te verander/te verifieer.
> [!NOTE]
> The admin could also enable the option to **login with a user preferred username**. Note that you won't be able to change this value to **any username or preferred_username already being used** to impersonate a different user.
> Die admin kan ook die opsie aktiver om **in te log met 'n gebruiker se verkose gebruikersnaam**. Let daarop dat jy nie hierdie waarde kan verander na **enige gebruikersnaam of verkose_gebruikersnaam wat reeds gebruik word** om 'n ander gebruiker na te doen nie.
### Recover/Change Password
It's possible to recover a password just **knowing the username** (or email or phone is accepted) and having access to it as a code will be sent there:
### Herstel/Verander Wagwoord
Dit is moontlik om 'n wagwoord te herstel net deur **die gebruikersnaam** te ken (of e-pos of telefoon word aanvaar) en toegang daartoe te hê, aangesien 'n kode daar gestuur sal word:
```bash
aws cognito-idp forgot-password \
--client-id <client_id> \
--username <username/email/phone> --region <region>
--client-id <client_id> \
--username <username/email/phone> --region <region>
```
> [!NOTE]
> The response of the server is always going to be positive, like if the username existed. You cannot use this method to enumerate users
With the code you can change the password with:
> Die antwoord van die bediener gaan altyd positief wees, soos as die gebruikersnaam bestaan. Jy kan nie hierdie metode gebruik om gebruikers te enumereer nie.
Met die kode kan jy die wagwoord verander met:
```bash
aws cognito-idp confirm-forgot-password \
--client-id <client_id> \
--username <username> \
--confirmation-code <conf_code> \
--password <pwd> --region <region>
--client-id <client_id> \
--username <username> \
--confirmation-code <conf_code> \
--password <pwd> --region <region>
```
To change the password you need to **know the previous password**:
Om die wagwoord te verander, moet jy **die vorige wagwoord weet**:
```bash
aws cognito-idp change-password \
--previous-password <value> \
--proposed-password <value> \
--access-token <value>
--previous-password <value> \
--proposed-password <value> \
--access-token <value>
```
## Authentisering
## Authentication
'n Gebruikerspoel ondersteun **verskillende maniere om te autentiseer**. As jy 'n **gebruikersnaam en wagwoord** het, is daar ook **verskillende metodes** wat ondersteun word om aan te meld.\
Boonop, wanneer 'n gebruiker in die Poel **3 tipes tokens gegee word**: Die **ID Token**, die **Toegangstoken** en die **Herlaa token**.
A user pool supports **different ways to authenticate** to it. If you have a **username and password** there are also **different methods** supported to login.\
Moreover, when a user is authenticated in the Pool **3 types of tokens are given**: The **ID Token**, the **Access token** and the **Refresh token**.
- [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): It contains claims about the **identity of the authenticated user,** such as `name`, `email`, and `phone_number`. The ID token can also be used to **authenticate users to your resource servers or server applications**. You must **verify** the **signature** of the ID token before you can trust any claims inside the ID token if you use it in external applications.
- The ID Token is the token that **contains the attributes values of the user**, even the custom ones.
- [**Access Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): It contains claims about the authenticated user, a list of the **user's groups, and a list of scopes**. The purpose of the access token is to **authorize API operations** in the context of the user in the user pool. For example, you can use the access token to **grant your user access** to add, change, or delete user attributes.
- [**Refresh Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): With refresh tokens you can **get new ID Tokens and Access Tokens** for the user until the **refresh token is invalid**. By **default**, the refresh token **expires 30 days after** your application user signs into your user pool. When you create an application for your user pool, you can set the application's refresh token expiration to **any value between 60 minutes and 10 years**.
- [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): Dit bevat aansprake oor die **identiteit van die geverifieerde gebruiker**, soos `name`, `email`, en `phone_number`. Die ID token kan ook gebruik word om **gebruikers te autentiseer op jou hulpbronne bedieners of bediener toepassings**. Jy moet die **handtekening** van die ID token **verifieer** voordat jy enige aansprake binne die ID token kan vertrou as jy dit in eksterne toepassings gebruik.
- Die ID Token is die token wat **die attribuutwaardes van die gebruiker bevat**, selfs die pasgemaakte.
- [**Toegangstoken**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): Dit bevat aansprake oor die geverifieerde gebruiker, 'n lys van die **gebruiker se groepe, en 'n lys van skope**. Die doel van die toegangstoken is om **API operasies te autoriseer** in die konteks van die gebruiker in die gebruikerspoel. Byvoorbeeld, jy kan die toegangstoken gebruik om **jou gebruiker toegang te gee** om gebruikersattribuut te voeg, te verander of te verwyder.
- [**Herlaa token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): Met herlaa tokens kan jy **nuwe ID Tokens en Toegangstokens kry** vir die gebruiker totdat die **herlaa token ongeldig is**. Deur **standaard** verval die herlaa token **30 dae nadat** jou toepassingsgebruiker in jou gebruikerspoel aanmeld. Wanneer jy 'n toepassing vir jou gebruikerspoel skep, kan jy die herlaa token vervaldatum van die toepassing stel op **enige waarde tussen 60 minute en 10 jaar**.
### ADMIN_NO_SRP_AUTH & ADMIN_USER_PASSWORD_AUTH
This is the server side authentication flow:
Dit is die bediener kant autentisering vloei:
- The server-side app calls the **`AdminInitiateAuth` API operation** (instead of `InitiateAuth`). This operation requires AWS credentials with permissions that include **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`**. The operation returns the required authentication parameters.
- After the server-side app has the **authentication parameters**, it calls the **`AdminRespondToAuthChallenge` API operation**. The `AdminRespondToAuthChallenge` API operation only succeeds when you provide AWS credentials.
- Die bediener-kant toepassing roep die **`AdminInitiateAuth` API operasie** aan (in plaas van `InitiateAuth`). Hierdie operasie vereis AWS geloofsbriewe met toestemmings wat **`cognito-idp:AdminInitiateAuth`** en **`cognito-idp:AdminRespondToAuthChallenge`** insluit. Die operasie gee die vereiste autentisering parameters terug.
- Nadat die bediener-kant toepassing die **autentisering parameters** het, roep dit die **`AdminRespondToAuthChallenge` API operasie** aan. Die `AdminRespondToAuthChallenge` API operasie slaag slegs wanneer jy AWS geloofsbriewe verskaf.
This **method is NOT enabled** by default.
Hierdie **metode is NIE geaktiveer** deur standaard nie.
To **login** you **need** to know:
Om te **meld aan** moet jy **weet**:
- user pool id
- client id
- username
- password
- client secret (only if the app is configured to use a secret)
- gebruikerspoel id
- kliënt id
- gebruikersnaam
- wagwoord
- kliënt geheim (slegs as die toepassing geconfigureer is om 'n geheim te gebruik)
> [!NOTE]
> In order to be **able to login with this method** that application must allow to login with `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\
> Moreover, to perform this action you need credentials with the permissions **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`**
> Ten einde **in staat te wees om met hierdie metode aan te meld** moet daardie toepassing toelaat om aan te meld met `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\
> Boonop, om hierdie aksie uit te voer, het jy geloofsbriewe met die toestemmings **`cognito-idp:AdminInitiateAuth`** en **`cognito-idp:AdminRespondToAuthChallenge`** nodig.
```python
aws cognito-idp admin-initiate-auth \
--client-id <client-id> \
--auth-flow ADMIN_USER_PASSWORD_AUTH \
--region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
--user-pool-id "<pool-id>"
--client-id <client-id> \
--auth-flow ADMIN_USER_PASSWORD_AUTH \
--region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
--user-pool-id "<pool-id>"
# Check the python code to learn how to generate the hsecret_hash
```
<details>
<summary>Code to Login</summary>
<summary>Kode om in te log</summary>
```python
import boto3
import botocore
@@ -249,61 +216,57 @@ password = "<pwd>"
boto_client = boto3.client('cognito-idp', region_name='us-east-1')
def get_secret_hash(username, client_id, client_secret):
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
# If the Client App isn't configured to use a secret
## just delete the line setting the SECRET_HASH
def login_user(username_or_alias, password, client_id, client_secret, user_pool_id):
try:
return boto_client.admin_initiate_auth(
UserPoolId=user_pool_id,
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
try:
return boto_client.admin_initiate_auth(
UserPoolId=user_pool_id,
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(login_user(username, password, client_id, client_secret, user_pool_id))
```
</details>
### USER_PASSWORD_AUTH
This method is another simple and **traditional user & password authentication** flow. It's recommended to **migrate a traditional** authentication method **to Cognito** and **recommended** to then **disable** it and **use** then **ALLOW_USER_SRP_AUTH** method instead (as that one never sends the password over the network).\
This **method is NOT enabled** by default.
Hierdie metode is 'n ander eenvoudige en **tradisionele gebruiker & wagwoord outentikasie** vloei. Dit word aanbeveel om **'n tradisionele** outentikasie metode **na Cognito** te **migreer** en **aanbeveel** om dit dan **te deaktiveer** en **in plaas daarvan** die **ALLOW_USER_SRP_AUTH** metode te **gebruik** (aangesien dit nooit die wagwoord oor die netwerk stuur).\
Hierdie **metode is NIE geaktiveer** nie as standaard.
The main **difference** with the **previous auth method** inside the code is that you **don't need to know the user pool ID** and that you **don't need extra permissions** in the Cognito User Pool.
Die hoof **verskil** met die **vorige outentikasie metode** binne die kode is dat jy **nie die gebruiker poel ID** hoef te weet nie en dat jy **nie ekstra toestemmings** in die Cognito Gebruiker Poel nodig het nie.
To **login** you **need** to know:
Om te **log in** moet jy **weet**:
- client id
- username
- password
- client secret (only if the app is configured to use a secret)
- kliënt id
- gebruikersnaam
- wagwoord
- kliënt geheim (slegs as die toepassing gekonfigureer is om 'n geheim te gebruik)
> [!NOTE]
> In order to be **able to login with this method** that application must allow to login with ALLOW_USER_PASSWORD_AUTH.
> Ten einde **in staat te wees om met hierdie metode in te log** moet daardie toepassing toelaat om in te log met ALLOW_USER_PASSWORD_AUTH.
```python
aws cognito-idp initiate-auth --client-id <client-id> \
--auth-flow USER_PASSWORD_AUTH --region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
--auth-flow USER_PASSWORD_AUTH --region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
# Check the python code to learn how to generate the secret_hash
```
<details>
<summary>Python code to Login</summary>
<summary>Python kode om aan te meld</summary>
```python
import boto3
import botocore
@@ -321,48 +284,46 @@ password = "<pwd>"
boto_client = boto3.client('cognito-idp', region_name='us-east-1')
def get_secret_hash(username, client_id, client_secret):
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
# If the Client App isn't configured to use a secret
## just delete the line setting the SECRET_HASH
def login_user(username_or_alias, password, client_id, client_secret, user_pool_id):
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(login_user(username, password, client_id, client_secret, user_pool_id))
```
</details>
### USER_SRP_AUTH
This is scenario is similar to the previous one but **instead of of sending the password** through the network to login a **challenge authentication is performed** (so no password navigating even encrypted through he net).\
This **method is enabled** by default.
Hierdie scenario is soortgelyk aan die vorige een, maar **in plaas daarvan om die wagwoord** deur die netwerk te stuur om aan te meld, word 'n **uitdaging-authentisering uitgevoer** (so geen wagwoord wat selfs versleuteld deur die netwerk beweeg nie).\
Hierdie **metode is standaard geaktiveer**.
To **login** you **need** to know:
Om te **meld aan** moet jy weet:
- user pool id
- client id
- username
- password
- client secret (only if the app is configured to use a secret)
- gebruikerspoel id
- kliënt id
- gebruikersnaam
- wagwoord
- kliënt geheim (slegs as die toepassing gekonfigureer is om 'n geheim te gebruik)
<details>
<summary>Code to login</summary>
<summary>Code om aan te meld</summary>
```python
from warrant.aws_srp import AWSSRP
import os
@@ -375,32 +336,28 @@ CLIENT_SECRET = 'secreeeeet'
os.environ["AWS_DEFAULT_REGION"] = "<region>"
aws = AWSSRP(username=USERNAME, password=PASSWORD, pool_id=POOL_ID,
client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
tokens = aws.authenticate_user()
id_token = tokens['AuthenticationResult']['IdToken']
refresh_token = tokens['AuthenticationResult']['RefreshToken']
access_token = tokens['AuthenticationResult']['AccessToken']
token_type = tokens['AuthenticationResult']['TokenType']
```
</details>
### REFRESH_TOKEN_AUTH & REFRESH_TOKEN
This **method is always going to be valid** (it cannot be disabled) but you need to have a valid refresh token.
Hierdie **metode gaan altyd geldig wees** (dit kan nie gedeaktiveer word nie) maar jy moet 'n geldige herlaai-token.
```bash
aws cognito-idp initiate-auth \
--client-id 3ig6h5gjm56p1ljls1prq2miut \
--auth-flow REFRESH_TOKEN_AUTH \
--region us-east-1 \
--auth-parameters 'REFRESH_TOKEN=<token>'
--client-id 3ig6h5gjm56p1ljls1prq2miut \
--auth-flow REFRESH_TOKEN_AUTH \
--region us-east-1 \
--auth-parameters 'REFRESH_TOKEN=<token>'
```
<details>
<summary>Code to refresh</summary>
<summary>Kode om te verfris</summary>
```python
import boto3
import botocore
@@ -414,83 +371,74 @@ token = '<token>'
boto_client = boto3.client('cognito-idp', region_name='<region>')
def refresh(client_id, refresh_token):
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token
}
)
except botocore.exceptions.ClientError as e:
return e.response
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(refresh(client_id, token))
```
</details>
### CUSTOM_AUTH
In this case the **authentication** is going to be performed through the **execution of a lambda function**.
In hierdie geval gaan die **verifikasie** deur die **uitvoering van 'n lambda-funksie** plaasvind.
## Extra Security
## Ekstra Sekuriteit
### Advanced Security
### Gevorderde Sekuriteit
By default it's disabled, but if enabled, Cognito could be able to **find account takeovers**. To minimise the probability you should login from a **network inside the same city, using the same user agent** (and IP is thats possible)**.**
Standaard is dit gedeaktiveer, maar as dit geaktiveer is, kan Cognito in staat wees om **rekening oorname** te **vind**. Om die waarskynlikheid te minimaliseer, moet jy aanmeld vanaf 'n **netwerk binne dieselfde stad, met dieselfde gebruikersagent** (en IP as dit moontlik is)**.**
### **MFA Remember device**
### **MFA Onthou toestel**
If the user logins from the same device, the MFA might be bypassed, therefore try to login from the same browser with the same metadata (IP?) to try to bypass the MFA protection.
As die gebruiker vanaf dieselfde toestel aanmeld, kan die MFA omseil word, probeer dus om vanaf dieselfde blaaiers met dieselfde metadata (IP?) aan te meld om die MFA-beskerming te probeer omseil.
## User Pool Groups IAM Roles
## Gebruiker Pool Groepe IAM Rolle
It's possible to add **users to User Pool** groups that are related to one **IAM roles**.\
Moreover, **users** can be assigned to **more than 1 group with different IAM roles** attached.
Dit is moontlik om **gebruikers aan Gebruiker Pool** groepe toe te voeg wat verband hou met een **IAM rol**.\
Boonop kan **gebruikers** aan **meer as 1 groep met verskillende IAM rolle** toegeken word.
Note that even if a group is inside a group with an IAM role attached, in order to be able to access IAM credentials of that group it's needed that the **User Pool is trusted by an Identity Pool** (and know the details of that Identity Pool).
Let daarop dat selfs al is 'n groep binne 'n groep met 'n IAM rol aangeheg, om toegang te verkry tot die IAM geloofsbriewe van daardie groep, is dit nodig dat die **Gebruiker Pool vertrou word deur 'n Identiteits Pool** (en die besonderhede van daardie Identiteits Pool ken).
Another requisite to get the **IAM role indicated in the IdToken** when a user is authenticated in the User Pool (`aws cognito-idp initiate-auth...`) is that the **Identity Provider Authentication provider** needs indicate that the **role must be selected from the token.**
Nog 'n vereiste om die **IAM rol aangedui in die IdToken** te verkry wanneer 'n gebruiker in die Gebruiker Pool geverifieer word (`aws cognito-idp initiate-auth...`), is dat die **Identiteits Verskaffer Verifikasie verskaffer** moet aandui dat die **rol uit die token gekies moet word.**
<figure><img src="../../../../images/image (250).png" alt=""><figcaption></figcaption></figure>
The **roles** a user have access to are **inside the `IdToken`**, and a user can **select which role he would like credentials for** with the **`--custom-role-arn`** from `aws cognito-identity get-credentials-for-identity`.\
However, if the **default option** is the one **configured** (`use default role`), and you try to access a role from the IdToken, you will get **error** (that's why the previous configuration is needed):
Die **rolle** waartoe 'n gebruiker toegang het, is **binne die `IdToken`**, en 'n gebruiker kan **kies watter rol hy graag geloofsbriewe vir** wil hê met die **`--custom-role-arn`** van `aws cognito-identity get-credentials-for-identity`.\
As die **standaard opsie** egter die een is wat **gekonfigureer** is (`use default role`), en jy probeer om toegang te verkry tot 'n rol vanaf die IdToken, sal jy **fout** kry (dit is waarom die vorige konfigurasie nodig is):
```
An error occurred (InvalidParameterException) when calling the GetCredentialsForIdentity operation: Only SAML providers and providers with RoleMappings support custom role ARN.
```
> [!WARNING]
> Note that the role assigned to a **User Pool Group** needs to be **accesible by the Identity Provider** that **trust the User Pool** (as the IAM role **session credentials are going to be obtained from it**).
> Let daarop dat die rol wat aan 'n **User Pool Group** toegeken is, **toeganklik moet wees deur die Identiteitsverskaffer** wat **die User Pool vertrou** (aangesien die IAM-rol **sessie-inligting daaruit verkry gaan word**).
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:2361092e-9db6-a876-1027-10387c9de439"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "authenticated"
}
}
}
]
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:2361092e-9db6-a876-1027-10387c9de439"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "authenticated"
}
}
}
]
}js
```
{{#include ../../../../banners/hacktricks-training.md}}