Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

Amazon EC2: Inspect Security Groups and Inbound/Outbound Rules

See more Amazon EC2 Examples

Inspect groups in a selected VPC without changing network access. Displays both inbound and outbound permissions, including IPv4, IPv6, referenced security groups, and prefix lists. Protocol -1 means all protocols; port fields can be absent. For ICMP/ICMPv6, the two fields represent type/code, with -1 meaning all. Security groups are stateful allow rules, not an ordered firewall with deny rules. Network ACLs, routes, and host firewalls also affect reachability.

Follows nextToken even after an empty page. Tokens are opaque strings; replace the previous NextToken rather than adding duplicates. A repeated token or the 1000-page demonstration bound reports incomplete results. Pages are not an atomic snapshot, and response order is not guaranteed.

Uses the current EC2 Query API (Version=2016-11-15) over HTTPS. Chilkat.Rest and AuthAws sign the GET request with AWS Signature Version 4, service ec2. Set the region once; the code builds the corresponding commercial AWS endpoint. Other partitions require their own endpoint suffix. EC2 returns XML, unlike DynamoDB's JSON protocol. AddQueryParam encodes parameter values.

Load current IAM credentials from a private qa_data/aws/ec2.json with string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials. The example explicitly reads this file; it does not discover profiles or refresh expired credentials. The session token is included in the signed query, so keep URLs and diagnostics private. A Socket enables TLS certificate verification before handing its connection to Rest.

IAM permissions for the illustrated requests: ec2:DescribeSecurityGroups. Use least-privilege permissions for the intended resources; EC2 describe operations generally require Resource *.

Transport completion, HTTP status, and XML validity are checked separately. API errors contain Errors/Error/Code and RequestID; successful responses use requestId. Check the error code rather than assuming every HTTP 4xx means bad input. Use bounded exponential backoff with jitter for retryable failures. EC2 is eventually consistent: a recent resource change may not appear immediately. Verify account, region, ID, and observed state before retrying a change whose outcome is uncertain.

DescribeSecurityGroups reference

Chilkat B4X Downloads

B4X
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean = False
'  Private configuration, not a file in public web content or source control.
'  Load current IAM credentials authorized for the EC2 operation.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/ec2.json")
If success <> True Then
    Log("Could not load private AWS credentials.")
    Return
End If

If (credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "") Then
    Log("Missing or invalid access_key.")
    Return
End If

If (credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "") Then
    Log("Missing or invalid secret_key.")
    Return
End If

'  Set this once to the region containing the instances.
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("ec2.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "ec2"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure AWS signing.")
    Return
End If

'  Temporary IAM/STS credentials require their session token on every signed request.
'  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
'  Leave session_token absent or empty only for credentials that do not have one.
If credentials.HasMember("session_token") = True Then
    If credentials.JsonTypeOf("session_token") <> 1 Then
        Log("session_token must be a string.")
        Return
    End If

    If credentials.StringOf("session_token") <> "" Then
        success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
        If success <> True Then
            Log("Could not set the session-token parameter.")
            Return
        End If

    End If

End If

'  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach the TLS connection.")
    Return
End If

'  EC2 uses the Query API and XML responses, not AWS JSON protocol headers.
'  AddQueryParam URL-encodes the values; do not pre-encode IDs or tokens.
Dim xml As ChilkatXml
xml.Initialize
xml.Strict = True
success = rest.AddQueryParam("Version", "2016-11-15")
If success <> True Then
    Log("Could not set Version.")
    Return
End If

