Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[buddy] Truncate AssumeRole session name to API limits #45202

Merged
merged 6 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions api/proto/teleport/legacy/types/events/events.proto
Original file line number Diff line number Diff line change
Expand Up @@ -2745,6 +2745,13 @@ message AppSessionStart {
(gogoproto.embed) = true,
(gogoproto.jsontag) = ""
];

// AWS contains common AWS session information.
AWSSessionMetadata AWS = 9 [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make it more generic like

Suggested change
AWSSessionMetadata AWS = 9 [
AWSMetadata AWS = 9 [

I wonder what other fields can be added to AWSSessionMetadata, where AWSMetadata would be more flexible and in the case of other AWS fields not related to AWSSession context I think that the AWSMetadata it will be a better fit.

(gogoproto.nullable) = false,
(gogoproto.embed) = true,
(gogoproto.jsontag) = ""
];
}

// AppSessionEnd is emitted when an application session ends.
Expand Down Expand Up @@ -2874,6 +2881,13 @@ message AppSessionRequest {
];
}

// AWSSessionMetadata contains extra AWS metadata of an AWS session.
message AWSSessionMetadata {
// AWSRoleSessionName is used to specify the username when assuming the AWS
// IAM role.
string AWSRoleSessionName = 1 [(gogoproto.jsontag) = "aws_role_session_name,omitempty"];
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
}

// AWSRequestMetadata contains extra AWS metadata of an AppSessionRequest.
message AWSRequestMetadata {
// AWSRegion is the requested AWS region.
Expand Down
2,520 changes: 1,373 additions & 1,147 deletions api/types/events/events.pb.go

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,20 @@ username which you can search for to get the events history:

![CloudTrail](../../../../img/application-access/cloud-trail.png)

When you access an AWS application in a remote cluster, the remote cluster will
use the name `remote-<your-teleport-username>-<root-cluster-name>` for your
federated session. This is to prevent any naming collisions with users in the
remote cluster.

<Admonition type="warning" title="Long Usernames">
AWS imposes a 64-character limit on role session names. If a Teleport username
exceeds this length, Teleport generates a hash and combines it with the
original username to fit within the 64-character limit.
</Admonition>

You can also locate the federated username in the `aws_role_session_name` field
within the "App Session Start" (`app.session.start`) audit event.

## Troubleshooting

Read this section if you run into issues while following this guide.
Expand Down
17 changes: 17 additions & 0 deletions lib/auth/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
)

// NewWebSessionRequest defines a request to create a new user
Expand Down Expand Up @@ -623,6 +624,12 @@ func (a *Server) CreateAppSessionFromReq(ctx context.Context, req NewAppSessionR
AppPublicAddr: req.PublicAddr,
AppName: req.AppName,
},
AWSSessionMetadata: apievents.AWSSessionMetadata{
// Make an educated guess of the role session name. We have to
// guess here since this event is emitted on Auth instead of the
// App service that issues the actual AssumeRole call.
AWSRoleSessionName: guessAWSRoleSessionName(clusterName.GetClusterName(), req),
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
},
})
if err != nil {
log.WithError(err).Warn("Failed to emit app session start event")
Expand Down Expand Up @@ -792,3 +799,13 @@ func (a *Server) CreateSAMLIdPSession(ctx context.Context, req types.CreateSAMLI

return session, nil
}

// guessAWSRoleSessionName make an educated guess of the role session name.
func guessAWSRoleSessionName(localClusterName string, req NewAppSessionRequest) string {
// App service uses the Teleport username as the RoleSessionName.
user := req.User
if req.ClusterName != "" && localClusterName != req.ClusterName {
user = services.UsernameForRemoteCluster(req.User, localClusterName)
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
}
return awsutils.MaybeHashRoleSessionName(user)
}
33 changes: 33 additions & 0 deletions lib/auth/sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package auth

import (
"context"
"fmt"
"testing"
"time"

Expand Down Expand Up @@ -83,3 +84,35 @@ func TestServer_CreateWebSessionFromReq_deviceWebToken(t *testing.T) {
}
})
}

