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 C# Downloads
// Assumes Chilkat is unlocked. See Global Unlock Sample.
bool success = false;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the EC2 operation.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/ec2.json");
if (success != true) {
Debug.WriteLine("Could not load private AWS credentials.");
return;
}
if ((credentials.JsonTypeOf("access_key") != 1) || (credentials.StringOf("access_key") == "")) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
if ((credentials.JsonTypeOf("secret_key") != 1) || (credentials.StringOf("secret_key") == "")) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
// Set this once to the region containing the instances.
string region = "us-west-2";
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("ec2.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
Chilkat.AuthAws aws = new Chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "ec2";
aws.SignatureVersion = 4;
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("Could not configure AWS signing.");
return;
}
// 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) {
if (credentials.JsonTypeOf("session_token") != 1) {
Debug.WriteLine("session_token must be a string.");
return;
}
if (credentials.StringOf("session_token") != "") {
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
if (success != true) {
Debug.WriteLine("Could not set the session-token parameter.");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Debug.WriteLine("Could not attach the TLS connection.");
return;
}
// 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.
Chilkat.Xml xml = new Chilkat.Xml();
xml.Strict = true;
success = rest.AddQueryParam("Version","2016-11-15");
if (success != true) {
Debug.WriteLine("Could not set Version.");
return;
}
string responseXml = "";
string errorCode = "";
string vpcId = "vpc-0123456789abcdef0";
int i = 0;
int j = 0;
int k = 0;
success = rest.AddQueryParam("Action","DescribeSecurityGroups");
if (success != true) {
Debug.WriteLine("Could not set Action.");
return;
}
success = rest.AddQueryParam("Filter.1.Name","vpc-id");
if (success != true) {
Debug.WriteLine("Could not set Filter.1.Name.");
return;
}
success = rest.AddQueryParam("Filter.1.Value.1",vpcId);
if (success != true) {
Debug.WriteLine("Could not set Filter.1.Value.1.");
return;
}
success = rest.AddQueryParam("MaxResults","100");
if (success != true) {
Debug.WriteLine("Could not set MaxResults.");
return;
}
Chilkat.Hashtable seenTokens = new Chilkat.Hashtable();
string nextToken = "";
bool more = true;
int page = 0;
while ((more == true)) {
if (page == 1000) {
Debug.WriteLine("Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.");
return;
}
responseXml = rest.FullRequestNoBody("GET","/");
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately.");
return;
}
success = xml.LoadXml(responseXml);
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("EC2 HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
if (success == true) {
if (xml.HasChildWithTag("Errors|Error|Code") == true) {
errorCode = xml.GetChildContent("Errors|Error|Code");
Debug.WriteLine("AWS error code: " + errorCode);
}
if (xml.HasChildWithTag("RequestID") == true) {
Debug.WriteLine("AWS request ID: " + xml.GetChildContent("RequestID"));
}
}
// 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;
}
if (success != true) {
Debug.WriteLine("Expected a well-formed XML response.");
return;
}
if (xml.Tag != "DescribeSecurityGroupsResponse") {
Debug.WriteLine("Unexpected EC2 response element.");
return;
}
if ((xml.HasChildWithTag("requestId") != true) || (xml.GetChildContent("requestId") == "")) {
Debug.WriteLine("Missing or empty requestId.");
return;
}
Debug.WriteLine("AWS request ID: " + xml.GetChildContent("requestId"));
if (xml.HasChildWithTag("securityGroupInfo") != true) {
Debug.WriteLine("Expected securityGroupInfo.");
return;
}
i = 0;
while ((i < xml.NumChildrenAt("securityGroupInfo"))) {
xml.I = i;
if ((xml.HasChildWithTag("securityGroupInfo|item[i]|groupId") != true) || (xml.GetChildContent("securityGroupInfo|item[i]|groupId") == "")) {
Debug.WriteLine("Missing or empty securityGroupInfo|item[i]|groupId.");
return;
}
Debug.WriteLine("Security group ID: " + xml.GetChildContent("securityGroupInfo|item[i]|groupId"));
if (xml.HasChildWithTag("securityGroupInfo|item[i]|groupName") == true) {
Debug.WriteLine("Name: " + xml.GetChildContent("securityGroupInfo|item[i]|groupName"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|vpcId") == true) {
Debug.WriteLine("VPC: " + xml.GetChildContent("securityGroupInfo|item[i]|vpcId"));
}
j = 0;
while ((j < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissions"))) {
xml.J = j;
Debug.WriteLine("Inbound rule");
if ((xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol") != true) || (xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol") == "")) {
Debug.WriteLine("Missing or empty securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol.");
return;
}
Debug.WriteLine("Protocol: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipProtocol"));
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|fromPort") == true) {
Debug.WriteLine("From port or ICMP type: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|fromPort"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|toPort") == true) {
Debug.WriteLine("To port or ICMP code: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|toPort"));
}
k = 0;
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) {
Debug.WriteLine("IPv4 CIDR: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|cidrIp"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipRanges|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("IPv6 CIDR: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|cidrIpv6"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|ipv6Ranges|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("Referenced security group: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|groupId"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|groups|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("Prefix list: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|prefixListId"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissions|item[j]|prefixListIds|item[k]|description"));
}
k = k + 1;
}
j = j + 1;
}
j = 0;
while ((j < xml.NumChildrenAt("securityGroupInfo|item[i]|ipPermissionsEgress"))) {
xml.J = j;
Debug.WriteLine("Outbound rule");
if ((xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol") != true) || (xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol") == "")) {
Debug.WriteLine("Missing or empty securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol.");
return;
}
Debug.WriteLine("Protocol: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipProtocol"));
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|fromPort") == true) {
Debug.WriteLine("From port or ICMP type: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|fromPort"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|toPort") == true) {
Debug.WriteLine("To port or ICMP code: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|toPort"));
}
k = 0;
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) {
Debug.WriteLine("IPv4 CIDR: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|cidrIp"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipRanges|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("IPv6 CIDR: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|cidrIpv6"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|ipv6Ranges|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("Referenced security group: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|groupId"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|groups|item[k]|description"));
}
k = k + 1;
}
k = 0;
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) {
Debug.WriteLine("Prefix list: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|prefixListId"));
}
if (xml.HasChildWithTag("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|description") == true) {
Debug.WriteLine("Description: " + xml.GetChildContent("securityGroupInfo|item[i]|ipPermissionsEgress|item[j]|prefixListIds|item[k]|description"));
}
k = k + 1;
}
j = j + 1;
}
i = i + 1;
}
page = page + 1;
more = false;
nextToken = "";
if (xml.HasChildWithTag("nextToken") == true) {
nextToken = xml.GetChildContent("nextToken");
}
if (nextToken != "") {
if (seenTokens.Contains(nextToken) == true) {
Debug.WriteLine("Repeated pagination token; enumeration is incomplete.");
return;
}
success = seenTokens.AddInt(nextToken,1);
if (success != true) {
Debug.WriteLine("Could not track pages.");
return;
}
if (page > 1) {
success = rest.RemoveQueryParam("NextToken");
if (success != true) {
Debug.WriteLine("Could not replace pagination token.");
return;
}
}
success = rest.AddQueryParam("NextToken",nextToken);
if (success != true) {
Debug.WriteLine("Could not set NextToken.");
return;
}
more = true;
}
}
Debug.WriteLine("Enumeration complete.");