-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
aws_verifier.go
277 lines (239 loc) · 8.18 KB
/
aws_verifier.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
/*
Copyright 2020 The Kubernetes 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 awsup
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/sts"
"k8s.io/kops/pkg/bootstrap"
nodeidentityaws "k8s.io/kops/pkg/nodeidentity/aws"
"k8s.io/kops/pkg/wellknownports"
)
type AWSVerifierOptions struct {
// NodesRoles are the IAM roles that worker nodes are permitted to have.
NodesRoles []string `json:"nodesRoles"`
// Region is the AWS region of the cluster.
Region string
}
type awsVerifier struct {
accountId string
partition string
opt AWSVerifierOptions
ec2 *ec2.EC2
sts *sts.STS
client http.Client
}
var _ bootstrap.Verifier = &awsVerifier{}
func NewAWSVerifier(opt *AWSVerifierOptions) (bootstrap.Verifier, error) {
config := aws.NewConfig().
WithCredentialsChainVerboseErrors(true).
WithRegion(opt.Region).
WithSTSRegionalEndpoint(endpoints.RegionalSTSEndpoint)
sess, err := session.NewSession(config)
if err != nil {
return nil, err
}
stsClient := sts.New(sess, config)
identity, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{})
if err != nil {
return nil, err
}
partition := strings.Split(aws.StringValue(identity.Arn), ":")[1]
ec2Client := ec2.New(sess, config)
return &awsVerifier{
accountId: aws.StringValue(identity.Account),
partition: partition,
opt: *opt,
ec2: ec2Client,
sts: stsClient,
client: http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
},
}, nil
}
type GetCallerIdentityResponse struct {
XMLName xml.Name `xml:"GetCallerIdentityResponse"`
GetCallerIdentityResult []GetCallerIdentityResult `xml:"GetCallerIdentityResult"`
ResponseMetadata []ResponseMetadata `xml:"ResponseMetadata"`
}
type GetCallerIdentityResult struct {
Arn string `xml:"Arn"`
UserId string `xml:"UserId"`
Account string `xml:"Account"`
}
type ResponseMetadata struct {
RequestId string `xml:"RequestId"`
}
func (a awsVerifier) VerifyToken(ctx context.Context, rawRequest *http.Request, token string, body []byte, useInstanceIDForNodeName bool) (*bootstrap.VerifyResult, error) {
if !strings.HasPrefix(token, AWSAuthenticationTokenPrefix) {
return nil, fmt.Errorf("incorrect authorization type")
}
token = strings.TrimPrefix(token, AWSAuthenticationTokenPrefix)
// We rely on the client and server using the same version of the same STS library.
stsRequest, _ := a.sts.GetCallerIdentityRequest(nil)
err := stsRequest.Sign()
if err != nil {
return nil, fmt.Errorf("creating identity request: %v", err)
}
stsRequest.HTTPRequest.Header = nil
tokenBytes, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return nil, fmt.Errorf("decoding authorization token: %v", err)
}
err = json.Unmarshal(tokenBytes, &stsRequest.HTTPRequest.Header)
if err != nil {
return nil, fmt.Errorf("unmarshalling authorization token: %v", err)
}
// Verify the token has signed the body content.
sha := sha256.Sum256(body)
if stsRequest.HTTPRequest.Header.Get("X-Kops-Request-SHA") != base64.RawStdEncoding.EncodeToString(sha[:]) {
return nil, fmt.Errorf("incorrect SHA")
}
requestBytes, _ := io.ReadAll(stsRequest.Body)
_, _ = stsRequest.Body.Seek(0, io.SeekStart)
if stsRequest.HTTPRequest.Header.Get("Content-Length") != strconv.Itoa(len(requestBytes)) {
return nil, fmt.Errorf("incorrect content-length")
}
response, err := a.client.Do(stsRequest.HTTPRequest)
if err != nil {
return nil, fmt.Errorf("sending STS request: %v", err)
}
if response != nil {
defer response.Body.Close()
}
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("reading STS response: %v", err)
}
if response.StatusCode != 200 {
return nil, fmt.Errorf("received status code %d from STS: %s", response.StatusCode, string(responseBody))
}
callerIdentity := GetCallerIdentityResponse{}
err = xml.NewDecoder(bytes.NewReader(responseBody)).Decode(&callerIdentity)
if err != nil {
return nil, fmt.Errorf("decoding STS response: %v", err)
}
if callerIdentity.GetCallerIdentityResult[0].Account != a.accountId {
return nil, fmt.Errorf("incorrect account %s", callerIdentity.GetCallerIdentityResult[0].Account)
}
arn := callerIdentity.GetCallerIdentityResult[0].Arn
parts := strings.Split(arn, ":")
if len(parts) != 6 {
return nil, fmt.Errorf("arn %q contains unexpected number of colons", arn)
}
if parts[0] != "arn" {
return nil, fmt.Errorf("arn %q doesn't start with \"arn:\"", arn)
}
if parts[1] != a.partition {
return nil, fmt.Errorf("arn %q not in partion %q", arn, a.partition)
}
if parts[2] != "iam" && parts[2] != "sts" {
return nil, fmt.Errorf("arn %q has unrecognized service", arn)
}
// parts[3] is region
// parts[4] is account
resource := strings.Split(parts[5], "/")
if resource[0] != "assumed-role" {
return nil, fmt.Errorf("arn %q has unrecognized type", arn)
}
if len(resource) < 3 {
return nil, fmt.Errorf("arn %q contains too few slashes", arn)
}
found := false
for _, role := range a.opt.NodesRoles {
if resource[1] == role {
found = true
break
}
}
if !found {
return nil, fmt.Errorf("arn %q does not contain acceptable node role", arn)
}
instanceID := resource[2]
instances, err := a.ec2.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: aws.StringSlice([]string{instanceID}),
})
if err != nil {
return nil, fmt.Errorf("describing instance for arn %q", arn)
}
if len(instances.Reservations) <= 0 || len(instances.Reservations[0].Instances) <= 0 {
return nil, fmt.Errorf("missing instance id: %s", instanceID)
}
if len(instances.Reservations[0].Instances) > 1 {
return nil, fmt.Errorf("found multiple instances with instance id: %s", instanceID)
}
instance := instances.Reservations[0].Instances[0]
addrs, err := GetInstanceCertificateNames(instances, useInstanceIDForNodeName)
if err != nil {
return nil, err
}
var challengeEndpoints []string
for _, nic := range instance.NetworkInterfaces {
if ip := aws.StringValue(nic.PrivateIpAddress); ip != "" {
challengeEndpoints = append(challengeEndpoints, net.JoinHostPort(ip, strconv.Itoa(wellknownports.NodeupChallenge)))
}
for _, a := range nic.PrivateIpAddresses {
if ip := aws.StringValue(a.PrivateIpAddress); ip != "" {
challengeEndpoints = append(challengeEndpoints, net.JoinHostPort(ip, strconv.Itoa(wellknownports.NodeupChallenge)))
}
}
for _, a := range nic.Ipv6Addresses {
if ip := aws.StringValue(a.Ipv6Address); ip != "" {
challengeEndpoints = append(challengeEndpoints, net.JoinHostPort(ip, strconv.Itoa(wellknownports.NodeupChallenge)))
}
}
}
if len(challengeEndpoints) == 0 {
return nil, fmt.Errorf("cannot determine challenge endpoint for instance id: %s", instanceID)
}
result := &bootstrap.VerifyResult{
NodeName: addrs[0],
CertificateNames: addrs,
ChallengeEndpoint: challengeEndpoints[0],
}
for _, tag := range instance.Tags {
tagKey := aws.StringValue(tag.Key)
if tagKey == nodeidentityaws.CloudTagInstanceGroupName {
result.InstanceGroupName = aws.StringValue(tag.Value)
}
}
return result, nil
}