-
Notifications
You must be signed in to change notification settings - Fork 10
/
review-security-groups.php
88 lines (68 loc) · 1.89 KB
/
review-security-groups.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
// takes JSON on stdin; writes clean report on stdout
$contents = '';
while (!feof(STDIN)) {
$contents .= fread(STDIN, 8192);
}
// --- process json data ----
$sgs = json_decode($contents, true);
foreach ($sgs['SecurityGroups'] as $g) {
$name = $g['GroupName'];
$sgid = $g['GroupId'];
$ingressCount = count($g['IpPermissions']);
$egressCount = count($g['IpPermissionsEgress']);
echo "$sgid ###### IN: $ingressCount OUT: $egressCount - $name\n";
$rulesIngress = getRuleText($g['IpPermissions']);
$rulesEgress = getRuleText($g['IpPermissionsEgress']);
// sort the rules for stability
natsort($rulesIngress);
natsort($rulesEgress);
foreach ($rulesIngress as $in) {
echo "$sgid <- $in\n";
}
foreach ($rulesEgress as $out) {
echo "$sgid -> $out\n";
}
}
// --------------------------------------------------------------------
function getRuleText($node) {
if (! is_array($node)) {
return "INVALID";
}
$rules = array();
foreach ($node as $item) {
switch($item['IpProtocol']) {
case '6': $proto = 'TCP'; break;
case '17': $proto = 'UDP'; break;
case '-1': $proto = 'ANY'; break;
default:
$proto = $item['IpProtocol'];
break;
}
$nets = array();
foreach ($item['IpRanges'] as $cidr) {
$nets[] = $cidr['CidrIp'];
}
$ugids = array();
foreach ($item['UserIdGroupPairs'] as $ugp) {
$ugids[] = $ugp['GroupId'];
}
// merge the set of sources, and sort them for stability
$sources = array_merge($nets, $ugids);
natsort($sources);
$ports = '';
if (array_key_exists('FromPort', $item) &&
array_key_exists('ToPort', $item)) {
if ($item['ToPort'] == $item['FromPort']) {
$ports = $item['FromPort'];
} else {
$ports = $item['FromPort'] .'-'. $item['ToPort'];
}
} elseif ('ANY' == $proto){
$ports = 'ANY';
}
$sourceList = implode(' ', $sources);
$rules[] = "$proto $ports $sourceList";
}
return $rules;
}