Dim responseXml As String = ""
Dim errorCode As String = ""
Dim vpcId As String = "vpc-0123456789abcdef0"
Dim i As Int = 0
Dim j As Int = 0
Dim k As Int = 0
success = rest.AddQueryParam("Action", "DescribeSecurityGroups")
If success <> True Then
    Log("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("Filter.1.Name", "vpc-id")
If success <> True Then
    Log("Could not set Filter.1.Name.")
    Return
End If

success = rest.AddQueryParam("Filter.1.Value.1", vpcId)
If success <> True Then
    Log("Could not set Filter.1.Value.1.")
    Return
End If

success = rest.AddQueryParam("MaxResults", "100")
If success <> True Then
    Log("Could not set MaxResults.")
    Return
End If

Dim seenTokens As ChilkatHashtable
seenTokens.Initialize
Dim nextToken As String = ""
Dim more As Boolean = True
Dim page As Int = 0
Do While (more = True)
    If page = 1000 Then
        Log("Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.")
        Return
    End If

    responseXml = rest.FullRequestNoBody("GET", "/")
    If rest.LastMethodSuccess <> True Then
        Log("Request did not complete; inspect diagnostics privately.")
        Return
    End If

    success = xml.LoadXml(responseXml)
    If rest.ResponseStatusCode <> 200 Then
        Log("EC2 HTTP status: " & rest.ResponseStatusCode)
        If success = True Then
            If xml.HasChildWithTag("Errors|Error|Code") = True Then
                errorCode = xml.GetChildContent("Errors|Error|Code")
                Log("AWS error code: " & errorCode)
            End If

            If xml.HasChildWithTag("RequestID") = True Then
                Log("AWS request ID: " & xml.GetChildContent("RequestID"))
            End If

        End If

        '  Keep full error messages and signed request diagnostics private.
        '  UnauthorizedOperation is not a successful dry run. Check IAM permissions.
        '  Retry throttled reads with bounded backoff; renew expired credentials.
        Return
    End If

    If success <> True Then
        Log("Expected a well-formed XML response.")
        Return
    End If

    If xml.Tag <> "DescribeSecurityGroupsResponse" Then
        Log("Unexpected EC2 response element.")
        Return
    End If

    If (xml.HasChildWithTag("requestId") <> True) Or (xml.GetChildContent("requestId") = "") Then
        Log("Missing or empty requestId.")
        Return
    End If

    Log("AWS request ID: " & xml.GetChildContent("requestId"))
    If xml.HasChildWithTag("securityGroupInfo") <> True Then
        Log("Expected securityGroupInfo.")
        Return
    End If

    i = 0
    Do While (i < xml.NumChildrenAt("securityGroupInfo"))
        xml.I = i
        If (xml.HasChildWithTag("securityGroupInfo|item[i]|groupId") <> True) Or (xml.GetChildContent("securityGroupInfo|item[i]|groupId") = "") Then
            Log("Missing or empty securityGroupInfo|item[i]|groupId.")
            Return
        End If

        Log("Security group ID: " & xml.GetChildContent("securityGroupInfo|item[i]|groupId"))
        If xml.HasChildWithTag("securityGroupInfo|item[i]|groupName") = True Then
            Log("Name: " & xml.GetChildContent("securityGroupInfo|item[i]|groupName"))
        End If

        If xml.HasChildWithTag("securityGroupInfo|item[i]|vpcId") = True Then
            Log("VPC: " & xml.GetChildContent("securityGroupInfo|item[i]|vpcId"))
        End If

        j = 0
        Do While (j < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions"))
            xml.J = j
            Log("Inbound rule")
            If (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol") <> True) Or (xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol") = "") Then
                Log("Missing or empty securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol.")
                Return
            End If

            Log("Protocol: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol"))
            If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|fromPort") = True Then
                Log("From port or ICMP type: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|fromPort"))
            End If

            If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|toPort") = True Then
                Log("To port or ICMP code: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|toPort"))
            End If

            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|cidrIp") = True Then
                    Log("IPv4 CIDR: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|cidrIp"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|cidrIpv6") = True Then
                    Log("IPv6 CIDR: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|cidrIpv6"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions|item[j]|groups"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|groupId") = True Then
                    Log("Referenced security group: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|groupId"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|prefixListId") = True Then
                    Log("Prefix list: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|prefixListId"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|description"))
                End If

                k = k + 1
            Loop
            j = j + 1
        Loop
        j = 0
        Do While (j < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress"))
            xml.J = j
            Log("Outbound rule")
            If (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol") <> True) Or (xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol") = "") Then
                Log("Missing or empty securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol.")
                Return
            End If

            Log("Protocol: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol"))
            If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|fromPort") = True Then
                Log("From port or ICMP type: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|fromPort"))
            End If

            If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|toPort") = True Then
                Log("To port or ICMP code: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|toPort"))
            End If

            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|cidrIp") = True Then
                    Log("IPv4 CIDR: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|cidrIp"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|cidrIpv6") = True Then
                    Log("IPv6 CIDR: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|cidrIpv6"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|groupId") = True Then
                    Log("Referenced security group: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|groupId"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|description"))
                End If

                k = k + 1
            Loop
            k = 0
            Do While (k < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds"))
                xml.K = k
                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|prefixListId") = True Then
                    Log("Prefix list: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|prefixListId"))
                End If

                If xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|description") = True Then
                    Log("Description: " & xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|description"))
                End If

                k = k + 1
            Loop
            j = j + 1
        Loop
        i = i + 1
    Loop
    page = page + 1
    more = False
    nextToken = ""
    If xml.HasChildWithTag("nextToken") = True Then
        nextToken = xml.GetChildContent("nextToken")
    End If

    If nextToken <> "" Then
        If seenTokens.Contains(nextToken) = True Then
            Log("Repeated pagination token; enumeration is incomplete.")
            Return
        End If

        success = seenTokens.AddInt(nextToken, 1)
        If success <> True Then
            Log("Could not track pages.")
            Return
        End If

        If page > 1 Then
            success = rest.RemoveQueryParam("NextToken")
            If success <> True Then
                Log("Could not replace pagination token.")
                Return
            End If

        End If

        success = rest.AddQueryParam("NextToken", nextToken)
        If success <> True Then
            Log("Could not set NextToken.")
            Return
        End If

        more = True
    End If

Loop
Log("Enumeration complete.")