forked from gravitational/teleport
/
policy.go
462 lines (415 loc) · 14.8 KB
/
policy.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
Copyright 2021 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 aws
import (
"context"
"encoding/json"
"fmt"
"net/url"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// Policy represents an AWS IAM policy.
type Policy struct {
// Name is the policy name.
Name string
// Description is the policy description.
Description string
// Tags is the policy tags.
Tags map[string]string
// PolicyDocument is the IAM policy document.
Document *PolicyDocument
}
// NewPolicy returns a new AWS IAM Policy.
func NewPolicy(name, description string, tags map[string]string, document *PolicyDocument) *Policy {
return &Policy{
Name: name,
Description: description,
Tags: tags,
Document: document,
}
}
// PolicyDocument represents a parsed AWS IAM policy document.
//
// Note that PolicyDocument and its Ensure/Delete methods are not currently
// goroutine-safe. To create a policy using AWS IAM API, dump the object to
// JSON format using json.Marshal.
type PolicyDocument struct {
// Version is the policy version.
Version string `json:"Version"`
// Statements is a list of the policy statements.
Statements []*Statement `json:"Statement"`
}
// Statement is a single AWS IAM policy statement.
type Statement struct {
// Effect is the statement effect such as Allow or Deny.
Effect string `json:"Effect"`
// Actions is a list of actions.
Actions SliceOrString `json:"Action"`
// Resources is a list of resources.
Resources SliceOrString `json:"Resource"`
}
// ParsePolicyDocument returns parsed AWS IAM policy document.
func ParsePolicyDocument(document string) (*PolicyDocument, error) {
// Policy document returned from AWS API can be URL-encoded:
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRolePolicy.html
decoded, err := url.QueryUnescape(document)
if err != nil {
return nil, trace.Wrap(err)
}
var parsed PolicyDocument
if err := json.Unmarshal([]byte(decoded), &parsed); err != nil {
return nil, trace.Wrap(err)
}
return &parsed, nil
}
// NewPolicyDocument returns new empty AWS IAM policy document.
func NewPolicyDocument(statements ...*Statement) *PolicyDocument {
return &PolicyDocument{
Version: PolicyVersion,
Statements: statements,
}
}
// Ensure ensures that the policy document contains the specified resource
// action.
//
// Returns true if the resource action was already a part of the policy and
// false otherwise.
func (p *PolicyDocument) Ensure(effect, action, resource string) bool {
for _, s := range p.Statements {
if s.Effect != effect {
continue
}
for _, a := range s.Actions {
if a != action {
continue
}
for _, r := range s.Resources {
// Resource action is already in the policy.
if r == resource {
return true
}
}
// Action exists but resource is missing.
s.Resources = append(s.Resources, resource)
return false
}
}
// No statement yet for this resource action, add it.
p.Statements = append(p.Statements, &Statement{
Effect: effect,
Actions: []string{action},
Resources: []string{resource},
})
return false
}
// Delete deletes the specified resource action from the policy.
func (p *PolicyDocument) Delete(effect, action, resource string) {
var statements []*Statement
for _, s := range p.Statements {
if s.Effect != effect {
statements = append(statements, s)
continue
}
var resources []string
for _, a := range s.Actions {
for _, r := range s.Resources {
if a != action || r != resource {
resources = append(resources, r)
}
}
}
if len(resources) != 0 {
statements = append(statements, &Statement{
Effect: s.Effect,
Actions: s.Actions,
Resources: resources,
})
}
}
p.Statements = statements
}
// Marshal formats the PolicyDocument in a "friendly" format, which can be
// presented to end users.
func (p *PolicyDocument) Marshal() (string, error) {
b, err := json.MarshalIndent(p, "", " ")
if err != nil {
return "", trace.Wrap(err)
}
return string(b), nil
}
// ForEach loops through each action and resource of each statement.
func (p *PolicyDocument) ForEach(fn func(effect, action, resource string)) {
for _, statement := range p.Statements {
for _, action := range statement.Actions {
for _, resource := range statement.Resources {
fn(statement.Effect, action, resource)
}
}
}
}
// SliceOrString defines a type that can be either a single string or a slice.
//
// For example, these types can be either a single string or a slice:
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html
type SliceOrString []string
// UnmarshalJSON implements json.Unmarshaller.
func (s *SliceOrString) UnmarshalJSON(bytes []byte) error {
// Check if input is a slice of strings.
var slice []string
sliceErr := json.Unmarshal(bytes, &slice)
if sliceErr == nil {
*s = slice
return nil
}
// Check if input is a single string.
var str string
strErr := json.Unmarshal(bytes, &str)
if strErr == nil {
*s = []string{str}
return nil
}
// Failed both format.
return trace.NewAggregate(sliceErr, strErr)
}
// MarshalJSON implements json.Marshaler.
func (s SliceOrString) MarshalJSON() ([]byte, error) {
switch len(s) {
case 0:
return json.Marshal([]string{})
case 1:
return json.Marshal(s[0])
default:
return json.Marshal([]string(s))
}
}
// Policies set of IAM Policy helper functions defined as an interface to make
// easier for other packages to mock and test with it.
type Policies interface {
// Upsert creates a new Policy or creates a Policy version if a policy with
// the same name already exists.
Upsert(ctx context.Context, policy *Policy) (arn string, err error)
// Retrieve retrieves a policy and its versions. If the tags list is
// present, the Policy should have all of them, otherwise an error is
// returned.
Retrieve(ctx context.Context, arn string, tags map[string]string) (policy *iam.Policy, policyVersions []*iam.PolicyVersion, err error)
// Attach attaches a policy with `arn` to the provided `identity`.
Attach(ctx context.Context, arn string, identity Identity) error
// AttachBoundary attaches a policy boundary with `arn` to the provided
// `identity`.
AttachBoundary(ctx context.Context, arn string, identity Identity) error
}
// policies default implementation of the policies functions.
type policies struct {
// partitionID is the partition ID.
partitionID string
// accountID current AWS account ID.
accountID string
// iamClient already initialized IAM client.
iamClient iamiface.IAMAPI
}
// NewPolicies creates new instance of Policies using the provided
// identity, partitionID and IAM client.
func NewPolicies(partitionID string, accountID string, iamClient iamiface.IAMAPI) Policies {
return &policies{
partitionID: partitionID,
accountID: accountID,
iamClient: iamClient,
}
}
// Upsert creates a new Policy or creates a Policy version if a policy with the
// same name already exists.
//
// Since policies can have a limited number of versions, we need to delete a
// policy version (if the limit is reached) and create a new version. Check the
// constant `maxPolicyVersions` for reference.
//
// Requires the following AWS permissions to be performed:
// * All permissions required to run `Retrieve` function;
// * `iam:CreatePolicy`: wildcard ("*") or policy that will be created;
// * `iam:DeletePolicyVersion`: wildcard ("*") or policy that will be created;
// * `iam:CreatePolicyVersion`: wildcard ("*") or policy that will be created;
func (p *policies) Upsert(ctx context.Context, policy *Policy) (string, error) {
policyARN := fmt.Sprintf("arn:%s:iam::%s:policy/%s", p.partitionID, p.accountID, policy.Name)
encodedPolicyDocument, err := json.Marshal(policy.Document)
if err != nil {
return "", trace.Wrap(err)
}
// Retrieve policy versions.
_, versions, err := p.Retrieve(ctx, policyARN, policy.Tags)
if err != nil && !trace.IsNotFound(err) {
return "", trace.Wrap(err)
}
// Convert tags into IAM policy tags.
policyTags := make([]*iam.Tag, 0, len(policy.Tags))
for key, value := range policy.Tags {
policyTags = append(policyTags, &iam.Tag{Key: aws.String(key), Value: aws.String(value)})
}
// If no versions were found, we need to create a new policy.
if trace.IsNotFound(err) {
resp, err := p.iamClient.CreatePolicyWithContext(ctx, &iam.CreatePolicyInput{
PolicyName: aws.String(policy.Name),
Description: aws.String(policy.Description),
PolicyDocument: aws.String(string(encodedPolicyDocument)),
Tags: policyTags,
})
if err != nil {
return "", trace.Wrap(ConvertIAMError(err))
}
log.Debugf("Created new policy %q with ARN %q", policy.Name, aws.StringValue(resp.Policy.Arn))
return aws.StringValue(resp.Policy.Arn), nil
}
// Check number of policy versions and delete one if necessary.
if len(versions) == maxPolicyVersions {
// Sort versions based on create date.
sort.Slice(versions, func(i, j int) bool {
return versions[i].CreateDate.Before(aws.TimeValue(versions[j].CreateDate))
})
// Find the first version that is not default.
var policyVersionID string
for _, policyVersion := range versions {
if !aws.BoolValue(policyVersion.IsDefaultVersion) {
policyVersionID = *policyVersion.VersionId
break
}
}
// Delete first non-default version.
_, err := p.iamClient.DeletePolicyVersionWithContext(ctx, &iam.DeletePolicyVersionInput{
PolicyArn: aws.String(policyARN),
VersionId: aws.String(policyVersionID),
})
if err != nil {
return "", trace.Wrap(ConvertIAMError(err))
}
log.Debugf("Max policy versions reached for policy %q, deleted policy version %q", policyARN, policyVersionID)
}
// Create new policy version.
createPolicyResp, err := p.iamClient.CreatePolicyVersionWithContext(ctx, &iam.CreatePolicyVersionInput{
PolicyArn: aws.String(policyARN),
PolicyDocument: aws.String(string(encodedPolicyDocument)),
SetAsDefault: aws.Bool(true),
})
if err != nil {
return "", trace.Wrap(ConvertIAMError(err))
}
log.Debugf("Created new policy version %q for %q", aws.StringValue(createPolicyResp.PolicyVersion.VersionId), policyARN)
return policyARN, nil
}
// Retrieve retrieves a policy and its versions. If the tags list is present,
// the Policy should have all of them, otherwise an error is returned.
//
// Requires the following AWS permissions to be performed:
// * `iam:GetPolicy`: wildcard ("*") or the policy to be retrieved;
// * `iam.ListPolicyVersions`: wildcard ("*") or the policy to be retrieved;
func (p *policies) Retrieve(ctx context.Context, arn string, tags map[string]string) (*iam.Policy, []*iam.PolicyVersion, error) {
getPolicyResp, err := p.iamClient.GetPolicyWithContext(ctx, &iam.GetPolicyInput{PolicyArn: aws.String(arn)})
if err != nil {
return nil, nil, trace.Wrap(ConvertIAMError(err))
}
for tagName, tagValue := range tags {
if !matchTag(getPolicyResp.Policy.Tags, tagName, tagValue) {
return nil, nil, trace.AlreadyExists("policy %q doesn't have the tag %s=%q", arn, tagName, tagValue)
}
}
resp, err := p.iamClient.ListPolicyVersionsWithContext(ctx, &iam.ListPolicyVersionsInput{PolicyArn: aws.String(arn)})
if err != nil {
return nil, nil, trace.Wrap(ConvertIAMError(err))
}
return getPolicyResp.Policy, resp.Versions, nil
}
// Attach attaches a policy with `arn` to the provided `identity`.
//
// Only `User` and `Role` identities supported.
//
// Requires the following AWS permissions to be performed:
// * `iam:AttachUserPolicy`: wildcard ("*") or provided user identity;
// * `iam:AttachRolePolicy`: wildcard ("*") or provided role identity;
func (p *policies) Attach(ctx context.Context, arn string, identity Identity) error {
switch identity.(type) {
case User, *User:
_, err := p.iamClient.AttachUserPolicyWithContext(ctx, &iam.AttachUserPolicyInput{
PolicyArn: aws.String(arn),
UserName: aws.String(identity.GetName()),
})
if err != nil {
return trace.Wrap(ConvertIAMError(err))
}
case Role, *Role:
_, err := p.iamClient.AttachRolePolicyWithContext(ctx, &iam.AttachRolePolicyInput{
PolicyArn: aws.String(arn),
RoleName: aws.String(identity.GetName()),
})
if err != nil {
return trace.Wrap(ConvertIAMError(err))
}
default:
return trace.BadParameter("policies can be attached to users and roles, received %q.", identity.GetType())
}
return nil
}
// AttachBoundary attaches a policy boundary with `arn` to the provided
// `identity`.
//
// Only `User` and `Role` identities supported.
//
// Requires the following AWS permissions to be performed:
// * `iam:PutUserPermissionsBoundary`: wildcard ("*") or provided user identity;
// * `iam:PutRolePermissionsBoundary`: wildcard ("*") or provided role identity;
func (p *policies) AttachBoundary(ctx context.Context, arn string, identity Identity) error {
switch identity.(type) {
case User, *User:
_, err := p.iamClient.PutUserPermissionsBoundaryWithContext(ctx, &iam.PutUserPermissionsBoundaryInput{
PermissionsBoundary: aws.String(arn),
UserName: aws.String(identity.GetName()),
})
if err != nil {
return trace.Wrap(ConvertIAMError(err))
}
case Role, *Role:
_, err := p.iamClient.PutRolePermissionsBoundaryWithContext(ctx, &iam.PutRolePermissionsBoundaryInput{
PermissionsBoundary: aws.String(arn),
RoleName: aws.String(identity.GetName()),
})
if err != nil {
return trace.Wrap(ConvertIAMError(err))
}
default:
return trace.BadParameter("boundary policies can be attached to users and roles, received %q.", identity.GetType())
}
return nil
}
// matchTag checks if tag name and value are present on the policy tags list.
func matchTag(policyTags []*iam.Tag, name, value string) bool {
for _, policyTag := range policyTags {
if *policyTag.Key == name && *policyTag.Value == value {
return true
}
}
return false
}
const (
// PolicyVersion is default IAM policy version.
PolicyVersion = "2012-10-17"
// EffectAllow is the Allow IAM policy effect.
EffectAllow = "Allow"
// EffectDeny is the Deny IAM policy effect.
EffectDeny = "Deny"
// maxPolicyVersions max number of policy versions a policy can have.
// Ref: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-versioning.html#version-limits
maxPolicyVersions = 5
)