/
analyze.go
149 lines (129 loc) · 4.19 KB
/
analyze.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
/*
Copyright © 2022 The K9CLI Authors
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 core
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
)
type analyzeRequestBody struct {
CustomerID string `json:"customerId"`
Account string `json:"accountId"`
}
// Example:
// {"customerId": "C10000", "accountId": "139710491120", "executionId": "ondemand-C10000-139710491120-2022-09-15_TV49"}
type analyzeResponseBody struct {
CustomerID string `json:"customerId"`
Account string `json:"accountId"`
ExecutionID string `json:"executionId"`
}
func AnalyzeAccount(o io.Writer, cfg aws.Config, apiHost, customerID, account string) error {
analysisUrl := &url.URL{
Scheme: "https",
Host: apiHost,
Path: fmt.Sprintf("/customer/%s/account/%s/analysis", customerID, account),
}
requestBody := analyzeRequestBody{
CustomerID: customerID,
Account: account,
}
requestBodyBytes, _ := json.Marshal(requestBody)
request, err := http.NewRequest("POST", analysisUrl.String(), bytes.NewBuffer(requestBodyBytes))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not build API request: %s\n", err)
return err
}
now := time.Now()
request.Header.Set("Date", now.Format(time.RFC3339))
request.Header.Set("Content-Type", "application/json")
if err != signApiRequest(cfg, request, now) {
fmt.Fprintf(os.Stderr, "Could not sign API request: %s\n", err)
return err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not execute API request: %s\n", err)
return err
} else {
defer response.Body.Close()
}
body, _ := ioutil.ReadAll(response.Body)
responseBodyStr := string(body)
if response.StatusCode == http.StatusOK || response.StatusCode == http.StatusAccepted {
analyzeResponse := analyzeResponseBody{}
if err != json.Unmarshal(body, &analyzeResponse) {
fmt.Fprintf(os.Stderr, "Could not deserialize API response: %s\n", responseBodyStr)
return err
}
fmt.Fprintf(o, "Started analysis for %s account %s with execution ID: %s\n",
customerID,
account,
analyzeResponse.ExecutionID)
} else {
fmt.Fprintf(os.Stderr, "Analyze API Response Status: %s\n", response.Status)
fmt.Fprintf(os.Stderr, "Could not start analysis for %s account %s. API Response: %s\n",
customerID,
account,
responseBodyStr)
}
return nil
}
// Sign a request to the k9 Security AWS API gateway endpoint with an AWS v4 signature
// using the aws-sdk-go-v2 v4.SignHTTP function.
//
// The request should be fully-built and ready to send to the gateway.
//
// The provided request will be modified in place.
func signApiRequest(cfg aws.Config, request *http.Request, signingTime time.Time) error {
ctx := context.TODO()
credentials, err := cfg.Credentials.Retrieve(ctx)
if err != nil {
return err
}
hash, err := createPayloadHash(request)
if err != nil {
return err
}
signer := v4.NewSigner()
if err != signer.SignHTTP(ctx, credentials, request, hash, "execute-api", cfg.Region, signingTime) {
return err
}
// fmt.Printf("Authorization: %s\n", request.Header.Get("Authorization"))
return err
}
// Create a hex-encoded SHA256 hash of the request payload. Use when calculating an AWS v4 signature.
func createPayloadHash(req *http.Request) (string, error) {
// from https://github.com/yuizho/salon/blob/a159bcfeb263cb6502403f682c138286a2d7bb1f/backend/lambda/mutate-user/appsync/client.go
body, err := req.GetBody()
if err != nil {
return "", err
}
var buf bytes.Buffer
_, err = buf.ReadFrom(body)
if err != nil {
return "", err
}
b := sha256.Sum256(buf.Bytes())
return hex.EncodeToString(b[:]), nil
}