-
Notifications
You must be signed in to change notification settings - Fork 14
/
awsRole.go
371 lines (353 loc) · 10.8 KB
/
awsRole.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
package main
import (
"context"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/Cloud-Foundations/keymaster/lib/certgen"
"github.com/Cloud-Foundations/keymaster/lib/instrumentedwriter"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/organizations"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
const (
awsAccountListInterval = time.Minute * 5
)
type assumeRoleCredentialsProvider struct {
credentials aws.Credentials
roleArn *string
stsClient *sts.Client
}
type getCallerIdentityResult struct {
Arn string
}
type getCallerIdentityResponse struct {
GetCallerIdentityResult getCallerIdentityResult
}
type parsedArnType struct {
parsedArn arn.ARN
role string
}
func awsListAccounts(ctx context.Context, orgClient *organizations.Client) (
map[string]struct{}, error) {
output, err := orgClient.ListAccounts(ctx,
&organizations.ListAccountsInput{})
if err != nil {
return nil, err
}
list := make(map[string]struct{}, len(output.Accounts))
for _, account := range output.Accounts {
list[*account.Id] = struct{}{}
}
return list, nil
}
func getCallerIdentity(header http.Header,
validator func(presignedUrl string) (*url.URL, error)) (
*parsedArnType, error) {
claimedArn := header.Get("claimed-arn")
presignedMethod := header.Get("presigned-method")
presignedUrl := header.Get("presigned-url")
if claimedArn == "" || presignedUrl == "" || presignedMethod == "" {
return nil, fmt.Errorf("missing presigned request data")
}
validatedUrl, err := validator(presignedUrl)
if err != nil {
return nil, err
}
presignedUrl = validatedUrl.String()
validateReq, err := http.NewRequest(presignedMethod, presignedUrl, nil)
if err != nil {
return nil, err
}
validateResp, err := http.DefaultClient.Do(validateReq)
if err != nil {
return nil, err
}
defer validateResp.Body.Close()
if validateResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("verification request failed")
}
body, err := ioutil.ReadAll(validateResp.Body)
if err != nil {
return nil, err
}
var callerIdentity getCallerIdentityResponse
if err := xml.Unmarshal(body, &callerIdentity); err != nil {
return nil, err
}
parsedArn, err := arn.Parse(callerIdentity.GetCallerIdentityResult.Arn)
if err != nil {
return nil, err
}
// Normalise to the actual role ARN, rather than an ARN showing how the
// credentials were obtained. This mirrors the way AWS policy documents are
// written.
parsedArn.Region = ""
parsedArn.Service = "iam"
splitResource := strings.Split(parsedArn.Resource, "/")
if len(splitResource) < 2 || splitResource[0] != "assumed-role" {
return nil, fmt.Errorf("invalid resource: %s", parsedArn.Resource)
}
parsedArn.Resource = "role/" + splitResource[1]
if parsedArn.String() != claimedArn {
return nil, fmt.Errorf("validated ARN: %s != claimed ARN: %s",
parsedArn.String(), claimedArn)
}
return &parsedArnType{
parsedArn: parsedArn,
role: splitResource[1],
}, nil
}
// validateStsPresignedUrl will validate if the URL is a valid AWS URL.
// It returns the parsed, validated URL so that the caller can rebuild the URL
// (to hopefully silence code security scanners which are dumb).
func validateStsPresignedUrl(presignedUrl string) (*url.URL, error) {
parsedPresignedUrl, err := url.Parse(presignedUrl)
if err != nil {
return nil, err
}
if parsedPresignedUrl.Scheme != "https" {
return nil, fmt.Errorf("invalid scheme: %s", parsedPresignedUrl.Scheme)
}
if parsedPresignedUrl.Path != "/" {
return nil, fmt.Errorf("invalid path: %s", parsedPresignedUrl.Path)
}
if !strings.HasPrefix(parsedPresignedUrl.RawQuery,
"Action=GetCallerIdentity&") {
return nil,
fmt.Errorf("invalid action: %s", parsedPresignedUrl.RawQuery)
}
splitHost := strings.Split(parsedPresignedUrl.Host, ".")
if len(splitHost) != 4 ||
splitHost[0] != "sts" ||
splitHost[2] != "amazonaws" ||
splitHost[3] != "com" {
return nil, fmt.Errorf("malformed presigned URL host")
}
return parsedPresignedUrl, nil
}
func (p *assumeRoleCredentialsProvider) Retrieve(ctx context.Context) (
aws.Credentials, error) {
if time.Until(p.credentials.Expires) > time.Minute {
return p.credentials, nil
}
output, err := p.stsClient.AssumeRole(ctx, &sts.AssumeRoleInput{
RoleArn: p.roleArn,
RoleSessionName: aws.String("keymaster"),
})
if err != nil {
return aws.Credentials{}, err
}
p.credentials = aws.Credentials{
AccessKeyID: *output.Credentials.AccessKeyId,
CanExpire: true,
Expires: *output.Credentials.Expiration,
SecretAccessKey: *output.Credentials.SecretAccessKey,
SessionToken: *output.Credentials.SessionToken,
}
return p.credentials, nil
}
func (state *RuntimeState) checkAwsRolesEnabled() bool {
if len(state.Config.AwsCerts.AllowedAccounts) > 0 {
return true
}
if state.Config.AwsCerts.ListAccountsRole != "" {
return true
}
return false
}
func (state *RuntimeState) configureAwsRoles() error {
if len(state.Config.AwsCerts.AllowedAccounts) > 0 {
state.Config.AwsCerts.allowedAccounts =
make(map[string]struct{})
for _, id := range state.Config.AwsCerts.AllowedAccounts {
if _, err := strconv.ParseUint(id, 10, 64); err != nil {
return fmt.Errorf("accountID: %s is not a number", id)
}
state.Config.AwsCerts.allowedAccounts[id] = struct{}{}
}
}
if state.Config.AwsCerts.ListAccountsRole != "" {
ctx := context.TODO()
awsConfig, err := awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithEC2IMDSRegion())
if err != nil {
return err
}
credsProvider := &assumeRoleCredentialsProvider{
roleArn: aws.String(state.Config.AwsCerts.ListAccountsRole),
stsClient: sts.NewFromConfig(awsConfig),
}
awsConfig, err = awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithEC2IMDSRegion(),
awsconfig.WithCredentialsProvider(credsProvider))
if err != nil {
return err
}
orgClient := organizations.NewFromConfig(awsConfig)
state.Config.AwsCerts.organisationAccounts, err =
awsListAccounts(ctx, orgClient)
if err != nil {
return err
}
go state.refreshAwsAccounts(ctx, orgClient)
}
return nil
}
func (state *RuntimeState) checkAwsAccountAllowed(accountId string) bool {
if _, ok := state.Config.AwsCerts.allowedAccounts[accountId]; ok {
return true
}
if _, ok := state.Config.AwsCerts.organisationAccounts[accountId]; ok {
return true
}
if _, ok := state.Config.AwsCerts.allowedAccounts["*"]; ok {
return true
}
return false
}
func (state *RuntimeState) refreshAwsAccounts(ctx context.Context,
orgClient *organizations.Client) {
for {
time.Sleep(awsAccountListInterval)
if list, err := awsListAccounts(ctx, orgClient); err != nil {
state.logger.Println(err)
} else {
state.Config.AwsCerts.organisationAccounts = list
}
}
}
func (state *RuntimeState) requestAwsRoleCertificateHandler(
w http.ResponseWriter, r *http.Request) {
state.logger.Debugln(1, "Entered requestAwsRoleCertificateHandler()")
if state.sendFailureToClientIfLocked(w, r) {
return
}
if r.Method != "POST" {
state.writeFailureResponse(w, r, http.StatusMethodNotAllowed, "")
return
}
// First extract and validate AWS credentials claim.
callerArn, err := getCallerIdentity(r.Header, validateStsPresignedUrl)
if err != nil {
state.logger.Println(err)
state.writeFailureResponse(w, r, http.StatusUnauthorized,
"verification request failed")
return
}
if !state.checkAwsAccountAllowed(callerArn.parsedArn.AccountID) {
state.logger.Printf("AWS account: %s not allowed\n",
callerArn.parsedArn.AccountID)
state.writeFailureResponse(w, r, http.StatusUnauthorized,
"AWS account not allowed")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
state.logger.Println(err)
state.writeFailureResponse(w, r, http.StatusInternalServerError,
"error reading body")
return
}
// Now extract the public key PEM data.
block, _ := pem.Decode(body)
if block == nil {
state.logger.Println("unable to decode PEM block")
state.writeFailureResponse(w, r, http.StatusBadRequest,
"invalid PEM block")
return
}
if block.Type != "PUBLIC KEY" {
state.logger.Printf("unsupport PEM type: %s\n", block.Type)
state.writeFailureResponse(w, r, http.StatusBadRequest,
"unsupported PEM type")
return
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
state.logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "invalid DER")
return
}
strong, err := certgen.ValidatePublicKeyStrength(pub)
if err != nil {
state.logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest,
"cannot check key strength")
return
}
if !strong {
state.writeFailureResponse(w, r, http.StatusBadRequest, "key too weak")
return
}
certDER, commonName, err := state.generateRoleCert(pub, callerArn)
if err != nil {
state.logger.Println(err)
state.writeFailureResponse(w, r, http.StatusInternalServerError,
"cannot generate certificate")
return
}
w.(*instrumentedwriter.LoggingWriter).SetUsername(commonName)
pem.Encode(w, &pem.Block{Bytes: certDER, Type: "CERTIFICATE"})
}
// Returns certificate DER and CommonName.
func (state *RuntimeState) generateRoleCert(publicKey interface{},
callerArn *parsedArnType) ([]byte, string, error) {
commonName := fmt.Sprintf("aws:iam:%s:%s",
callerArn.parsedArn.AccountID, callerArn.role)
subject := pkix.Name{
CommonName: commonName,
Organization: []string{"keymaster"},
}
arnUrl, err := url.Parse(callerArn.parsedArn.String())
if err != nil {
return nil, "", err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, "", err
}
now := time.Now()
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
NotBefore: now,
NotAfter: now.Add(time.Hour * 24),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
IsCA: false,
URIs: []*url.URL{arnUrl},
}
caCert, err := x509.ParseCertificate(state.caCertDer)
if err != nil {
return nil, "", err
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, caCert,
publicKey, state.Signer)
if err != nil {
return nil, "", err
}
state.logger.Printf("Generated x509 Certificate for ARN=`%s`, expires=%s",
callerArn.parsedArn.String(), template.NotAfter)
metricLogCertDuration("x509", "granted",
float64(time.Until(template.NotAfter).Seconds()))
go func(username string, certType string) {
metricsMutex.Lock()
defer metricsMutex.Unlock()
certGenCounter.WithLabelValues(username, certType).Inc()
}(commonName, "x509")
return certDER, commonName, nil
}