获取具有公共IP的每个网络接口的安全组规则

时间:2017-10-09 08:09:36

标签: python amazon-web-services security networking amazon-ec2

我在尝试使用Boto3获取某些信息时遇到了麻烦。 这就是我想要做的事情:

我遍历AWS账户中的所有网络接口,如果一个接口正在使用并且它有一个公共IP,我得到它的安全组,看看是否有任何规则开放流到互联网,如0.0.0.0/0或公共IP。目标是获得有关网络接口连接到Internet的所有实例的安全报告。

这是脚本:

# create dict
ip = {}
SGName = ''
SGID = ''
interfaceID = ''
ListGroups = {}
Message = 'Instances With Public Ips :'  
 # check aws profiles
for p in awsProfile:
    print(p)
    # define aws session
    session = Session(region_name="eu-west-1", profile_name=p)
    ec2 = session.resource('ec2')
    client = session.client('ec2')
    all_interfaces = ec2.network_interfaces.all()
    for interface in all_interfaces:
        interfaceID = interface.id
        desc = client.describe_network_interfaces(NetworkInterfaceIds=[interfaceID])
        for d in desc['NetworkInterfaces']:
            if interface.status == 'in-use' and d.get('Association') is not None:
                interfaceID = interface.id
                print(interfaceID)
                desc = client.describe_network_interfaces(NetworkInterfaceIds=[interfaceID])
                publicIp = d.get('Association')['PublicIp']
                SGName = d.get('Groups')[0].get('GroupName')
                SGID = d.get('Groups')[0].get('GroupId')
                ListGroups[SGName] = SGID
                Message = Message + str(p)+str(interface.vpc.id)+str(interface.attachment.get('InstanceId'))+str(interface.description)+str(interface.private_ip_address)+str(publicIp)+str(interfaceID)+str(SGID)+str(SGName)
                for key in ListGroups:
                    sg = ec2.SecurityGroup(ListGroups[key])
                    for i in range(len(sg.ip_permissions)):
                        for j in range(len(sg.ip_permissions[i]['IpRanges'])):
                            ip = IPNetwork(sg.ip_permissions[i]['IpRanges'][j]['CidrIp'])
                            if(ip.is_private()==False):
                                Message = Message + 'Public Securiy Groups details :'
                                Message = Message +str(ListGroups[key])+str(sg.ip_permissions[i]['ToPort'])

当我执行脚本时,我收到此错误:

Traceback (most recent call last):
  File "openNetwork.py", line 62, in <module>
    for i in range(len(sg.ip_permissions)):
  File "C:\Python\Python35-32\lib\site-packages\boto3\resources\factory.py", line 339, in property_loader
    self.load()
  File "C:\Python\Python35-32\lib\site-packages\boto3\resources\factory.py", line 505, in do_action
    response = action(self, *args, **kwargs)
  File "C:\Python\Python35-32\lib\site-packages\boto3\resources\action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(**params)
  File "C:\Python\Python35-32\lib\site-packages\botocore\client.py", line 310, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\Python\Python35-32\lib\site-packages\botocore\client.py", line 599, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'sg-9abc52e3' d
oes not exist

它说某些安全组不存在。我应该得到附加到某个网络接口的安全组ID并且它存在。我跟踪了导致我出现此错误的网络接口,它有2个连续组,其中任何一个都没有错误中的此ID。知道如何让这个工作吗?

1 个答案:

答案 0 :(得分:0)

如果您的唯一任务只是查找可能构成安全威胁的安全组,请转到AWS Trusted Advisor。其核心检查之一是安全组

  

检查安全组以获取允许不受限制访问的规则   (0.0.0.0/0)到特定端口。无限制访问增加   恶意活动的机会(黑客攻击,拒绝服务   攻击,数据丢失)。风险最高的端口标记为红色,   那些风险较小的人被标记为黄色。标记为绿色的端口是   通常由需要不受限制访问的应用程序使用   作为HTTP和SMTP。