-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
672 lines (601 loc) · 17.3 KB
/
ec2.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
package ec2
import (
"errors"
"fmt"
"os"
"sort"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
// Connection provides a connection
// to AWS EC2.
//
// **Attributes:**
//
// Client: the EC2 client
type Connection struct {
Client *ec2.EC2
}
// Params provides information
// about an EC2 instance.
//
// **Attributes:**
//
// AssociatePublicIPAddress: whether to associate a public IP address
// ImageID: the ID of the AMI to use
// InstanceProfile: the name of the instance profile to use
// InstanceType: the type of the instance to use
// MinCount: the minimum number of instances to launch
// MaxCount: the maximum number of instances to launch
// SecurityGroupIDs: the IDs of the security groups to use
// KeyName: the name of the key pair to use
// SubnetID: the ID of the subnet to use
// VolumeSize: the size of the volume to use
// InstanceName: the name of the instance to use
type Params struct {
AssociatePublicIPAddress bool
ImageID string
InstanceProfile string
InstanceType string
MinCount int
MaxCount int
SecurityGroupIDs []string
KeyName string
SubnetID string
VolumeSize int64
InstanceName string
}
// AMIInfo provides information
// about an AMI.
//
// **Attributes:**
//
// Distro: the distro to use
// Version: the version to use
// Architecture: the architecture to use
// Region: the region to use
type AMIInfo struct {
Distro string
Version string
Architecture string
Region string
}
// NewConnection creates a new connection
// to AWS EC2.
//
// **Returns:**
//
// *Connection: a new connection to AWS EC2
func NewConnection() *Connection {
sess := session.Must(session.NewSessionWithOptions(
session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := ec2.New(sess)
return &Connection{Client: svc}
}
// IsEC2Instance checks whether the code is running on an AWS
// EC2 instance by checking the existence of the file
// /sys/devices/virtual/dmi/id/product_uuid. If the file exists,
// the code is running on an EC2 instance, and the function
// returns true. If the file does not exist, the function returns false,
// indicating that the code is not running on an EC2 instance.
//
// **Returns:**
//
// bool: A boolean value that indicates whether the code is running on an EC2 instance.
func IsEC2Instance() bool {
// Check for the existence of the product_uuid file. If it exists, we're on an EC2 instance.
if _, err := os.Stat("/sys/devices/virtual/dmi/id/product_uuid"); err == nil {
return true
}
return false
}
// CreateInstance creates a new EC2 instance
// with the provided parameters.
//
// **Parameters:**
//
// ec2Params: the parameters to use
//
// **Returns:**
//
// *ec2.Reservation: the reservation of the created instance
//
// error: an error if any issue occurs while trying to create the instance
func (c *Connection) CreateInstance(ec2Params Params) (*ec2.Reservation, error) {
input := &ec2.RunInstancesInput{
BlockDeviceMappings: c.getBlockDeviceMappings(ec2Params),
IamInstanceProfile: c.getIAMInstanceProfile(ec2Params),
ImageId: aws.String(ec2Params.ImageID),
InstanceType: aws.String(ec2Params.InstanceType),
MinCount: aws.Int64(int64(ec2Params.MinCount)),
MaxCount: aws.Int64(int64(ec2Params.MaxCount)),
NetworkInterfaces: c.getNetworkInterfaces(ec2Params),
TagSpecifications: c.getTagSpecifications(ec2Params),
}
result, err := c.Client.RunInstances(input)
if err != nil {
return nil, err
}
return result, nil
}
// CheckInstanceExists checks whether an instance
// with the provided ID exists.
//
// **Parameters:**
//
// instanceID: the ID of the instance to check
//
// **Returns:**
//
// error: an error if any issue occurs while trying to check the instance
func (c *Connection) CheckInstanceExists(instanceID string) error {
instances, err := c.GetInstances(nil)
if err != nil {
return err
}
for _, instance := range instances {
if *instance.InstanceId == instanceID {
return nil
}
}
return fmt.Errorf("instance %s does not exist", instanceID)
}
// TagInstance tags an instance with the provided key and value.
//
// **Parameters:**
//
// instanceID: the ID of the instance to tag
//
// tagKey: the key of the tag to use
//
// tagValue: the value of the tag to use
//
// **Returns:**
//
// error: an error if any issue occurs while trying to tag the instance
func (c *Connection) TagInstance(instanceID string, tagKey string, tagValue string) error {
input := &ec2.CreateTagsInput{
Resources: []*string{&instanceID},
Tags: []*ec2.Tag{
{
Key: aws.String(tagKey),
Value: aws.String(tagValue),
},
},
}
_, err := c.Client.CreateTags(input)
if err != nil {
return err
}
return nil
}
// DestroyInstance destroys the instance with the provided ID.
//
// **Parameters:**
//
// instanceID: the ID of the instance to destroy
//
// **Returns:**
//
// error: an error if any issue occurs while trying to destroy the instance
func (c *Connection) DestroyInstance(instanceID string) error {
input := &ec2.TerminateInstancesInput{
InstanceIds: []*string{&instanceID},
}
_, err := c.Client.TerminateInstances(input)
if err != nil {
return err
}
return nil
}
// GetRunningInstances retrieves all running instances.
//
// **Returns:**
//
// *ec2.DescribeInstancesOutput: the output of the DescribeInstances operation
//
// error: an error if any issue occurs while trying to retrieve the running instances
func (c *Connection) GetRunningInstances() (*ec2.DescribeInstancesOutput, error) {
input := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("running")},
},
},
}
result, err := c.Client.DescribeInstances(input)
if err != nil {
return nil, err
}
return result, err
}
// WaitForInstance waits until the instance with the provided ID
// is in the running state.
//
// **Parameters:**
//
// instanceID: the ID of the instance to wait for
//
// **Returns:**
//
// error: an error if any issue occurs while trying to wait for the instance
func (c *Connection) WaitForInstance(instanceID string) error {
input := &ec2.DescribeInstanceStatusInput{
InstanceIds: []*string{&instanceID},
}
err := c.Client.WaitUntilInstanceStatusOk(input)
if err != nil {
return err
}
return nil
}
// GetInstancePublicIP retrieves the public IP address of the instance
// with the provided ID.
//
// **Parameters:**
//
// instanceID: the ID of the instance to use
//
// **Returns:**
//
// string: the public IP address of the instance
//
// error: an error if any issue occurs while trying to retrieve the public IP address
func (c *Connection) GetInstancePublicIP(instanceID string) (string, error) {
input := &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
}
result, err := c.Client.DescribeInstances(input)
if err != nil {
return "", err
}
return *result.Reservations[0].
Instances[0].
NetworkInterfaces[0].
Association.
PublicIp, nil
}
// GetRegion retrieves the region of the connection.
//
// **Returns:**
//
// string: the region of the connection
//
// error: an error if any issue occurs while trying to retrieve the region
func (c *Connection) GetRegion() (string, error) {
region := c.Client.Config.Region
if region == nil {
return "", errors.New("failed to retrieve region")
}
return *region, nil
}
// GetInstances retrieves all instances matching the provided filters.
//
// **Parameters:**
//
// filters: the filters to use
//
// **Returns:**
//
// []*ec2.Instance: the instances matching the provided filters
//
// error: an error if any issue occurs while trying to retrieve the instances
func (c *Connection) GetInstances(filters []*ec2.Filter) ([]*ec2.Instance, error) {
input := &ec2.DescribeInstancesInput{
Filters: filters,
}
result, err := c.Client.DescribeInstances(input)
if err != nil {
return nil, err
}
var instances []*ec2.Instance
for _, reservation := range result.Reservations {
instances = append(instances, reservation.Instances...)
}
return instances, nil
}
// GetInstanceState retrieves the state of the instance with the provided ID.
//
// **Parameters:**
//
// instanceID: the ID of the instance to use
//
// **Returns:**
//
// string: the state of the instance
//
// error: an error if any issue occurs while trying to retrieve the state
func (c *Connection) GetInstanceState(instanceID string) (string, error) {
input := &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
}
result, err := c.Client.DescribeInstances(input)
if err != nil {
return "", err
}
return *result.Reservations[0].Instances[0].State.Name, nil
}
// GetInstancesRunningForMoreThan24Hours retrieves all instances
// that have been running for more than 24 hours.
//
// **Returns:**
//
// []*ec2.Instance: the instances that have been running for more than 24 hours
//
// error: an error if any issue occurs while trying to retrieve the instances
func (c *Connection) GetInstancesRunningForMoreThan24Hours() ([]*ec2.Instance, error) {
instances, err := c.GetInstances(nil)
if err != nil {
return nil, err
}
var instancesOver24Hours []*ec2.Instance
for _, instance := range instances {
if instance.LaunchTime.Before(time.Now().Add(-24 * time.Hour)) {
instancesOver24Hours = append(instancesOver24Hours, instance)
}
}
return instancesOver24Hours, nil
}
// GetLatestAMI retrieves the latest Amazon Machine Image (AMI) for a
// specified distribution, version and architecture. It utilizes AWS SDK
// to query AWS EC2 for the AMIs matching the provided pattern and returns
// the latest one based on the creation date.
//
// **Parameters:**
//
// info: An AMIInfo struct containing necessary details like Distro,
// Version, Architecture, and Region for which the AMI needs to be retrieved.
//
// **Returns:**
//
// string: The ID of the latest AMI found based on the provided information.
//
// error: An error if any issue occurs while trying to get the latest AMI.
func (c *Connection) GetLatestAMI(info AMIInfo) (string, error) {
versionToAMIName := map[string]map[string]map[string]string{
"ubuntu": {
"22.04": {
"amd64": "ubuntu/images/hvm-ssd/ubuntu-jammy-%s-amd64-server-*",
"arm64": "ubuntu/images/hvm-ssd/ubuntu-jammy-%s-arm64-server-*",
},
"20.04": {
"amd64": "ubuntu/images/hvm-ssd/ubuntu-focal-%s-amd64-server-*",
"arm64": "ubuntu/images/hvm-ssd/ubuntu-focal-%s-arm64-server-*",
},
"18.04": {
"amd64": "ubuntu/images/hvm-ssd/ubuntu-bionic-%s-amd64-server-*",
"arm64": "ubuntu/images/hvm-ssd/ubuntu-bionic-%s-arm64-server-*",
},
},
"centos": {
"7": {
"x86_64": "CentOS Linux %s x86_64 HVM EBS*",
"arm64": "CentOS Linux %s arm64 HVM EBS*",
},
"8": {
"x86_64": "CentOS %s AMI*",
"arm64": "CentOS %s ARM64 AMI*",
},
},
"debian": {
"10": {
"amd64": "debian-%s-buster-hvm-amd64-gp2*",
"arm64": "debian-%s-buster-hvm-arm64-gp2*",
},
},
"kali": {
"2023.1": {
"amd64": "kali-linux-%s-amd64*",
"arm64": "kali-linux-%s-arm64*",
},
},
}
distToOwner := map[string]string{
"ubuntu": "099720109477", // Canonical
"debian": "136693071363", // Debian
"kali": "679593333241", // Kali Linux
}
owner, ok := distToOwner[info.Distro]
if !ok {
return "", fmt.Errorf("unsupported distribution: %s", info.Distro)
}
amiNamePattern, ok := versionToAMIName[info.Distro][info.Version][info.Architecture]
if !ok {
return "", fmt.Errorf("unsupported distribution/version/architecture: %s/%s/%s", info.Distro, info.Version, info.Architecture)
}
amiNamePattern = fmt.Sprintf(amiNamePattern, info.Version)
sess, err := session.NewSession(&aws.Config{
Region: aws.String(info.Region),
})
if err != nil {
return "", err
}
svc := ec2.New(sess)
input := &ec2.DescribeImagesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("name"),
Values: []*string{aws.String(amiNamePattern + "*")},
},
},
Owners: []*string{aws.String(owner)},
}
result, err := svc.DescribeImages(input)
if err != nil {
return "", err
}
if len(result.Images) == 0 {
return "", fmt.Errorf("no images found for distro: %s, version: %s, "+
"architecture: %s", info.Distro, info.Version, info.Architecture)
}
// Sort images by CreationDate in descending order
sort.Slice(result.Images, func(i, j int) bool {
iTime, _ := time.Parse(time.RFC3339, *result.Images[i].CreationDate)
jTime, _ := time.Parse(time.RFC3339, *result.Images[j].CreationDate)
return iTime.After(jTime)
})
// Get the latest image (first image after sorting in descending order)
latestImage := result.Images[0]
return *latestImage.ImageId, nil
}
// FindOverlyPermissiveInboundRules checks if a specific security group permits
// all inbound traffic.
//
// Specifically, it checks if the security group has an inbound rule with the
// IP protocol set to "-1", which allows all IP traffic. This is useful for
// identifying security groups that are configured with lenient security rules,
// especially in testing environments. The function uses AWS SDK to describe
// security groups in AWS EC2 and checks their inbound rules.
//
// **Parameters:**
//
// secGrpID: A string containing the ID of the security group which needs to be
// checked for the all traffic inbound rule.
//
// **Returns:**
//
// bool: A boolean value indicating whether the security group permits all
// inbound traffic or not.
//
// error: An error if any issue occurs while trying to describe the
// security group or check its inbound rules.
func (c *Connection) FindOverlyPermissiveInboundRules(secGrpID string) (bool, error) {
input := &ec2.DescribeSecurityGroupsInput{
GroupIds: []*string{aws.String(secGrpID)},
}
resp, err := c.Client.DescribeSecurityGroups(input)
if err != nil {
return false, err
}
for _, group := range resp.SecurityGroups {
for _, permission := range group.IpPermissions {
if *permission.IpProtocol == "-1" {
return true, nil
}
}
}
return false, nil
}
// ListSecurityGroups lists all security groups.
//
// **Returns:**
//
// []*ec2.SecurityGroup: all security groups
//
// error: an error if any issue occurs while trying to list the security groups
func (c *Connection) ListSecurityGroups() ([]*ec2.SecurityGroup, error) {
input := &ec2.DescribeSecurityGroupsInput{}
result, err := c.Client.DescribeSecurityGroups(input)
if err != nil {
return nil, err
}
return result.SecurityGroups, nil
}
// CreateSecurityGroup creates a new security group with the provided name,
// description and VPC ID.
//
// **Parameters:**
//
// groupName: the name of the security group to use
//
// description: the description of the security group to use
//
// vpcID: the ID of the VPC to use
//
// **Returns:**
//
// string: the ID of the created security group
//
// error: an error if any issue occurs while trying to create the security group
func (c *Connection) CreateSecurityGroup(groupName, description, vpcID string) (string, error) {
input := &ec2.CreateSecurityGroupInput{
GroupName: aws.String(groupName),
Description: aws.String(description),
VpcId: aws.String(vpcID),
}
result, err := c.Client.CreateSecurityGroup(input)
if err != nil {
return "", err
}
return *result.GroupId, nil
}
// DestroySecurityGroup destroys the security group with the provided ID.
//
// **Parameters:**
//
// groupId: the ID of the security group to destroy
//
// **Returns:**
//
// error: an error if any issue occurs while trying to destroy the security group
func (c *Connection) DestroySecurityGroup(groupID string) error {
input := &ec2.DeleteSecurityGroupInput{
GroupId: aws.String(groupID),
}
_, err := c.Client.DeleteSecurityGroup(input)
if err != nil {
return err
}
return nil
}
func (c *Connection) checkResourceExistence(resourceName, resourceID string) error {
switch resourceName {
case "subnet":
input := &ec2.DescribeSubnetsInput{
SubnetIds: []*string{aws.String(resourceID)},
}
_, err := c.Client.DescribeSubnets(input)
return err
case "vpc":
input := &ec2.DescribeVpcsInput{
VpcIds: []*string{aws.String(resourceID)},
}
_, err := c.Client.DescribeVpcs(input)
return err
default:
return errors.New("unsupported resource type")
}
}
func (c *Connection) getBlockDeviceMappings(ec2Params Params) []*ec2.BlockDeviceMapping {
return []*ec2.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/sdh"),
Ebs: &ec2.EbsBlockDevice{
VolumeSize: aws.Int64(ec2Params.VolumeSize),
},
},
}
}
func (c *Connection) getIAMInstanceProfile(ec2Params Params) *ec2.IamInstanceProfileSpecification {
return &ec2.IamInstanceProfileSpecification{
Name: aws.String(ec2Params.InstanceProfile),
}
}
func (c *Connection) getNetworkInterfaces(ec2Params Params) []*ec2.InstanceNetworkInterfaceSpecification {
return []*ec2.InstanceNetworkInterfaceSpecification{
{
AssociatePublicIpAddress: aws.Bool(ec2Params.AssociatePublicIPAddress),
DeviceIndex: aws.Int64(int64(0)),
SubnetId: aws.String(ec2Params.SubnetID),
Groups: aws.StringSlice(ec2Params.SecurityGroupIDs),
},
}
}
func (c *Connection) getTagSpecifications(ec2Params Params) []*ec2.TagSpecification {
return []*ec2.TagSpecification{
{
ResourceType: aws.String("instance"),
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String(ec2Params.InstanceName),
},
},
},
}
}