-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
main.go
376 lines (320 loc) · 10.8 KB
/
main.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
/*
Copyright 2023 Gravitational, Inc.
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.
*/
package main
import (
"crypto/sha256"
"errors"
"fmt"
"log"
"math"
"math/rand"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/endpoints"
awsrequest "github.com/aws/aws-sdk-go/aws/request"
awssession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
const (
scanDuration = time.Hour * 24 * 30
indexName = "timesearchV2"
)
func main() {
params, err := getParams()
if err != nil {
log.Fatal(err)
}
// sets of unique users for calculating MAU
state := &trackedState{
ssh: make(map[string]struct{}),
kube: make(map[string]struct{}),
db: make(map[string]struct{}),
app: make(map[string]struct{}),
desktop: make(map[string]struct{}),
}
fmt.Println("Gathering data, this may take a moment")
// Assume a base read capacity of 25 units per second to start off.
// If this is too high and we encounter throttling that could impede Teleport, it will be adjusted automatically.
limiter := newAdaptiveRateLimiter(25)
// Check the package name for one of the boring primitives. If the package
// path is from BoringCrypto, we know this binary was compiled using
// `GOEXPERIMENT=boringcrypto`.
hash := sha256.New()
useFIPSEndpoint := endpoints.FIPSEndpointStateUnset
if reflect.TypeOf(hash).Elem().PkgPath() == "crypto/internal/boring" {
useFIPSEndpoint = endpoints.FIPSEndpointStateEnabled
}
// create an AWS session using default SDK behavior, i.e. it will interpret
// the environment and ~/.aws directory just like an AWS CLI tool would:
session, err := awssession.NewSessionWithOptions(awssession.Options{
SharedConfigState: awssession.SharedConfigEnable,
Config: aws.Config{
Retryer: limiter,
Region: aws.String(params.awsRegion),
CredentialsChainVerboseErrors: aws.Bool(true),
EC2MetadataEnableFallback: aws.Bool(false),
UseFIPSEndpoint: useFIPSEndpoint,
},
})
if err != nil {
log.Fatal(err)
}
// Reduce internal retry count so throttling errors bubble up to our rate limiter with less delay.
svc := dynamodb.New(session)
for _, date := range daysBetween(params.startDate, params.startDate.Add(scanDuration)) {
err := scanDay(svc, limiter, params.tableName, date, state)
if err != nil {
log.Fatal(err)
}
}
startDate := params.startDate.Format(time.DateOnly)
endDate := params.startDate.Add(scanDuration).Format(time.DateOnly)
fmt.Printf("Monthly active users by product during the period %v to %v:\n", startDate, endDate)
displayProductResults("Server Access", state.ssh, params.showUsers)
displayProductResults("Kubernetes Access", state.kube, params.showUsers)
displayProductResults("Database Access", state.db, params.showUsers)
displayProductResults("Application Access", state.app, params.showUsers)
displayProductResults("Desktop Access", state.desktop, params.showUsers)
}
func displayProductResults(name string, users map[string]struct{}, showUsers bool) {
fmt.Printf(" %v: %v", name, len(users))
if showUsers && len(users) > 0 {
userList := make([]string, 0, len(users))
for user := range users {
userList = append(userList, user)
}
fmt.Printf(" (%v)", strings.Join(userList, ", "))
}
fmt.Print("\n")
}
// scanDay scans a single day of events from the audit log table.
func scanDay(svc *dynamodb.DynamoDB, limiter *adaptiveRateLimiter, tableName string, date string, state *trackedState) error {
attributes := map[string]interface{}{
":date": date,
":e1": "session.start",
":e2": "db.session.start",
":e3": "app.session.start",
":e4": "windows.desktop.session.start",
":e5": "kube.request",
}
attributeValues, err := dynamodbattribute.MarshalMap(attributes)
if err != nil {
return err
}
var paginationKey map[string]*dynamodb.AttributeValue
pageCount := 1
outer:
for {
fmt.Printf(" scanning date %v page %v...\n", date, pageCount)
scanOut, err := svc.Query(&dynamodb.QueryInput{
TableName: aws.String(tableName),
IndexName: aws.String(indexName),
KeyConditionExpression: aws.String("CreatedAtDate = :date"),
ExpressionAttributeValues: attributeValues,
FilterExpression: aws.String("EventType IN (:e1, :e2, :e3, :e4, :e5)"),
ExclusiveStartKey: paginationKey,
ReturnConsumedCapacity: aws.String(dynamodb.ReturnConsumedCapacityTotal),
// We limit the number of items returned to the current capacity to minimize any usage spikes
// that could affect Teleport as RCUs may be consumed for multiple seconds if the response is large, slowing down Teleport significantly.
Limit: aws.Int64(int64(limiter.currentCapacity())),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == dynamodb.ErrCodeProvisionedThroughputExceededException {
fmt.Println(" throttled by DynamoDB, adjusting request rate...")
limiter.reportThrottleError()
continue outer
}
return err
}
pageCount++
limiter.wait(*scanOut.ConsumedCapacity.CapacityUnits)
err = reduceEvents(scanOut.Items, state)
if err != nil {
return err
}
paginationKey = scanOut.LastEvaluatedKey
if paginationKey == nil {
break
}
}
return nil
}
type event struct {
EventType string
FieldsMap struct {
User string
KubernetesCluster *string `dynamodbav:"kubernetes_cluster,omitempty"`
}
}
// applies a set of scanned raw events onto the tracked state.
func reduceEvents(rawEvents []map[string]*dynamodb.AttributeValue, state *trackedState) error {
for _, rawEvent := range rawEvents {
var event event
err := dynamodbattribute.UnmarshalMap(rawEvent, &event)
if err != nil {
log.Fatal(err)
}
var set map[string]struct{}
switch event.EventType {
case "kube.request":
set = state.kube
case "session.start":
set = state.ssh
if event.FieldsMap.KubernetesCluster != nil {
set = state.kube
}
case "db.session.start":
set = state.db
case "app.session.start":
set = state.app
case "windows.desktop.session.start":
set = state.desktop
default:
return errors.New("unexpected event type: " + event.EventType)
}
set[event.FieldsMap.User] = struct{}{}
}
return nil
}
// daysBetween returns a list of all dates between `start` and `end` in the format `yyyy-mm-dd`.
func daysBetween(start, end time.Time) []string {
var days []string
oneDay := time.Hour * time.Duration(24)
startDay := daysSinceEpoch(start)
endDay := daysSinceEpoch(end)
for startDay < endDay {
days = append(days, start.Format(time.DateOnly))
startDay++
start = start.Add(oneDay)
}
return days
}
func daysSinceEpoch(timestamp time.Time) int64 {
return timestamp.Unix() / (60 * 60 * 24)
}
// trackedState is a set of unique users for each protocol.
type trackedState struct {
ssh map[string]struct{}
kube map[string]struct{}
db map[string]struct{}
app map[string]struct{}
desktop map[string]struct{}
}
type params struct {
tableName string
awsRegion string
showUsers bool
startDate time.Time
}
func getParams() (params, error) {
tableName := os.Getenv("TABLE_NAME")
awsRegion := os.Getenv("AWS_REGION")
showUsersStr := os.Getenv("SHOW_USERS")
startDate := os.Getenv("START_DATE")
if showUsersStr == "" {
showUsersStr = "false"
}
showUsers, err := strconv.ParseBool(showUsersStr)
if err != nil {
return params{}, err
}
if tableName == "" {
return params{}, errors.New("TABLE_NAME environment variable is required")
}
if awsRegion == "" {
return params{}, errors.New("AWS_REGION environment variable is required")
}
var timestamp time.Time
if startDate == "" {
timestamp = time.Now().UTC().Add(-scanDuration)
} else {
timestamp, err = time.Parse(time.DateOnly, startDate)
if err != nil {
return params{}, err
}
}
return params{
tableName: tableName,
awsRegion: awsRegion,
showUsers: showUsers,
startDate: timestamp,
}, nil
}
// adaptiveRateLimiter is a rate limiter that dynamically adjusts its request rate based on throttling errors.
// This unusual strategy was chosen since we cannot know how much free read capacity is available.
//
// This rate limiter progressively increases the request rate when it is not throttled for a longer period of time, and decreases it when it is.
//
// This will never cause actual interrupts to Teleport since the AWS SDK there will retry generously to smooth over
// any possible retries caused by us. The important element is that we back off as soon as we notice this which
// allows Teleport to success eventually.
type adaptiveRateLimiter struct {
permitCapacity float64
low float64
high float64
}
func (a *adaptiveRateLimiter) reportThrottleError() {
a.high = a.permitCapacity
if math.Abs(a.high-a.low)/a.high < 0.05 {
a.low = a.high / 2
}
old := a.permitCapacity
capacity := math.Abs(a.high-a.low)/2 + a.low
// A capacity of zero is not valid and results in requests to be rejected.
if capacity < 1 {
capacity = 1.0
}
a.permitCapacity = capacity
fmt.Printf(" throttled by DynamoDB. adjusting request rate from %v RCUs to %v RCUs\n", int(old), int(a.permitCapacity))
}
func (a *adaptiveRateLimiter) wait(permits float64) {
durationToWait := time.Duration(permits / a.permitCapacity * float64(time.Second))
time.Sleep(durationToWait)
if rand.Intn(10) == 0 {
a.adjustUp()
}
}
func (a *adaptiveRateLimiter) adjustUp() {
a.low = a.permitCapacity
if math.Abs(a.high-a.low)/a.low < 0.05 {
a.high = a.low * 2
}
old := a.permitCapacity
a.permitCapacity = math.Abs(a.high-a.low)/2 + a.low
fmt.Printf(" no throttling for a while. adjusting request rate from %v RCUs to %v RCUs\n", int(old), int(a.permitCapacity))
}
func (a *adaptiveRateLimiter) currentCapacity() float64 {
return a.permitCapacity
}
func (a *adaptiveRateLimiter) RetryRules(r *awsrequest.Request) time.Duration {
return 0
}
func (a *adaptiveRateLimiter) ShouldRetry(*awsrequest.Request) bool {
return false
}
func (a *adaptiveRateLimiter) MaxRetries() int {
return 0
}
func newAdaptiveRateLimiter(permitsPerSecond float64) *adaptiveRateLimiter {
fmt.Printf(" setting initial read rate to %v RCUs\n", int(permitsPerSecond))
return &adaptiveRateLimiter{
permitCapacity: permitsPerSecond,
high: 250,
}
}