aboutsummaryrefslogtreecommitdiff
path: root/cloud/aws/aws.go
blob: 36ac338a5a34f3e27a60ba9e0c0805f44de14ad8 (plain)
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
package aws

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"

	"code.crute.us/mcrute/cloud-identity-broker/app/models"

	"code.crute.us/mcrute/golib/vault"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/sts"
)

// defaultRegion is the region where AWS currently has may authoritative
// service like IAM and ancillary auth services.
var defaultRegion = aws.String("us-east-1")

type Region struct {
	Name    string
	Enabled bool
}

type AWSClient interface {
	AssumeRole(string, *string) (*sts.Credentials, error)
	GetFederationURL(string, string) (string, error)
	GetRegionList() ([]*Region, error)
}

// account models the account configuration stored in Vault for an AWS account
// with assumable roles that are stored within a kv JSON record.
type account struct {
	AccessKeyId     string
	SecretAccessKey string
	Roles           map[string]struct {
		ARN        string
		ExternalId string
	}
}

type client struct {
	AccessKeyId                string
	SecretAccessKey            string
	ARN                        string
	ExternalId                 string
	ConsoleSessionDurationSecs int64
}

var _ AWSClient = (*client)(nil)

// NewAWSClientFromAccount returns a new AWSClient based on an account.
//
// An account is actually more accurately called an assumable role. Each
// account contains a vault material set path which is used to fetch all of the
// credentials for that AWS account and is filtered to one assumable role ARN
// which is used as the scope for this AWS client. Thus even if an account has
// multiple roles there must be one instance of the AWS client per account/role
// pair.
func NewAWSClientFromAccount(a *models.Account) (AWSClient, error) {
	var ac account
	if err := vault.GetVaultKeyStruct(a.VaultMaterial, &ac); err != nil {
		return nil, err
	}

	r, ok := ac.Roles[a.ShortName]
	if !ok {
		return nil, fmt.Errorf("No roles for account %s in vault response", a.ShortName)
	}

	return &client{
		AccessKeyId:                ac.AccessKeyId,
		SecretAccessKey:            ac.SecretAccessKey,
		ARN:                        r.ARN,
		ExternalId:                 r.ExternalId,
		ConsoleSessionDurationSecs: a.ConsoleSessionDurationSecs(),
	}, nil
}

// ValidateVaultMaterial is used to check that a Vault material can be accessed
// and that the shape of that material is correct for an AWS access key and
// role list.
//
// This should be used for admission control for the creation of new accounts.
func ValidateVaultMaterial(m string) error {
	var ac account
	if err := vault.GetVaultKeyStruct(m, &ac); err != nil {
		return fmt.Errorf("Unable to access vault material: %w", err)
	}

	if ac.AccessKeyId == "" {
		return fmt.Errorf("AccessKeyId is empty")
	}

	if ac.SecretAccessKey == "" {
		return fmt.Errorf("SecretAccessKey is empty")
	}

	if len(ac.Roles) == 0 {
		return fmt.Errorf("No roles specified")
	}

	for k, r := range ac.Roles {
		if r.ARN == "" {
			return fmt.Errorf("ARN for role %s is empty", k)
		}
		if r.ExternalId == "" {
			return fmt.Errorf("ExternalId for role %s is empty", k)
		}
	}

	return nil
}

// AssumeRole uses an IAM user credential with higher privilege to assume a
// role in an AWS account and region. It returns the STS credentials.
//
// Not all credentials work for all regions. For newer regions and opt-in
// regions AWS has been siloing assumed role credentials to that region so it's
// important to use the correct regional endpoint to fetch the credentials.
//
// Note that this is not simply a passthrough to Vault's AWS backend because
// the Vault backend works by assuming roles and when assuming roles with an
// assumed role AWS limits the chained role lifetime to 1 hour which doesn't
// work depending on how the upstream web application tied to this client
// works. This method instead uses a long-lived IAM user credential to assume a
// role, which has a limited lifetime which is typically greater than 1 hour.
func (a *client) AssumeRole(user string, region *string) (*sts.Credentials, error) {
	if region != nil && *region == "global" {
		region = nil
	}

	c := sts.New(session.New(&aws.Config{
		Region: region,
		Credentials: credentials.NewStaticCredentials(
			a.AccessKeyId,
			a.SecretAccessKey,
			"",
		),
	}))
	result, err := c.AssumeRole(&sts.AssumeRoleInput{
		ExternalId:      aws.String(a.ExternalId),
		RoleArn:         aws.String(a.ARN),
		RoleSessionName: aws.String(user),
		DurationSeconds: aws.Int64(a.ConsoleSessionDurationSecs),
	})
	if err != nil {
		return nil, err
	}

	return result.Credentials, nil
}

// GetRegionList returns all of the EC2 regions that are enabled for an
// account.
//
// All regions should return the same answer to this query so just send it to
// the default region.
func (a *client) GetRegionList() ([]*Region, error) {
	r, err := a.AssumeRole("region-list", defaultRegion)
	if err != nil {
		return nil, err
	}

	ec2c := ec2.New(session.New(&aws.Config{
		Region: defaultRegion,
		Credentials: credentials.NewStaticCredentials(
			*r.AccessKeyId,
			*r.SecretAccessKey,
			*r.SessionToken,
		),
	}))

	ro, err := ec2c.DescribeRegions(&ec2.DescribeRegionsInput{AllRegions: aws.Bool(true)})
	if err != nil {
		return nil, err
	}

	out := []*Region{}
	for _, r := range ro.Regions {
		out = append(out, &Region{
			Name:    *r.RegionName,
			Enabled: (*r.OptInStatus != "not-opted-in"),
		})
	}

	return out, nil
}

// GetFederationURL assumes a role and returns a URL that can be used to login
// to the AWS console for that role.
//
// This URL can be used for any region but the endpoints to return the URL only
// work in us-east-1.
func (a *client) GetFederationURL(user string, issuerEndpoint string) (string, error) {
	r, err := a.AssumeRole(user, defaultRegion)
	if err != nil {
		return "", err
	}

	sp, _ := json.Marshal(map[string]string{
		"sessionId":    *r.AccessKeyId,
		"sessionKey":   *r.SecretAccessKey,
		"sessionToken": *r.SessionToken,
	})

	client := &http.Client{}
	fedResp, err := client.Do(&http.Request{
		Method: http.MethodGet,
		URL: &url.URL{
			Scheme: "https",
			Host:   "signin.aws.amazon.com",
			Path:   "/federation",
			RawQuery: url.Values{
				"Action":          []string{"getSigninToken"},
				"Session":         []string{string(sp)},
				"SessionDuration": []string{strconv.FormatInt(a.ConsoleSessionDurationSecs, 10)},
			}.Encode(),
		},
	})
	if err != nil {
		return "", err
	}

	if fedResp.StatusCode != 200 {
		return "", fmt.Errorf("federation endpoint returned HTTP %d", fedResp.StatusCode)
	}

	body, err := ioutil.ReadAll(fedResp.Body)
	if err != nil {
		return "", err
	}

	var fedData map[string]string
	if err = json.Unmarshal(body, &fedData); err != nil {
		return "", err
	}

	u, _ := url.Parse("https://signin.aws.amazon.com/federation")
	u.RawQuery = url.Values{
		"Action":      []string{"login"},
		"Issuer":      []string{issuerEndpoint},
		"Destination": []string{"https://console.aws.amazon.com/"},
		"SigninToken": []string{fedData["SigninToken"]},
	}.Encode()

	return u.String(), nil
}