func Test_guessAWSRoleSessionName(t *testing.T) {
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
localClusterName := "teleport.abigcompany.com"

for _, tt := range []struct {
request NewAppSessionRequest
expected string
}{
{
request: NewAppSessionRequest{
NewWebSessionRequest: NewWebSessionRequest{
User: "[email protected]",
},
ClusterName: "teleport.abigcompany.com",
},
expected: "[email protected]",
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
},
{
request: NewAppSessionRequest{
NewWebSessionRequest: NewWebSessionRequest{
User: "[email protected]",
},
ClusterName: "leaf.teleport.abigcompany.com",
},
expected: "remote-raimundo.oliveir-8fe1f87e599b043e6a0108338feee3f111e9c1e4",
},
} {
t.Run(fmt.Sprintf("%s@%s", tt.request.User, tt.request.ClusterName), func(t *testing.T) {
require.Equal(t, tt.expected, guessAWSRoleSessionName(localClusterName, tt.request))
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
})
}
}
2 changes: 1 addition & 1 deletion lib/srv/app/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (c *cloud) getAWSSigninToken(ctx context.Context, req *AWSSigninRequest, en
options = append(options, func(creds *stscreds.AssumeRoleProvider) {
// Setting role session name to Teleport username will allow to
// associate CloudTrail events with the Teleport user.
creds.RoleSessionName = req.Identity.Username
creds.RoleSessionName = awsutils.MaybeHashRoleSessionName(req.Identity.Username)

// Setting web console session duration through AssumeRole call for AWS
// sessions with temporary credentials.
Expand Down
37 changes: 35 additions & 2 deletions lib/utils/aws/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ package aws
import (
"bytes"
"context"
"crypto/sha1"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"net/textproto"
"sort"
Expand All @@ -33,7 +36,6 @@ import (
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"

apievents "github.com/gravitational/teleport/api/types/events"
apiawsutils "github.com/gravitational/teleport/api/utils/aws"
Expand Down Expand Up @@ -68,6 +70,10 @@ const (
AmzJSON1_0 = "application/x-amz-json-1.0"
// AmzJSON1_1 is an AWS Content-Type header that indicates the media type is JSON.
AmzJSON1_1 = "application/x-amz-json-1.1"

// MaxRoleSessionName is the maximum length of the role session name used by the AssumeRole call.
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html
MaxRoleSessionName = 64
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: just to make it explicit that this is not count but name length.

Suggested change
MaxRoleSessionName = 64
MaxRoleSessionNameLength = 64

)

// SigV4 contains parsed content of the AWS Authorization header.
Expand Down Expand Up @@ -249,7 +255,7 @@ func FilterAWSRoles(arns []string, accountID string) (result Roles) {
for _, roleARN := range arns {
parsed, err := ParseRoleARN(roleARN)
if err != nil {
logrus.Warnf("skipping invalid AWS role ARN: %v", err)
slog.WarnContext(context.Background(), "Skipping invalid AWS role ARN.", "error", err)
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
continue
}
if accountID != "" && parsed.AccountID != accountID {
Expand Down Expand Up @@ -484,3 +490,30 @@ func iamResourceARN(partition, accountID, resourceType, resourceName string) str
Resource: fmt.Sprintf("%s/%s", resourceType, resourceName),
}.String()
}

// MaybeHashRoleSessionName truncates the role session name and adds a hash
// when the original role session name is greater than AWS character limit
// (64).
func MaybeHashRoleSessionName(roleSessionName string) (ret string) {
if len(roleSessionName) <= MaxRoleSessionName {
return roleSessionName
}

hash := sha1.New()
hash.Write([]byte(roleSessionName))
hex := hex.EncodeToString(hash.Sum(nil))
greedy52 marked this conversation as resolved.
Show resolved Hide resolved

// "1" for the delimiter.
keepPrefixIndex := MaxRoleSessionName - len(hex) - 1
greedy52 marked this conversation as resolved.
Show resolved Hide resolved

if keepPrefixIndex < 0 {
// This should not happen since sha1 length and MaxRoleSessionName are
// both constant.
ret = hex[:MaxRoleSessionName]
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
} else {
ret = fmt.Sprintf("%s-%s", roleSessionName[:keepPrefixIndex], hex)
}

slog.DebugContext(context.Background(), "AWS role session name is too long. Using a hash instead.", "hashed", ret, "original", roleSessionName)
return ret
}
30 changes: 30 additions & 0 deletions lib/utils/aws/aws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,3 +493,33 @@ func TestResourceARN(t *testing.T) {
})
}
}

func TestMaybeHashRoleSessionName(t *testing.T) {
for _, tt := range []struct {
name string
role string
expected string
}{
{
name: "role session name not hashed, less than 64 characters",
role: "MyRole",
expected: "MyRole",
},
{
name: "role session name not hashed, exactly 64 characters",
role: "Role1234567890123456789012345678901234567890",
expected: "Role1234567890123456789012345678901234567890",
},
{
name: "role session name hashed, longer than 64 characters",
role: "remote-raimundo.oliveira@abigcompany.com-teleport.abigcompany.com",
expected: "remote-raimundo.oliveir-8fe1f87e599b043e6a0108338feee3f111e9c1e4",
},
} {
t.Run(tt.name, func(t *testing.T) {
actual := MaybeHashRoleSessionName(tt.role)
require.Equal(t, tt.expected, actual)
require.LessOrEqual(t, len(actual), MaxRoleSessionName)
})
}
}
2 changes: 1 addition & 1 deletion lib/utils/aws/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (g *credentialsGetter) Get(_ context.Context, request GetCredentialsRequest
logrus.Debugf("Creating STS session %q for %q.", request.SessionName, request.RoleARN)
return stscreds.NewCredentials(request.Provider, request.RoleARN,
func(cred *stscreds.AssumeRoleProvider) {
cred.RoleSessionName = request.SessionName
cred.RoleSessionName = MaybeHashRoleSessionName(request.SessionName)
cred.Expiry.SetExpiration(request.Expiry, 0)

if request.ExternalID != "" {
Expand Down