diff --git a/pkg/security/ptracer/container_context.go b/pkg/security/ptracer/container_context.go index 76748eb8540dd..87aa142aee834 100644 --- a/pkg/security/ptracer/container_context.go +++ b/pkg/security/ptracer/container_context.go @@ -9,6 +9,9 @@ package ptracer import ( "encoding/json" + "fmt" + "io" + "net/http" "os" "time" @@ -23,9 +26,19 @@ type ECSMetadata struct { } func retrieveECSMetadata(url string) (*ECSMetadata, error) { - body, err := simpleHTTPRequest(url) + res, err := http.Get(url) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to get ECS metadata endpoint response: %w", err) + } + + body, err := io.ReadAll(res.Body) + _ = res.Body.Close() + if err != nil { + return nil, fmt.Errorf("failed to read ECS metadata endpoint response: %w", err) + } + + if res.StatusCode > 299 { + return nil, fmt.Errorf("ECS metadata endpoint returned an invalid http code: %d", res.StatusCode) } data := ECSMetadata{} diff --git a/pkg/security/ptracer/utils.go b/pkg/security/ptracer/utils.go index 3d79037582aef..97e0d2b9eb82c 100644 --- a/pkg/security/ptracer/utils.go +++ b/pkg/security/ptracer/utils.go @@ -15,8 +15,6 @@ import ( "fmt" "io" "math/rand" - "net" - "net/url" "os" "path" "path/filepath" @@ -104,64 +102,6 @@ func getNSID() uint64 { return stat.Ino } -// simpleHTTPRequest used to avoid importing the crypto golang package -func simpleHTTPRequest(uri string) ([]byte, error) { - u, err := url.Parse(uri) - if err != nil { - return nil, err - } - - addr := u.Host - if u.Port() == "" { - addr += ":80" - } - - tcpAddr, err := net.ResolveTCPAddr("tcp", addr) - if err != nil { - return nil, err - } - - client, err := net.DialTCP("tcp", nil, tcpAddr) - if err != nil { - return nil, err - } - defer client.Close() - - path := u.Path - if path == "" { - path = "/" - } - - req := fmt.Sprintf("GET %s?%s HTTP/1.0\nHost: %s\nConnection: close\n\n", path, u.RawQuery, u.Hostname()) - - _, err = client.Write([]byte(req)) - if err != nil { - return nil, err - } - - var body []byte - buf := make([]byte, 256) - - for { - n, err := client.Read(buf) - if err != nil { - if err != io.EOF { - return nil, err - } - break - } - body = append(body, buf[:n]...) - } - - offset := bytes.Index(body, []byte{'\r', '\n', '\r', '\n'}) - if offset < 0 { - - return nil, errors.New("unable to parse http response") - } - - return body[offset+2:], nil -} - func fillProcessCwd(process *Process) error { cwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", process.Pid)) if err != nil {