From 7f029f27f3813f1480d09af7092326fe0d7c1adb Mon Sep 17 00:00:00 2001 From: Victoria Jeffrey Date: Thu, 28 Sep 2023 00:31:47 -0600 Subject: [PATCH 1/4] =?UTF-8?q?=F0=9F=90=9B=20fix=20instance=20identity=20?= =?UTF-8?q?doc=20fetching=20for=20ec2=20instances?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- providers/os/id/awsec2/metadata_cmd.go | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/providers/os/id/awsec2/metadata_cmd.go b/providers/os/id/awsec2/metadata_cmd.go index 622ad3c254..e1581d4578 100644 --- a/providers/os/id/awsec2/metadata_cmd.go +++ b/providers/os/id/awsec2/metadata_cmd.go @@ -21,8 +21,9 @@ import ( ) const ( - identityUrl = "http://169.254.169.254/latest/dynamic/instance-identity/document" - tagNameUrl = "http://169.254.169.254/latest/meta-data/tags/instance/Name" + identityUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/dynamic/instance-identity/document` + token = `-X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` + tagNameUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/meta-data/tags/instance/Name` ) func NewCommandInstanceMetadata(conn shared.Connection, pf *inventory.Platform, config *aws.Config) *CommandInstanceMetadata { @@ -85,10 +86,10 @@ func curlWindows(url string) string { return fmt.Sprintf("Invoke-RestMethod -TimeoutSec 1 -URI %s -UseBasicParsing | ConvertTo-Json", url) } -func (m *CommandInstanceMetadata) curlDocument(url string) (string, error) { +func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string, error) { switch { case m.platform.IsFamily(inventory.FAMILY_UNIX): - cmd, err := m.conn.RunCommand("curl " + url) + cmd, err := m.conn.RunCommand("curl " + token) if err != nil { return "", err } @@ -97,6 +98,16 @@ func (m *CommandInstanceMetadata) curlDocument(url string) (string, error) { return "", err } + tokenString := strings.TrimSpace(string(data)) + cmd, err = m.conn.RunCommand("curl " + fmt.Sprintf(identityUrl, tokenString)) + if err != nil { + return "", err + } + data, err = io.ReadAll(cmd.Stdout) + if err != nil { + return "", err + } + return strings.TrimSpace(string(data)), nil case m.platform.IsFamily(inventory.FAMILY_WINDOWS): curlCmd := curlWindows(url) @@ -117,7 +128,7 @@ func (m *CommandInstanceMetadata) curlDocument(url string) (string, error) { } func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { - res, err := m.curlDocument(tagNameUrl) + res, err := m.curlDocument(token, tagNameUrl) if err != nil { return "", err } @@ -128,5 +139,5 @@ func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { } func (m *CommandInstanceMetadata) instanceIdentityDocument() (string, error) { - return m.curlDocument(identityUrl) + return m.curlDocument(token, identityUrl) } From 0e11b0e2a5533f497e43ecb3c8311e7a1cbcc820 Mon Sep 17 00:00:00 2001 From: Christoph Hartmann Date: Wed, 4 Oct 2023 18:24:48 +0200 Subject: [PATCH 2/4] =?UTF-8?q?=E2=AD=90=EF=B8=8F=20update=20aws=20windows?= =?UTF-8?q?=20platform=20detection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 9 +++++ providers/os/id/awsec2/metadata_cmd.go | 47 +++++++++++++++++++------- providers/os/provider/detector.go | 4 +++ providers/os/provider/provider.go | 35 ++++++++++++++++--- 4 files changed, 77 insertions(+), 18 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 8780adddfe..5973af4fd1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -177,6 +177,15 @@ "args": [ "status", ], + }, + { + "name": "cnquery-shell", + "type": "go", + "request": "launch", + "program": "${workspaceRoot}/apps/cnquery/cnquery.go", + "args": [ + "shell", "ssh", "user@18.215.249.49", + ], } ] } diff --git a/providers/os/id/awsec2/metadata_cmd.go b/providers/os/id/awsec2/metadata_cmd.go index e1581d4578..194fddf864 100644 --- a/providers/os/id/awsec2/metadata_cmd.go +++ b/providers/os/id/awsec2/metadata_cmd.go @@ -22,8 +22,22 @@ import ( const ( identityUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/dynamic/instance-identity/document` - token = `-X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` + tokenUrl = `-X PUT "http://169.254.169.254/latest/api/token"` tagNameUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/meta-data/tags/instance/Name` + + identityUrlWindows = ` +$Headers = @{ + "X-aws-ec2-metadata-token" = %s +} +Invoke-RestMethod -TimeoutSec 1 -Headers $Headers -URI http://169.254.169.254/latest/dynamic/instance-identity/document -UseBasicParsing | ConvertTo-Json +` + + tokenUrlWindows = ` +$Headers = @{ + "X-aws-ec2-metadata-token-ttl-seconds" = "21600" +} +Invoke-RestMethod -Method Put -Uri "http://169.254.169.254/latest/api/token" -Headers $Headers -TimeoutSec 1 -UseBasicParsing +` ) func NewCommandInstanceMetadata(conn shared.Connection, pf *inventory.Platform, config *aws.Config) *CommandInstanceMetadata { @@ -82,14 +96,10 @@ func (m *CommandInstanceMetadata) Identify() (Identity, error) { }, nil } -func curlWindows(url string) string { - return fmt.Sprintf("Invoke-RestMethod -TimeoutSec 1 -URI %s -UseBasicParsing | ConvertTo-Json", url) -} - -func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string, error) { +func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (string, error) { switch { case m.platform.IsFamily(inventory.FAMILY_UNIX): - cmd, err := m.conn.RunCommand("curl " + token) + cmd, err := m.conn.RunCommand("curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" " + tokenUrl) if err != nil { return "", err } @@ -97,8 +107,8 @@ func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string if err != nil { return "", err } - tokenString := strings.TrimSpace(string(data)) + cmd, err = m.conn.RunCommand("curl " + fmt.Sprintf(identityUrl, tokenString)) if err != nil { return "", err @@ -110,9 +120,9 @@ func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string return strings.TrimSpace(string(data)), nil case m.platform.IsFamily(inventory.FAMILY_WINDOWS): - curlCmd := curlWindows(url) - encoded := powershell.Encode(curlCmd) - cmd, err := m.conn.RunCommand(encoded) + + tokenPwshEncoded := powershell.Encode(fmt.Sprintf(tokenUrlWindows, tokenUrl)) + cmd, err := m.conn.RunCommand(tokenPwshEncoded) if err != nil { return "", err } @@ -120,6 +130,17 @@ func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string if err != nil { return "", err } + tokenString := strings.TrimSpace(string(data)) + + curlPwshEncoded := powershell.Encode(fmt.Sprintf(identityUrlWindows, tokenString)) + cmd, err = m.conn.RunCommand(curlPwshEncoded) + if err != nil { + return "", err + } + data, err = io.ReadAll(cmd.Stdout) + if err != nil { + return "", err + } return strings.TrimSpace(string(data)), nil default: @@ -128,7 +149,7 @@ func (m *CommandInstanceMetadata) curlDocument(token string, url string) (string } func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { - res, err := m.curlDocument(token, tagNameUrl) + res, err := m.curlDocument(tagNameUrl, tokenUrl) if err != nil { return "", err } @@ -139,5 +160,5 @@ func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { } func (m *CommandInstanceMetadata) instanceIdentityDocument() (string, error) { - return m.curlDocument(token, identityUrl) + return m.curlDocument(identityUrl, tokenUrl) } diff --git a/providers/os/provider/detector.go b/providers/os/provider/detector.go index 2d112caf6c..333a8a9248 100644 --- a/providers/os/provider/detector.go +++ b/providers/os/provider/detector.go @@ -66,12 +66,14 @@ func (s *Service) detect(asset *inventory.Asset, conn shared.Connection) error { } if hasDetector(detectors, ids.IdDetector_Hostname) { + log.Debug().Msg("run hostname id detector") if id, ok := hostname.Hostname(conn, asset.Platform); ok { asset.PlatformIds = append(asset.PlatformIds, id) } } if hasDetector(detectors, ids.IdDetector_CloudDetect) { + log.Debug().Msg("run cloud platform detector") if id, name, related := aws.Detect(conn, asset.Platform); id != "" { asset.PlatformIds = append(asset.PlatformIds, id) asset.Platform.Name = name @@ -92,6 +94,7 @@ func (s *Service) detect(asset *inventory.Asset, conn shared.Connection) error { } if hasDetector(detectors, ids.IdDetector_SshHostkey) { + log.Debug().Msg("run ssh id detector") ids, err := sshhostkey.Detect(conn, asset.Platform) if err != nil { log.Warn().Err(err).Msg("failure in ssh hostkey detector") @@ -101,6 +104,7 @@ func (s *Service) detect(asset *inventory.Asset, conn shared.Connection) error { } if hasDetector(detectors, ids.IdDetector_MachineID) { + log.Debug().Msg("run machineID id detector") id, hostErr := machineid.MachineId(conn, asset.Platform) if hostErr != nil { log.Warn().Err(hostErr).Msg("failure in machineID detector") diff --git a/providers/os/provider/provider.go b/providers/os/provider/provider.go index aa8f7a7273..c3cca6d01f 100644 --- a/providers/os/provider/provider.go +++ b/providers/os/provider/provider.go @@ -189,7 +189,7 @@ func (s *Service) ParseCLI(req *plugin.ParseCLIReq) (*plugin.ParseCLIRes, error) conf.Host = containerID } - idDetector := "hostname" + idDetector := "" if flag, ok := flags["id-detector"]; ok { if string(flag.Value) != "" { idDetector = string(flag.Value) @@ -314,7 +314,13 @@ func (s *Service) connect(req *plugin.ConnectReq, callback plugin.ProviderCallba case LocalConnectionType: s.lastConnectionID++ conn = connection.NewLocalConnection(s.lastConnectionID, conf, asset) - fingerprint, err := IdentifyPlatform(conn, asset.Platform, []string{ids.IdDetector_Hostname, ids.IdDetector_CloudDetect}) + idDetectors := asset.IdDetector + if len(idDetectors) == 0 { + // fallback to default id detectors + idDetectors = []string{ids.IdDetector_Hostname, ids.IdDetector_CloudDetect} + } + + fingerprint, err := IdentifyPlatform(conn, asset.Platform, idDetectors) if err == nil { asset.Name = fingerprint.Name asset.PlatformIds = fingerprint.PlatformIDs @@ -326,7 +332,13 @@ func (s *Service) connect(req *plugin.ConnectReq, callback plugin.ProviderCallba if err != nil { return nil, err } - fingerprint, err := IdentifyPlatform(conn, asset.Platform, []string{ids.IdDetector_Hostname, ids.IdDetector_CloudDetect, ids.IdDetector_SshHostkey}) + idDetectors := asset.IdDetector + if len(idDetectors) == 0 { + // fallback to default id detectors + idDetectors = []string{ids.IdDetector_Hostname, ids.IdDetector_CloudDetect, ids.IdDetector_SshHostkey} + } + + fingerprint, err := IdentifyPlatform(conn, asset.Platform, idDetectors) if err == nil { if conn.Asset().Connections[0].Runtime != "vagrant" { asset.Name = fingerprint.Name @@ -340,7 +352,13 @@ func (s *Service) connect(req *plugin.ConnectReq, callback plugin.ProviderCallba if err != nil { return nil, err } - fingerprint, err := IdentifyPlatform(conn, asset.Platform, []string{ids.IdDetector_Hostname}) + + idDetectors := asset.IdDetector + if len(idDetectors) == 0 { + // fallback to default id detectors + idDetectors = []string{ids.IdDetector_Hostname} + } + fingerprint, err := IdentifyPlatform(conn, asset.Platform, idDetectors) if err == nil { asset.Name = fingerprint.Name asset.PlatformIds = fingerprint.PlatformIDs @@ -352,7 +370,14 @@ func (s *Service) connect(req *plugin.ConnectReq, callback plugin.ProviderCallba if err != nil { return nil, err } - fingerprint, err := IdentifyPlatform(conn, asset.Platform, []string{ids.IdDetector_Hostname}) + + idDetectors := asset.IdDetector + if len(idDetectors) == 0 { + // fallback to default id detectors + idDetectors = []string{ids.IdDetector_Hostname} + } + + fingerprint, err := IdentifyPlatform(conn, asset.Platform, idDetectors) if err == nil { asset.Name = fingerprint.Name asset.PlatformIds = fingerprint.PlatformIDs From 82304f52dc292ba836c372d60d05e229946fbea8 Mon Sep 17 00:00:00 2001 From: Christoph Hartmann Date: Wed, 4 Oct 2023 18:53:07 +0200 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=A7=B9=20remove=20machine=20id=20as?= =?UTF-8?q?=20default=20id=20detector?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- providers/os/connection/vagrant.go | 2 +- providers/os/provider/detector.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/os/connection/vagrant.go b/providers/os/connection/vagrant.go index 7799489161..d3efe0280f 100644 --- a/providers/os/connection/vagrant.go +++ b/providers/os/connection/vagrant.go @@ -119,7 +119,7 @@ func migrateVagrantAssetToSsh(id uint32, sshConfig *vagrant.VagrantVmSSHConfig, asset.Name = sshConfig.Host asset.Connections = []*inventory.Config{cc} - asset.IdDetector = []string{ids.IdDetector_Hostname, ids.IdDetector_SshHostkey, ids.IdDetector_MachineID} + asset.IdDetector = []string{ids.IdDetector_Hostname, ids.IdDetector_SshHostkey} return nil } diff --git a/providers/os/provider/detector.go b/providers/os/provider/detector.go index 333a8a9248..fac0449c24 100644 --- a/providers/os/provider/detector.go +++ b/providers/os/provider/detector.go @@ -19,9 +19,9 @@ import ( "go.mondoo.com/cnquery/providers/os/id/sshhostkey" ) +// default id detectors var IdDetectors = []string{ ids.IdDetector_Hostname, - ids.IdDetector_MachineID, ids.IdDetector_CloudDetect, ids.IdDetector_SshHostkey, } From 740f66408b134b7045835759a63f7a703ee62d46 Mon Sep 17 00:00:00 2001 From: Christoph Hartmann Date: Wed, 4 Oct 2023 20:22:47 +0200 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=A7=B9=20update=20tests=20for=20aws?= =?UTF-8?q?=20ec2=20detection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- providers/os/connection/mock/mock.go | 3 +- providers/os/id/aws/testdata/instance.toml | 8 ++-- providers/os/id/aws/testdata/instancearm.toml | 7 ++- providers/os/id/aws/testdata/notinstance.toml | 5 +- providers/os/id/awsec2/metadata_cmd.go | 47 +++++++++++++++---- providers/os/id/awsec2/metadata_local_test.go | 14 ++++++ .../instance-identity_document_linux.toml | 7 ++- ...tance-identity_document_linux_no_tags.toml | 7 ++- .../instance-identity_document_windows.toml | 11 +++-- ...nce-identity_document_windows_no_tags.toml | 12 +++-- 10 files changed, 92 insertions(+), 29 deletions(-) diff --git a/providers/os/connection/mock/mock.go b/providers/os/connection/mock/mock.go index c4565e0ccf..fd32ea8f19 100644 --- a/providers/os/connection/mock/mock.go +++ b/providers/os/connection/mock/mock.go @@ -139,7 +139,8 @@ func (c *Connection) RunCommand(command string) (*shared.Command, error) { found, ok := c.data.Commands[command] if !ok { // try to fetch command by hash (more reliable for whitespace) - found, ok = c.data.Commands[hashCmd(command)] + hash := hashCmd(command) + found, ok = c.data.Commands[hash] } if !ok { c.missing["command"][command] = true diff --git a/providers/os/id/aws/testdata/instance.toml b/providers/os/id/aws/testdata/instance.toml index c102f710c9..e1f1a5aefe 100644 --- a/providers/os/id/aws/testdata/instance.toml +++ b/providers/os/id/aws/testdata/instance.toml @@ -22,7 +22,10 @@ content = "Red Hat Enterprise Linux Server release 7.2 (Maipo)" gid = 0 size = 0 -[commands."curl http://169.254.169.254/latest/dynamic/instance-identity/document"] +[commands."curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -X PUT \"http://169.254.169.254/latest/api/token\""] +stdout = "MYTOKEN" + +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document"] stdout = """ { "devpayProductCodes" : null, @@ -43,6 +46,5 @@ stdout = """ } """ - -[commands."curl http://169.254.169.254/latest/meta-data/tags/instance/Name"] +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/meta-data/tags/instance/Name"] stdout = "ec2-name" \ No newline at end of file diff --git a/providers/os/id/aws/testdata/instancearm.toml b/providers/os/id/aws/testdata/instancearm.toml index 36a5fab4ce..9b1113b320 100644 --- a/providers/os/id/aws/testdata/instancearm.toml +++ b/providers/os/id/aws/testdata/instancearm.toml @@ -34,7 +34,10 @@ content = "Red Hat Enterprise Linux Server release 7.2 (Maipo)" gid = 0 size = 0 -[commands."curl http://169.254.169.254/latest/dynamic/instance-identity/document"] +[commands."curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -X PUT \"http://169.254.169.254/latest/api/token\""] +stdout = "MYTOKEN" + +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document"] stdout = """ { "devpayProductCodes" : null, @@ -55,5 +58,5 @@ stdout = """ } """ -[commands."curl http://169.254.169.254/latest/meta-data/tags/instance/Name"] +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/meta-data/tags/instance/Name"] stdout = "ec2-name" \ No newline at end of file diff --git a/providers/os/id/aws/testdata/notinstance.toml b/providers/os/id/aws/testdata/notinstance.toml index 64bd8a39c6..45d26c5fa0 100644 --- a/providers/os/id/aws/testdata/notinstance.toml +++ b/providers/os/id/aws/testdata/notinstance.toml @@ -22,7 +22,10 @@ content = "Red Hat Enterprise Linux Server release 7.2 (Maipo)" gid = 0 size = 0 -[commands."curl http://169.254.169.254/latest/dynamic/instance-identity/document"] +[commands."curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -X PUT \"http://169.254.169.254/latest/api/token\""] +stdout = "MYTOKEN" + +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document"] stdout = """ { "devpayProductCodes" : null, diff --git a/providers/os/id/awsec2/metadata_cmd.go b/providers/os/id/awsec2/metadata_cmd.go index 194fddf864..4a5be11399 100644 --- a/providers/os/id/awsec2/metadata_cmd.go +++ b/providers/os/id/awsec2/metadata_cmd.go @@ -22,7 +22,7 @@ import ( const ( identityUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/dynamic/instance-identity/document` - tokenUrl = `-X PUT "http://169.254.169.254/latest/api/token"` + tokenUrl = `-H "X-aws-ec2-metadata-token-ttl-seconds: 21600" -X PUT "http://169.254.169.254/latest/api/token"` tagNameUrl = `-H "X-aws-ec2-metadata-token: %s" -v http://169.254.169.254/latest/meta-data/tags/instance/Name` identityUrlWindows = ` @@ -37,6 +37,12 @@ $Headers = @{ "X-aws-ec2-metadata-token-ttl-seconds" = "21600" } Invoke-RestMethod -Method Put -Uri "http://169.254.169.254/latest/api/token" -Headers $Headers -TimeoutSec 1 -UseBasicParsing +` + tagNameUrlWindows = ` +$Headers = @{ + "X-aws-ec2-metadata-token" = %s +} +Invoke-RestMethod -Method Put -Uri "http://169.254.169.254/latest/meta-data/tags/instance/Name" -Headers $Headers -TimeoutSec 1 -UseBasicParsing ` ) @@ -96,10 +102,17 @@ func (m *CommandInstanceMetadata) Identify() (Identity, error) { }, nil } -func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (string, error) { +type metadataType int + +const ( + document metadataType = iota + instanceNameTag +) + +func (m *CommandInstanceMetadata) curlDocument(metadataType metadataType) (string, error) { switch { case m.platform.IsFamily(inventory.FAMILY_UNIX): - cmd, err := m.conn.RunCommand("curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" " + tokenUrl) + cmd, err := m.conn.RunCommand("curl " + tokenUrl) if err != nil { return "", err } @@ -109,7 +122,15 @@ func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (str } tokenString := strings.TrimSpace(string(data)) - cmd, err = m.conn.RunCommand("curl " + fmt.Sprintf(identityUrl, tokenString)) + commandScript := "" + switch metadataType { + case document: + commandScript = "curl " + fmt.Sprintf(identityUrl, tokenString) + case instanceNameTag: + commandScript = "curl " + fmt.Sprintf(tagNameUrl, tokenString) + } + + cmd, err = m.conn.RunCommand(commandScript) if err != nil { return "", err } @@ -120,8 +141,7 @@ func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (str return strings.TrimSpace(string(data)), nil case m.platform.IsFamily(inventory.FAMILY_WINDOWS): - - tokenPwshEncoded := powershell.Encode(fmt.Sprintf(tokenUrlWindows, tokenUrl)) + tokenPwshEncoded := powershell.Encode(tokenUrlWindows) cmd, err := m.conn.RunCommand(tokenPwshEncoded) if err != nil { return "", err @@ -132,8 +152,15 @@ func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (str } tokenString := strings.TrimSpace(string(data)) - curlPwshEncoded := powershell.Encode(fmt.Sprintf(identityUrlWindows, tokenString)) - cmd, err = m.conn.RunCommand(curlPwshEncoded) + commandScript := "" + switch metadataType { + case document: + commandScript = powershell.Encode(fmt.Sprintf(identityUrlWindows, tokenString)) + case instanceNameTag: + commandScript = powershell.Encode(fmt.Sprintf(tagNameUrlWindows, tokenString)) + } + + cmd, err = m.conn.RunCommand(commandScript) if err != nil { return "", err } @@ -149,7 +176,7 @@ func (m *CommandInstanceMetadata) curlDocument(url string, tokenUrl string) (str } func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { - res, err := m.curlDocument(tagNameUrl, tokenUrl) + res, err := m.curlDocument(instanceNameTag) if err != nil { return "", err } @@ -160,5 +187,5 @@ func (m *CommandInstanceMetadata) instanceNameTag() (string, error) { } func (m *CommandInstanceMetadata) instanceIdentityDocument() (string, error) { - return m.curlDocument(identityUrl, tokenUrl) + return m.curlDocument(document) } diff --git a/providers/os/id/awsec2/metadata_local_test.go b/providers/os/id/awsec2/metadata_local_test.go index be83fa6a52..a8b1e8e2e7 100644 --- a/providers/os/id/awsec2/metadata_local_test.go +++ b/providers/os/id/awsec2/metadata_local_test.go @@ -44,6 +44,13 @@ func TestEC2RoleProviderInstanceIdentityLocal(t *testing.T) { cfg := fakeConfig() cfg.HTTPClient = smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) { url := r.URL.String() + if strings.Contains(url, "latest/api/token") { + return &http.Response{ + StatusCode: 200, + Header: http.Header{}, + Body: io.NopCloser(bytes.NewBufferString("mock-token")), + }, nil + } if strings.Contains(url, "tags/instance/Name") { return &http.Response{ StatusCode: 200, @@ -75,6 +82,13 @@ func TestEC2RoleProviderInstanceIdentityLocalDisabledTagsService(t *testing.T) { cfg := fakeConfig() cfg.HTTPClient = smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) { url := r.URL.String() + if strings.Contains(url, "latest/api/token") { + return &http.Response{ + StatusCode: 200, + Header: http.Header{}, + Body: io.NopCloser(bytes.NewBufferString("mock-token")), + }, nil + } if strings.Contains(url, "tags/instance/Name") { return &http.Response{ StatusCode: 404, diff --git a/providers/os/id/awsec2/testdata/instance-identity_document_linux.toml b/providers/os/id/awsec2/testdata/instance-identity_document_linux.toml index fe308f1dd9..6f0fe79e62 100644 --- a/providers/os/id/awsec2/testdata/instance-identity_document_linux.toml +++ b/providers/os/id/awsec2/testdata/instance-identity_document_linux.toml @@ -10,7 +10,10 @@ stdout = "4.9.125-linuxkit" [files."/etc/redhat-release"] content = "Red Hat Enterprise Linux Server release 7.2 (Maipo)" -[commands."curl http://169.254.169.254/latest/dynamic/instance-identity/document"] +[commands."curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -X PUT \"http://169.254.169.254/latest/api/token\""] +stdout = "MYTOKEN" + +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document"] stdout = """ { "devpayProductCodes" : null, @@ -31,5 +34,5 @@ stdout = """ } """ -[commands."curl http://169.254.169.254/latest/meta-data/tags/instance/Name"] +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/meta-data/tags/instance/Name"] stdout = "ec2-name" \ No newline at end of file diff --git a/providers/os/id/awsec2/testdata/instance-identity_document_linux_no_tags.toml b/providers/os/id/awsec2/testdata/instance-identity_document_linux_no_tags.toml index 7a0d423768..6fbe2b1fb1 100644 --- a/providers/os/id/awsec2/testdata/instance-identity_document_linux_no_tags.toml +++ b/providers/os/id/awsec2/testdata/instance-identity_document_linux_no_tags.toml @@ -10,7 +10,10 @@ stdout = "4.9.125-linuxkit" [files."/etc/redhat-release"] content = "Red Hat Enterprise Linux Server release 7.2 (Maipo)" -[commands."curl http://169.254.169.254/latest/dynamic/instance-identity/document"] +[commands."curl -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" -X PUT \"http://169.254.169.254/latest/api/token\""] +stdout = "MYTOKEN" + +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document"] stdout = """ { "devpayProductCodes" : null, @@ -31,7 +34,7 @@ stdout = """ } """ -[commands."curl http://169.254.169.254/latest/meta-data/tags/instance/Name"] +[commands."curl -H \"X-aws-ec2-metadata-token: MYTOKEN\" -v http://169.254.169.254/latest/meta-data/tags/instance/Name"] stdout = """