Skip to content

feat: use IMDSv2 for requests #3

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

Open
wants to merge 2 commits into
base: development
Choose a base branch
from
Open
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
35 changes: 34 additions & 1 deletion pkg/metadata/provider_aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,34 @@ func awsMetaGet(lookupName string, fileName string, fileMode os.FileMode) {
}
}

func signRequest(req *http.Request, client *http.Client) (*http.Request, error) {
tokenReq, err := http.NewRequest("PUT", "http://169.254.169.254/latest/api/token", nil)
if err != nil {
return req, err
}

tokenReq.Header.Add("X-aws-ec2-metadata-token-ttl-seconds", "21600")

tokenRes, err := client.Do(tokenReq)
if err != nil {
return req, err
}
if tokenRes.StatusCode != 200 {
return req, fmt.Errorf("AWS: Status not ok: %d", tokenRes.StatusCode)
}

tokenBytes, err := io.ReadAll(tokenRes.Body)
if err != nil {
return req, err
}

token := string(tokenBytes)

req.Header.Add("X-aws-ec2-metadata-token", token)

return req, nil
}

// awsGet requests and extracts the requested URL
func awsGet(url string) ([]byte, error) {
var client = &http.Client{
Expand All @@ -101,7 +129,12 @@ func awsGet(url string) ([]byte, error) {
return nil, fmt.Errorf("AWS: http.NewRequest failed: %s", err)
}

resp, err := client.Do(req)
signedReq, err := signRequest(req, client)
if err != nil {
return nil, fmt.Errorf("AWS: Could not sign metadata request: %s", err)
}

resp, err := client.Do(signedReq)
if err != nil {
return nil, fmt.Errorf("AWS: Could not contact metadata service: %s", err)
}
Expand Down