-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-sg-updater.go
315 lines (243 loc) · 6.92 KB
/
aws-sg-updater.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"aws-sg-updater/pkg/ec2client"
"errors"
"flag"
"fmt"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/google/uuid"
"github.com/kirsle/configdir"
"github.com/rdegges/go-ipify"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"time"
)
type EntryDetails struct {
Port int32
Cidr string
Uuid string
Description string
}
var (
awsProfileConnectParam = flag.String("profile", "", "AWS Cli Profile to use")
securityGroupIdParam = flag.String("security-group-id", "", "Security group id")
securityGroupNameParam = flag.String("security-group-name", "", "Security group name")
useNameTag = flag.Bool("use-name-tag", false, "Use Name tag instead of security group name, relevant when --security-group-name specified")
portParam = flag.String("port", "", "Security group port number")
dateFormat = flag.String("date-format", "2006-01-02", "Go format of the date to put in the description")
)
func getAwsConnectProfile() string {
profile := *awsProfileConnectParam
if profile != "" {
return profile
}
profile = os.Getenv("AWS_PROFILE")
if profile != "" {
return profile
}
return ""
}
func initialize(awsProfile string) bool {
return ec2client.Initialize(awsProfile) == nil
}
func updateSecurityGroup() {
details, err := getEntryDetails()
if err != nil {
return
}
securityGroup, err := getSecurityGroup(*securityGroupIdParam, *securityGroupNameParam, *useNameTag)
if err != nil {
return
}
log.Printf("Updating %v with %v:%v - %v", *securityGroup.GroupName, details.Cidr, details.Port, details.Uuid)
if cleanupOldEntryIfExists(securityGroup, details) {
createNewEntry(securityGroup, details)
}
}
func getSecurityGroup(securityGroupId string, securityGroupName string, useNameTag bool) (*types.SecurityGroup, error) {
securityGroup, err := getSecurityGroupSilent(securityGroupId, securityGroupName, useNameTag)
if err != nil {
log.Printf("Error getting security group (provided id: %v) (provided name: %v) (use tag? %v) %v",
securityGroupId, securityGroupName, useNameTag, err)
}
if securityGroup == nil {
log.Printf("Security group not found (provided id: %v) (provided name: %v) (use tag? %v)",
securityGroupId, securityGroupName, useNameTag)
return nil, errors.New("Security group not found")
}
return securityGroup, err
}
func getSecurityGroupSilent(securityGroupId string, securityGroupName string, useNameTag bool) (*types.SecurityGroup, error) {
if securityGroupId != "" {
return ec2client.GetSecurityGroupById(securityGroupId)
} else if securityGroupName != "" {
return getSecurityGroupByName(securityGroupName, useNameTag)
} else {
return nil, errors.New("Neither security group id nor security group name provided")
}
}
func getSecurityGroupByName(securityGroupName string, useNameTag bool) (*types.SecurityGroup, error) {
if useNameTag {
return ec2client.GetSecurityGroupByFilter("tag:Name", securityGroupName)
} else {
return ec2client.GetSecurityGroupByFilter("group-name", securityGroupName)
}
}
func getEntryDetails() (EntryDetails, error) {
port, err := strconv.Atoi(*portParam)
if err != nil {
return EntryDetails{}, err
}
cidr, err := getCidr()
if err != nil {
return EntryDetails{}, err
}
uuid, err := getPersistedUuid()
if err != nil {
return EntryDetails{}, err
}
description, err := buildDescription(uuid, port)
if err != nil {
return EntryDetails{}, err
}
return EntryDetails{
Port: int32(port),
Cidr: cidr,
Uuid: uuid,
Description: description,
}, nil
}
func getCidr() (string, error) {
ip, err := ipify.GetIp()
if err != nil {
log.Printf("Couldn't get my IP address:", err)
return "", err
}
return fmt.Sprintf("%s/32", ip), nil
}
func getPersistedUuid() (string, error) {
uuidFile, err := getPersistedUuidFile()
if err != nil {
return "", err
}
if _, err := os.Stat(uuidFile); os.IsNotExist(err) {
if err := initializeUuidFile(uuidFile); err != nil {
return "", err
}
}
return readUuidFile(uuidFile)
}
func getPersistedUuidFile() (string, error) {
configPath := configdir.LocalConfig("aws-sg-updater")
err := configdir.MakePath(configPath)
if err != nil {
log.Printf("Error getting UUID file %v", err)
return "", err
}
return filepath.Join(configPath, "uuid"), nil
}
func initializeUuidFile(uuidFile string) error {
file, err := os.Create(uuidFile)
if err != nil {
log.Printf("Error openning UUID file for writing %v, %v", uuidFile, err)
return err
}
defer file.Close()
file.WriteString(uuid.NewString())
return nil
}
func readUuidFile(uuidFile string) (string, error) {
data, err := ioutil.ReadFile(uuidFile)
if err != nil {
log.Printf("Error openning UUID file %v, %v", uuidFile, err)
return "", err
}
return string(data), nil
}
func buildDescription(uuid string, port int) (string, error) {
formattedDate := getFormattedDate(*dateFormat)
username, err := getCurrentUserName()
if err != nil {
return "", err
}
return fmt.Sprintf("%s %s port:%d - %s", username, formattedDate, port, uuid), nil
}
func getFormattedDate(dateFormat string) string {
currentTime := time.Now()
return currentTime.Format("2006-01-02")
}
func getCurrentUserName() (string, error) {
user, err := user.Current()
if err != nil {
log.Printf("Error getting current user name %v", err)
return "", err
}
return user.Username, nil
}
func cleanupOldEntryIfExists(securityGroup *types.SecurityGroup, details EntryDetails) bool {
oldCidr := findOldCidr(securityGroup, details)
if oldCidr == "" {
return true
}
if oldCidr == details.Cidr {
log.Printf("Cidr is up to date.")
return false
}
err := ec2client.RevokeSecurityGroupIngress(
*securityGroup.GroupId,
details.Port,
oldCidr)
if err != nil {
log.Printf("Error revoking to %v %v %v", *securityGroup.GroupId, details, err)
return true
}
log.Printf("Successfully revoked old Cidr %v", oldCidr)
return true
}
func findOldCidr(securityGroup *types.SecurityGroup, details EntryDetails) string {
for _, inPermission := range securityGroup.IpPermissions {
if inPermission.FromPort != details.Port {
continue
}
if inPermission.ToPort != details.Port {
continue
}
for _, ipRange := range inPermission.IpRanges {
if ipRange.Description == nil {
continue
}
if ipRange.CidrIp == nil {
continue
}
if strings.Contains(*ipRange.Description, details.Uuid) {
return *ipRange.CidrIp
}
}
}
return ""
}
func createNewEntry(securityGroup *types.SecurityGroup, details EntryDetails) {
err := ec2client.AuthorizeSecurityGroupIngress(
*securityGroup.GroupId,
details.Port,
details.Cidr,
details.Description)
if err != nil {
log.Printf("Error authorizing to %v %v %v", *securityGroup.GroupId, details, err)
return
}
log.Printf("Successfully added authorize role")
}
func main() {
flag.Parse()
awsProfile := getAwsConnectProfile()
if !initialize(awsProfile) {
return
}
updateSecurityGroup()
}