# AWS - Secrets Manager Persistence

{{#include ../../../banners/hacktricks-training.md}}

## Secrets Manager

For more info check:

{{#ref}}
../aws-services/aws-secrets-manager-enum.md
{{#endref}}

### Via Resource Policies

It's possible to **grant access to secrets to external accounts** via resource policies. Check the [**Secrets Manager Privesc page**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) for more information. Note that to **access a secret**, the external account will also **need access to the KMS key encrypting the secret**.

### Via Secrets Rotate Lambda

To **rotate secrets** automatically a configured **Lambda** is called. If an attacker could **change** the **code** he could directly **exfiltrate the new secret** to himself.

This is how lambda code for such action could look like:

```python
import boto3

def rotate_secrets(event, context):
    # Create a Secrets Manager client
    client = boto3.client('secretsmanager')

    # Retrieve the current secret value
    secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']

    # Rotate the secret by updating its value
    new_secret_value = rotate_secret(secret_value)
    client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)

def rotate_secret(secret_value):
    # Perform the rotation logic here, e.g., generate a new password

    # Example: Generate a new password
    new_secret_value = generate_password()

    return new_secret_value

def generate_password():
    # Example: Generate a random password using the secrets module
    import secrets
    import string
    password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
    return password
```

{{#include ../../../banners/hacktricks-training.md}}




