如何检查IAM访问密钥是否具有特定权限?

2024-09-28 17:05:52 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以检查特定的AWS IAM密钥是否具有对一组特定命令的权限?在

本质上,AWS的privacy simulator是否有一个API?在

到目前为止,我一直在使用hacks,比如用不正确的参数执行一个命令,使用有问题的权限,并观察我得到的响应。在

示例:

# needed resource: 'elasticloadbalancer:SetLoadBalancerListenerSSLCertificate'

# Check:
try:
    elb.set_listener_SSL_certificate(443, 'fake')
except BotoServerError as e:
    if e.error_code == 'AccessDenied':
        print ("You don't have access to "
               "elasticloadbalancer:SetLoadBalancerListenerSSLCertificate")

这显然是老调重弹。理想情况下,我会有一些函数调用,比如iam.check_against(resource)或其他什么。有什么建议吗?在


Tags: 命令awsapi权限示例参数密钥resource
2条回答

IAM Policy Simulator为确定哪些用户有权访问特定的API调用提供了一个优秀的UI。在

如果您希望以编程方式测试此项,请使用DryRun参数进行API调用。该函数不会实际执行,但会通知您它是否有足够的权限执行。但是,它不会检查调用本身是否成功(例如证书名称不正确)。在

见第三条simulate_principal_policy。在

我用这个函数来测试权限(您需要稍微修改一下,因为它不是完全自包含的):

from typing import Dict, List, Optional

def blocked(
    actions: List[str],
    resources: Optional[List[str]] = None,
    context: Optional[Dict[str, List]] = None
) -> List[str]:
    """test whether IAM user is able to use specified AWS action(s)

    Args:
        actions (list): AWS action(s) to validate IAM user can use.
        resources (list): Check if action(s) can be used on resource(s).
            If None, action(s) must be usable on all resources ("*").
        context (dict): Check if action(s) can be used with context(s).
            If None, it is expected that no context restrictions were set.

    Returns:
        list: Actions denied by IAM due to insufficient permissions.
    """
    if not actions:
        return []
    actions = list(set(actions))

    if resources is None:
        resources = ["*"]

    _context: List[Dict] = [{}]
    if context is not None:
        # Convert context dict to list[dict] expected by ContextEntries.
        _context = [{
            'ContextKeyName': context_key,
            'ContextKeyValues': [str(val) for val in context_values],
            'ContextKeyType': "string"
        } for context_key, context_values in context.items()]

    # You'll need to create an IAM client here
    results = aws.iam_client().simulate_principal_policy(
        PolicySourceArn=consts.IAM_ARN,  # Your IAM user's ARN goes here
        ActionNames=actions,
        ResourceArns=resources,
        ContextEntries=_context
    )['EvaluationResults']

    return sorted([result['EvalActionName'] for result in results
        if result['EvalDecision'] != "allowed"])

您需要将权限的原始操作名传递给actions,如下所示:

^{pr2}$

下面是一个使用resourcescontext参数的示例:

def validate_type_and_size_allowed(instance_type, volume_size):
    """validate user is allowed to create instance with type and size"""
    if validate_perms.blocked(actions=["ec2:RunInstances"],
            resources=["arn:aws:ec2:*:*:instance/*"],
            context={'ec2:InstanceType': [instance_type]}):
        halt.err(f"Instance type {instance_type} not permitted.")
    if validate_perms.blocked(actions=["ec2:RunInstances"],
            resources=["arn:aws:ec2:*:*:volume/*"],
            context={'ec2:VolumeSize': [volume_size]}):
        halt.err(f"Volume size {volume_size}GiB is too large.")

相关问题 更多 >