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

Use AWS SDK to retrieve ec2 instance identity doc #1360

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
100 changes: 49 additions & 51 deletions pkg/agent/plugin/nodeattestor/aws/iid.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@ package aws
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"sync"

awsSdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/hashicorp/hcl"
"github.com/spiffe/spire/pkg/agent/plugin/nodeattestor"
"github.com/spiffe/spire/pkg/common/catalog"
"github.com/spiffe/spire/pkg/common/plugin/aws"
"github.com/spiffe/spire/proto/spire/common"
spi "github.com/spiffe/spire/proto/spire/common/plugin"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

"errors"

spi "github.com/spiffe/spire/proto/spire/common/plugin"
)

const (
defaultIdentityDocumentURL = "http://169.254.169.254/latest/dynamic/instance-identity/document"
defaultIdentitySignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature"
docPath = "instance-identity/document"
sigPath = "instance-identity/signature"
)

func BuiltIn() catalog.Plugin {
Expand All @@ -36,15 +36,15 @@ func builtin(p *IIDAttestorPlugin) catalog.Plugin {

// IIDAttestorConfig configures a IIDAttestorPlugin.
type IIDAttestorConfig struct {
EC2MetadataEndpoint string `hcl:"ec2_metadata_endpoint"`
IdentityDocumentURL string `hcl:"identity_document_url"`
IdentitySignatureURL string `hcl:"identity_signature_url"`
trustDomain string
}

// IIDAttestorPlugin implements aws nodeattestation in the agent.
type IIDAttestorPlugin struct {
config *IIDAttestorConfig
mtx sync.RWMutex
session *session.Session
mtx sync.RWMutex
}

// New creates a new IIDAttestorPlugin.
Expand All @@ -55,24 +55,25 @@ func New() *IIDAttestorPlugin {
// FetchAttestationData fetches attestation data from the aws metadata server and sends an attestation response
// on given stream.
func (p *IIDAttestorPlugin) FetchAttestationData(stream nodeattestor.NodeAttestor_FetchAttestationDataServer) error {
c, err := p.getConfig()
if err != nil {
return err
if p.session == nil {
return errors.New("not configured")
}

docBytes, err := httpGetBytes(c.IdentityDocumentURL)
client := ec2metadata.New(p.session)

doc, err := client.GetDynamicData(docPath)
if err != nil {
return aws.AttestationStepError("retrieving the IID from AWS", err)
}

sigBytes, err := httpGetBytes(c.IdentitySignatureURL)
sig, err := client.GetDynamicData(sigPath)
if err != nil {
return aws.AttestationStepError("retrieving the IID signature from AWS", err)
}

attestationData := aws.IIDAttestationData{
Document: string(docBytes),
Signature: string(sigBytes),
Document: doc,
Signature: sig,
}

respData, err := json.Marshal(attestationData)
Expand All @@ -96,27 +97,30 @@ func (p *IIDAttestorPlugin) Configure(ctx context.Context, req *spi.ConfigureReq
return nil, status.Errorf(codes.InvalidArgument, "unable to decode configuration: %v", err)
}

if req.GlobalConfig == nil {
return nil, status.Error(codes.InvalidArgument, "global configuration is required")
}
if req.GlobalConfig.TrustDomain == "" {
return nil, status.Error(codes.InvalidArgument, "global configuration missing trust domain")
// If the endpoint isn't explicitly configured but the legacy URLs are, extract the endpoint from it
// This code is transitional, here until these deprecated configs are removed
if config.EC2MetadataEndpoint == "" && (config.IdentityDocumentURL != "" || config.IdentitySignatureURL != "") {
endpoint, err := endpointFromLegacyConfig(config.IdentityDocumentURL, config.IdentitySignatureURL)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
config.EC2MetadataEndpoint = endpoint
}
// Set local vars from config struct
config.trustDomain = req.GlobalConfig.TrustDomain

if config.IdentityDocumentURL == "" {
config.IdentityDocumentURL = defaultIdentityDocumentURL
awsCfg := awsSdk.NewConfig()

if config.EC2MetadataEndpoint != "" {
awsCfg.WithEndpoint(config.EC2MetadataEndpoint)
}

if config.IdentitySignatureURL == "" {
config.IdentitySignatureURL = defaultIdentitySignatureURL
newSession, err := session.NewSession(awsCfg)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}

p.mtx.Lock()
defer p.mtx.Unlock()

p.config = config
p.session = newSession

return &spi.ConfigureResponse{}, nil
}
Expand All @@ -126,30 +130,24 @@ func (*IIDAttestorPlugin) GetPluginInfo(context.Context, *spi.GetPluginInfoReque
return &spi.GetPluginInfoResponse{}, nil
}

func (p *IIDAttestorPlugin) getConfig() (*IIDAttestorConfig, error) {
p.mtx.RLock()
defer p.mtx.RUnlock()

if p.config == nil {
return nil, errors.New("not configured")
// endpointFromLegacyConfig extracts the endpoint from legacy configuration values
// This code is transitional, here until these deprecated configs are removed
func endpointFromLegacyConfig(docURL, sigURL string) (string, error) {
docSuffix := "/dynamic/" + docPath
if !strings.HasSuffix(docURL, docSuffix) {
return "", fmt.Errorf("IID URL '%s' doesn't end in expected suffix %s", docURL, docSuffix)
}
return p.config, nil
}
docEndpoint := strings.TrimSuffix(docURL, docSuffix)

func httpGetBytes(url string) ([]byte, error) {
resp, err := http.Get(url) //nolint: gosec // URL is provided via explicit configuration
if err != nil {
return nil, err
sigSuffix := "/dynamic/" + sigPath
if !strings.HasSuffix(sigURL, sigSuffix) {
return "", fmt.Errorf("IID signature URL '%s' doesn't end in expected suffix %s", sigURL, sigSuffix)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is source #1 of incompatibility: If you don't use the regular path suffix, it's not going to work.

}
defer resp.Body.Close()
sigEndpoint := strings.TrimSuffix(sigURL, sigSuffix)

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
if docEndpoint != sigEndpoint {
return "", fmt.Errorf("IID URL and Signature URL had different endpoints: %s != %s", docEndpoint, sigEndpoint)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is source #2 of incompatibility: If you use two different endpoints it doesn't work -- the SDK only takes a single one.

}

bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bytes, nil
return docEndpoint, nil
}
42 changes: 27 additions & 15 deletions pkg/agent/plugin/nodeattestor/aws/iid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ import (
"testing"

"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/spiffe/spire/pkg/agent/plugin/nodeattestor"
"github.com/spiffe/spire/pkg/common/pemutil"
"github.com/spiffe/spire/pkg/common/plugin/aws"
"github.com/spiffe/spire/proto/spire/common/plugin"
"github.com/spiffe/spire/test/spiretest"
"github.com/stretchr/testify/require"
)

const (
apiTokenPath = "/latest/api/token" //nolint: gosec // false positive
defaultIdentityDocumentPath = "/latest/dynamic/instance-identity/document"
defaultIdentitySignaturePath = "/latest/dynamic/instance-identity/signature"
)
Expand Down Expand Up @@ -57,6 +60,10 @@ type Suite struct {
func (s *Suite) SetupTest() {
s.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch path := req.URL.Path; path {
case apiTokenPath:
// Token requested by AWS SDK for IMDSv2 authentication
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("token"))
case defaultIdentityDocumentPath:
// write doc resp
w.WriteHeader(s.status)
Expand All @@ -67,17 +74,15 @@ func (s *Suite) SetupTest() {
_, _ = w.Write([]byte(s.sigBody))
default:
// unexpected path
fmt.Printf("unexpected path %s", path)
w.WriteHeader(http.StatusForbidden)
}
}))

s.p = s.newPlugin()

_, err := s.p.Configure(context.Background(), &plugin.ConfigureRequest{
Configuration: fmt.Sprintf(`
identity_document_url = "http://%s%s"
identity_signature_url = "http://%s%s"
`, s.server.Listener.Addr().String(), defaultIdentityDocumentPath, s.server.Listener.Addr().String(), defaultIdentitySignaturePath),
Configuration: fmt.Sprintf(`ec2_metadata_endpoint = "http://%s/latest"`, s.server.Listener.Addr().String()),
GlobalConfig: &plugin.ConfigureRequest_GlobalConfig{
TrustDomain: "example.org",
},
Expand Down Expand Up @@ -107,7 +112,7 @@ func (s *Suite) TestUnexpectedStatus() {
s.status = http.StatusBadGateway
s.docBody = ""
_, err := s.fetchAttestationData()
s.RequireErrorContains(err, "unexpected status code: 502")
s.RequireErrorContains(err, "status code: 502")
}

func (s *Suite) TestSuccessfulIdentityProcessing() {
Expand Down Expand Up @@ -139,16 +144,6 @@ func (s *Suite) TestConfigure() {
require.Error(err)
require.Nil(resp)

// global configuration not provided
resp, err = s.p.Configure(context.Background(), &plugin.ConfigureRequest{})
s.RequireErrorContains(err, "global configuration is required")
require.Nil(resp)

// missing trust domain
resp, err = s.p.Configure(context.Background(), &plugin.ConfigureRequest{GlobalConfig: &plugin.ConfigureRequest_GlobalConfig{}})
s.RequireErrorContains(err, "global configuration missing trust domain")
require.Nil(resp)

// success
resp, err = s.p.Configure(context.Background(), &plugin.ConfigureRequest{
GlobalConfig: &plugin.ConfigureRequest_GlobalConfig{
Expand Down Expand Up @@ -202,3 +197,20 @@ func (s *Suite) buildDefaultIIDDocAndSig() (docBytes []byte, sigBytes []byte) {

return docBytes, sig
}

func TestEndpointFromLegacyConfig(t *testing.T) {
// These are the formerly-hardcoded default URLs
const defaultIdentityDocumentURL = "http://169.254.169.254/latest/dynamic/instance-identity/document"
const defaultIdentitySignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature"
// This is the default endpoint we should get from them
const defaultEndpointURL = "http://169.254.169.254/latest"

endpoint, err := endpointFromLegacyConfig(defaultIdentityDocumentURL, defaultIdentitySignatureURL)
require.NoError(t, err)
require.Equal(t, defaultEndpointURL, endpoint)

// Verify the endpoint is equal to what's in the SDK, too:
sdkDefaultEndpoint, err := endpoints.DefaultResolver().EndpointFor(ec2metadata.ServiceName, endpoints.CaCentral1RegionID)
require.NoError(t, err)
require.Equal(t, sdkDefaultEndpoint.URL, endpoint)
}
3 changes: 1 addition & 2 deletions pkg/server/plugin/nodeattestor/aws/iid.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ import (
"text/template"
"time"

"github.com/hashicorp/go-hclog"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/hcl"
"github.com/spiffe/spire/pkg/common/catalog"
caws "github.com/spiffe/spire/pkg/common/plugin/aws"
Expand Down