-
Notifications
You must be signed in to change notification settings - Fork 19
/
compute.go
261 lines (236 loc) · 8.9 KB
/
compute.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
/*
* Copyright 2021 Fraunhofer AISEC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $$\ $$\ $$\ $$\
* $$ | $$ |\__| $$ |
* $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\
* $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\
* $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__|
* $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ |
* \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ |
* \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
*
* This file is part of Clouditor Community Edition.
*/
package aws
import (
"context"
"errors"
"fmt"
"clouditor.io/clouditor/api/discovery"
"clouditor.io/clouditor/voc"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
typesEC2 "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/lambda"
typesLambda "github.com/aws/aws-sdk-go-v2/service/lambda/types"
"github.com/aws/smithy-go"
)
// computeDiscovery handles the AWS API requests regarding the computing services (EC2 and Lambda)
type computeDiscovery struct {
virtualMachineAPI EC2API
functionAPI LambdaAPI
isDiscovering bool
awsConfig *Client
}
// EC2API describes the EC2 api interface which is implemented by the official AWS client and mock clients in tests
type EC2API interface {
DescribeInstances(ctx context.Context,
params *ec2.DescribeInstancesInput,
optFns ...func(options *ec2.Options)) (*ec2.DescribeInstancesOutput, error)
}
// LambdaAPI describes the lambda api interface which is implemented by the official AWS client and mock clients in tests
type LambdaAPI interface {
ListFunctions(ctx context.Context,
params *lambda.ListFunctionsInput, optFns ...func(*lambda.Options)) (*lambda.ListFunctionsOutput, error)
}
// newFromConfigEC2 holds ec2.NewFromConfig(...) allowing a test function to mock it
var newFromConfigEC2 = ec2.NewFromConfig
// newFromConfigLambda holds lambda.NewFromConfig(...) allowing a test function tp mock it
var newFromConfigLambda = lambda.NewFromConfig
// NewAwsComputeDiscovery constructs a new awsS3Discovery initializing the s3-virtualMachineAPI and isDiscovering with true
func NewAwsComputeDiscovery(client *Client) discovery.Discoverer {
return &computeDiscovery{
virtualMachineAPI: newFromConfigEC2(client.cfg),
functionAPI: newFromConfigLambda(client.cfg),
isDiscovering: true,
awsConfig: client,
}
}
// Name is the method implementation defined in the discovery.Discoverer interface
func (*computeDiscovery) Name() string {
return "AWS Compute"
}
// List is the method implementation defined in the discovery.Discoverer interface
func (d computeDiscovery) List() (resources []voc.IsCloudResource, err error) {
log.Infof("Collecting evidences in %s", d.Name())
listOfVMs, err := d.discoverVirtualMachines()
if err != nil {
return nil, fmt.Errorf("could not discover virtual machines: %w", err)
}
for _, machine := range listOfVMs {
resources = append(resources, &machine)
}
listOfFunctions, err := d.discoverFunctions()
if err != nil {
return nil, fmt.Errorf("could not discover functions: %w", err)
}
for _, function := range listOfFunctions {
resources = append(resources, &function)
}
return
}
// discoverVirtualMachines discovers all VMs (in the current region)
func (d *computeDiscovery) discoverVirtualMachines() ([]voc.VirtualMachine, error) {
resp, err := d.virtualMachineAPI.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{})
if err != nil {
var ae smithy.APIError
if errors.As(err, &ae) {
err = formatError(ae)
}
return nil, err
}
var resources []voc.VirtualMachine
for _, reservation := range resp.Reservations {
for i := range reservation.Instances {
vm := &reservation.Instances[i]
computeResource := &voc.Compute{
Resource: &voc.Resource{
ID: d.addARNToVM(vm),
Name: d.getNameOfVM(vm),
CreationTime: 0,
Type: []string{"VirtualMachine", "Compute", "Resource"},
GeoLocation: voc.GeoLocation{
Region: d.awsConfig.cfg.Region,
},
},
NetworkInterface: d.getNetworkInterfacesOfVM(vm),
}
resources = append(resources, voc.VirtualMachine{
Compute: computeResource,
BlockStorage: d.mapBlockStorageIDsOfVM(vm),
BootLogging: d.getBootLog(vm),
OSLogging: d.getOSLog(vm),
})
}
}
return resources, nil
}
// discoverFunctions discovers all lambda functions
func (d *computeDiscovery) discoverFunctions() (resources []voc.Function, err error) {
// 'listFunctions' discovers up to 50 Lambda functions per execution -> loop through when response has nextMarker set
var resp *lambda.ListFunctionsOutput
var nextMarker *string
for {
resp, err = d.functionAPI.ListFunctions(context.TODO(), &lambda.ListFunctionsInput{
Marker: nextMarker,
})
if err != nil {
var ae smithy.APIError
if errors.As(err, &ae) {
err = formatError(ae)
}
return nil, err
}
resources = append(resources, d.mapFunctionResources(resp.Functions)...)
if nextMarker = resp.NextMarker; nextMarker == nil {
break
}
}
return
}
// mapFunctionResources iterates functionConfigurations and returns a list of corresponding FunctionResources
func (d *computeDiscovery) mapFunctionResources(functions []typesLambda.FunctionConfiguration) (resources []voc.Function) {
for i := range functions {
function := &functions[i]
resources = append(resources, voc.Function{
Compute: &voc.Compute{
Resource: &voc.Resource{
ID: voc.ResourceID(aws.ToString(function.FunctionArn)),
Name: aws.ToString(function.FunctionName),
CreationTime: 0,
Type: []string{"Function", "Compute", "Resource"},
GeoLocation: voc.GeoLocation{
Region: d.awsConfig.cfg.Region,
},
},
}})
}
return
}
// getBootLog checks if boot logging is enabled
// Currently there is no option to find out if any logs are enabled -> Assign default zero values
func (*computeDiscovery) getBootLog(_ *typesEC2.Instance) (l *voc.BootLogging) {
l = &voc.BootLogging{
Logging: &voc.Logging{
Auditing: nil,
LoggingService: nil,
Enabled: false,
RetentionPeriod: 0,
},
}
return
}
// getOSLog checks if OS logging is enabled
// Currently there is no option to find out if any logs are enabled -> Assign default zero values
func (*computeDiscovery) getOSLog(_ *typesEC2.Instance) (l *voc.OSLogging) {
l = &voc.OSLogging{
Logging: &voc.Logging{
Auditing: nil,
LoggingService: nil,
Enabled: false,
RetentionPeriod: 0,
},
}
return
}
// mapBlockStorageIDsOfVM returns block storages IDs by iterating the VMs block storages
func (*computeDiscovery) mapBlockStorageIDsOfVM(vm *typesEC2.Instance) (blockStorageIDs []voc.ResourceID) {
// Loop through mappings using an index, since BlockDeviceMappings is an array of a struct
// and not of a pointer; otherwise we would copy a lot of data
for i := range vm.BlockDeviceMappings {
mapping := &vm.BlockDeviceMappings[i]
blockStorageIDs = append(blockStorageIDs, voc.ResourceID(aws.ToString(mapping.Ebs.VolumeId)))
}
return
}
// getNetworkInterfacesOfVM returns the network interface IDs by iterating the VMs network interfaces
func (*computeDiscovery) getNetworkInterfacesOfVM(vm *typesEC2.Instance) (networkInterfaceIDs []voc.ResourceID) {
// Loop through mappings using an index, since is NetworkInterfaces an array of a struct
// and not of a pointer; otherwise we would copy a lot of data
for i := range vm.NetworkInterfaces {
ifc := &vm.NetworkInterfaces[i]
networkInterfaceIDs = append(networkInterfaceIDs, voc.ResourceID(aws.ToString(ifc.NetworkInterfaceId)))
}
return
}
// getNameOfVM returns the name if exists (i.e. a tag with key 'name' exists), otherwise instance ID is used
func (*computeDiscovery) getNameOfVM(vm *typesEC2.Instance) string {
for _, tag := range vm.Tags {
if aws.ToString(tag.Key) == "Name" {
return aws.ToString(tag.Value)
}
}
// If no tag with 'name' was found, return instanceId instead
return aws.ToString(vm.InstanceId)
}
// addARNToVM generates the ARN of a VM instance
func (d computeDiscovery) addARNToVM(vm *typesEC2.Instance) voc.ResourceID {
return voc.ResourceID("arn:aws:ec2:" +
d.awsConfig.cfg.Region + ":" +
aws.ToString(d.awsConfig.accountID) +
":instance/" +
aws.ToString(vm.InstanceId))
}