AWS - S3, Athena & Glacier Enum
Tip
Aprende y practica AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Aprende y practica Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Apoya a HackTricks
- Consulta los subscription plans!
- Únete al 💬 Discord group o al telegram group o síguenos en Twitter 🐦 @hacktricks_live.
- Comparte trucos de hacking enviando PRs a los HackTricks y HackTricks Cloud github repos.
S3
Amazon S3 es un servicio que te permite almacenar grandes cantidades de datos.
Amazon S3 ofrece múltiples opciones para lograr la protección de los datos en reposo. Las opciones incluyen Permisos (Policy), Cifrado (Client and Server Side), Bucket Versioning y MFA based delete. El usuario puede habilitar cualquiera de estas opciones para lograr la protección de los datos. La replicación de datos es una funcionalidad interna de AWS donde S3 replica automáticamente cada objeto a través de todas las Availability Zones y la organización no necesita habilitarla en este caso.
Con permisos basados en recursos, puedes definir permisos para subdirectorios de tu bucket por separado.
Bucket Versioning and MFA based delete
Cuando Bucket Versioning está habilitado, cualquier acción que intente alterar un archivo dentro de un archivo generará una nueva versión del archivo, conservando también el contenido anterior del mismo. Por lo tanto, no sobrescribirá su contenido.
Además, MFA based delete impedirá que las versiones de archivos en el bucket S3 sean eliminadas y también que Bucket Versioning sea deshabilitado, por lo que un atacante no podrá alterar estos archivos.
S3 Access logs
Es posible habilitar S3 access login (que por defecto está deshabilitado) en algún bucket y guardar los logs en un bucket diferente para saber quién está accediendo al bucket (ambos buckets deben estar en la misma región).
S3 Presigned URLs
Es posible generar un presigned URL que normalmente puede usarse para acceder al archivo especificado en el bucket. Un presigned URL se ve así:
https://<bucket-name>.s3.us-east-1.amazonaws.com/asd.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAUUE8GZC4S5L3TY3P%2F20230227%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230227T142551Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Security-Token=IQoJb3JpZ2luX2VjELf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCIBhQpdETJO3HKKDk2hjNIrPWwBE8gZaQccZFV3kCpPCWAiEAid3ueDtFFU%2FOQfUpvxYTGO%2BHoS4SWDMUrQAE0pIaB40qggMIYBAAGgwzMTgxNDIxMzg1NTMiDJLI5t7gr2EGxG1Y5CrfAioW0foHIQ074y4gvk0c%2B%2Fmqc7cNWb1njQslQkeePHkseJ3owzc%2FCwkgE0EuZTd4mw0aJciA2XIbJRCLPWTb%2FCBKPnIMJ5aBzIiA2ltsiUNQTTUxYmEgXZoJ6rFYgcodnmWW0Et4Xw59UlHnCDB2bLImxPprriyCzDDCD6nLyp3J8pFF1S8h3ZTJE7XguA8joMs4%2B2B1%2FeOZfuxXKyXPYSKQOOSbQiHUQc%2BFnOfwxleRL16prWk1t7TamvHR%2Bt3UgMn5QWzB3p8FgWwpJ6GjHLkYMJZ379tkimL1tJ7o%2BIod%2FMYrS7LDCifP9d%2FuYOhKWGhaakPuJKJh9fl%2B0vGl7kmApXigROxEWon6ms75laXebltsWwKcKuYca%2BUWu4jVJx%2BWUfI4ofoaGiCSaKALTqwu4QNBRT%2BMoK6h%2BQa7gN7JFGg322lkxRY53x27WMbUE4unn5EmI54T4dWt1%2Bg8ljDS%2BvKfBjqmAWRwuqyfwXa5YC3xxttOr3YVvR6%2BaXpzWtvNJQNnb6v0uI3%2BTtTexZkJpLQYqFcgZLQSxsXWSnf988qvASCIUhAzp2UnS1uqy7QjtD5T73zksYN2aesll7rvB80qIuujG6NOdHnRJ2M5%2FKXXNo1Yd15MtzPuSjRoSB9RSMon5jFu31OrQnA9eCUoawxbB0nHqwK8a43CKBZHhA8RoUAJW%2B48EuFsp3U%3D&X-Amz-Signature=3436e4139e84dbcf5e2e6086c0ebc92f4e1e9332b6fda24697bc339acbf2cdfa
Una presigned URL puede ser creada desde la cli usando las credenciales de un principal con acceso al objeto (si la cuenta que usas no tiene acceso, se creará una presigned URL más corta pero será inútil)
aws s3 presign --region <bucket-region> 's3://<bucket-name>/<file-name>'
Note
El único permiso requerido para generar una URL prefirmada es el permiso que se está otorgando, así que para el comando anterior el único permiso necesario por el principal es
s3:GetObject
También es posible crear URLs prefirmadas con otros permisos:
import boto3
url = boto3.client('s3').generate_presigned_url(
ClientMethod='put_object',
Params={'Bucket': 'BUCKET_NAME', 'Key': 'OBJECT_KEY'},
ExpiresIn=3600
)
Mecanismos de cifrado de S3
DEK significa Clave de cifrado de datos y es la clave que siempre se genera y se utiliza para cifrar los datos.
Server-side encryption with S3 managed keys, SSE-S3
Esta opción requiere una configuración mínima y toda la gestión de las claves de cifrado la maneja AWS. Todo lo que necesitas hacer es subir tus datos y S3 se encargará de todos los demás aspectos. A cada bucket en una cuenta S3 se le asigna una bucket key.
- Encryption:
- Object Data + created plaintext DEK –> Encrypted data (almacenados en S3)
- Created plaintext DEK + S3 Master Key –> Encrypted DEK (almacenado en S3) y el texto plano se elimina de la memoria
- Decryption:
- Encrypted DEK + S3 Master Key –> Plaintext DEK
- Plaintext DEK + Encrypted data –> Object Data
Por favor, ten en cuenta que en este caso la clave es gestionada por AWS (rotación solo cada 3 años). Si usas tu propia clave podrás rotarla, deshabilitarla y aplicar control de acceso.
Server-side encryption with KMS managed keys, SSE-KMS
Este método permite que S3 use el key management service para generar tus data encryption keys. KMS te da mucha más flexibilidad sobre cómo se gestionan tus claves. Por ejemplo, puedes desactivar, rotar y aplicar controles de acceso al CMK, y auditar su uso usando AWS Cloud Trail.
- Encryption:
- S3 request data keys from KMS CMK
- KMS uses a CMK to generate the pair DEK plaintext and DEK encrypted and send them to S£
- S3 uses the paintext key to encrypt the data, store the encrypted data and the encrypted key and deletes from memory the plain text key
- Decryption:
- S3 ask to KMS to decrypt the encrypted data key of the object
- KMS decrypt the data key with the CMK and send it back to S3
- S3 decrypts the object data
Server-side encryption with customer provided keys, SSE-C
Esta opción te da la oportunidad de proporcionar tu propia master key que quizá ya estés usando fuera de AWS. Tu clave proporcionada por el cliente se enviaría junto con tus datos a S3, donde S3 realizará el cifrado por ti.
- Encryption:
- The user sends the object data + Customer key to S3
- The customer key is used to encrypt the data and the encrypted data is stored
- a salted HMAC value of the customer key is stored also for future key validation
- the customer key is deleted from memory
- Decryption:
- The user send the customer key
- The key is validated against the HMAC value stored
- The customer provided key is then used to decrypt the data
Client-side encryption with KMS, CSE-KMS
De forma similar a SSE-KMS, esto también usa el key management service para generar tus data encryption keys. Sin embargo, esta vez KMS es llamado desde el cliente y no desde S3. El cifrado tiene lugar en el cliente y los datos cifrados se envían a S3 para su almacenamiento.
- Encryption:
- Client request for a data key to KMS
- KMS returns the plaintext DEK and the encrypted DEK with the CMK
- Both keys are sent back
- The client then encrypts the data with the plaintext DEK and send to S3 the encrypted data + the encrypted DEK (which is saved as metadata of the encrypted data inside S3)
- Decryption:
- The encrypted data with the encrypted DEK is sent to the client
- The client asks KMS to decrypt the encrypted key using the CMK and KMS sends back the plaintext DEK
- The client can now decrypt the encrypted data
Client-side encryption with customer provided keys, CSE-C
Usando este mecanismo, puedes utilizar tus propias claves proporcionadas y usar un AWS-SDK client para cifrar tus datos antes de enviarlos a S3 para su almacenamiento.
- Encryption:
- The client generates a DEK and encrypts the plaintext data
- Then, using it’s own custom CMK it encrypts the DEK
- submit the encrypted data + encrypted DEK to S3 where it’s stored
- Decryption:
- S3 sends the encrypted data and DEK
- As the client already has the CMK used to encrypt the DEK, it decrypts the DEK and then uses the plaintext DEK to decrypt the data
Enumeración
Una de las formas tradicionales principales de comprometer organizaciones de AWS comienza comprometiendo buckets públicamente accesibles. You can find public buckets enumerators in this page.
# Get buckets ACLs
aws s3api get-bucket-acl --bucket <bucket-name>
aws s3api get-object-acl --bucket <bucket-name> --key flag
# Get policy
aws s3api get-bucket-policy --bucket <bucket-name>
aws s3api get-bucket-policy-status --bucket <bucket-name> #if it's public
# list S3 buckets associated with a profile
aws s3 ls
aws s3api list-buckets
# list content of bucket (no creds)
aws s3 ls s3://bucket-name --no-sign-request
aws s3 ls s3://bucket-name --recursive --no-sign-request
# list content of bucket (with creds)
aws s3 ls s3://bucket-name
aws s3api list-objects-v2 --bucket <bucket-name>
aws s3api list-objects --bucket <bucket-name>
aws s3api list-object-versions --bucket <bucket-name>
# copy local folder to S3
aws s3 cp MyFolder s3://bucket-name --recursive
# delete
aws s3 rb s3://bucket-name –-force
# download a whole S3 bucket
aws s3 sync s3://<bucket>/ .
# move S3 bucket to different location
aws s3 sync s3://oldbucket s3://newbucket --source-region us-west-1
# list the sizes of an S3 bucket and its contents
aws s3api list-objects --bucket BUCKETNAME --output json --query "[sum(Contents[].Size), length(Contents[])]"
# Update Bucket policy
aws s3api put-bucket-policy --policy file:///root/policy.json --bucket <bucket-name>
##JSON policy example
{
"Id": "Policy1568185116930",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1568184932403",
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::welcome",
"Principal": "*"
},
{
"Sid": "Stmt1568185007451",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::welcome/*",
"Principal": "*"
}
]
}
# Update bucket ACL
aws s3api get-bucket-acl --bucket <bucket-name> # Way 1 to get the ACL
aws s3api put-bucket-acl --bucket <bucket-name> --access-control-policy file://acl.json
aws s3api get-object-acl --bucket <bucket-name> --key flag #Way 2 to get the ACL
aws s3api put-object-acl --bucket <bucket-name> --key flag --access-control-policy file://objacl.json
##JSON ACL example
## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved.
{
"Owner": {
"DisplayName": "<DisplayName>",
"ID": "<ID>"
},
"Grants": [
{
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
},
"Permission": "FULL_CONTROL"
}
]
}
## An ACL should give you the permission WRITE_ACP to be able to put a new ACL
dual-stack
Puedes acceder a un bucket S3 a través de un endpoint dual-stack usando un nombre de endpoint en estilo virtual hosted o en estilo path. Estos son útiles para acceder a S3 mediante IPv6.
Los endpoints dual-stack usan la siguiente sintaxis:
bucketname.s3.dualstack.aws-region.amazonaws.coms3.dualstack.aws-region.amazonaws.com/bucketname
Privesc
En la siguiente página puedes ver cómo abuse S3 permissions to escalate privileges:
Unauthenticated Access
S3 Post Exploitation
Persistence
Otras vulnerabilidades de S3
S3 HTTP Cache Poisoning Issue
According to this research era posible cachear la respuesta de un bucket arbitrario como si perteneciera a otro. Esto podría haberse abusado para cambiar, por ejemplo, respuestas de archivos javascript y comprometer páginas arbitrarias que usan S3 para almacenar código estático.
Amazon Athena
Amazon Athena es un servicio de consultas interactivas que facilita analizar datos directamente en Amazon Simple Storage Service (Amazon S3) usando SQL estándar.
Necesitas preparar una tabla relacional de base de datos con el formato del contenido que aparecerá en los buckets S3 monitorizados. Luego, Amazon Athena podrá poblar la tabla desde los logs, de modo que puedas consultar los datos.
Amazon Athena soporta la capacidad de consultar datos en S3 que ya están cifrados y, si está configurado para hacerlo, Athena también puede cifrar los resultados de la consulta que luego pueden almacenarse en S3.
Este cifrado de resultados es independiente de los datos subyacentes en S3 consultados, lo que significa que incluso si los datos de S3 no están cifrados, los resultados de la consulta pueden estarlo. Un par de puntos a tener en cuenta es que Amazon Athena solo soporta datos que han sido cifrados con los siguientes métodos de cifrado de S3, SSE-S3, SSE-KMS, and CSE-KMS.
SSE-C y CSE-C no son soportados. Además, es importante entender que Amazon Athena solo ejecutará consultas contra objetos cifrados que estén en la misma región que la propia consulta. Si necesitas consultar datos S3 que han sido cifrados usando KMS, entonces se requieren permisos específicos por parte del usuario de Athena para permitirle realizar la consulta.
Enumeración
# Get catalogs
aws athena list-data-catalogs
# Get databases inside catalog
aws athena list-databases --catalog-name <catalog-name>
aws athena list-table-metadata --catalog-name <catalog-name> --database-name <db-name>
# Get query executions, queries and results
aws athena list-query-executions
aws athena get-query-execution --query-execution-id <id> # Get query and meta of results
aws athena get-query-results --query-execution-id <id> # This will rerun the query and get the results
# Get workgroups & Prepared statements
aws athena list-work-groups
aws athena list-prepared-statements --work-group <wg-name>
aws athena get-prepared-statement --statement-name <name> --work-group <wg-name>
# Run query
aws athena start-query-execution --query-string <query>
Referencias
- https://cloudsecdocs.com/aws/defensive/tooling/cli/#s3
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html
Tip
Aprende y practica AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Aprende y practica Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Apoya a HackTricks
- Consulta los subscription plans!
- Únete al 💬 Discord group o al telegram group o síguenos en Twitter 🐦 @hacktricks_live.
- Comparte trucos de hacking enviando PRs a los HackTricks y HackTricks Cloud github repos.
HackTricks Cloud

