repo_id
stringclasses
927 values
file_path
stringlengths
99
214
content
stringlengths
2
4.15M
client
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/schema.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package client import ( "encoding/json" "path" "sort" "time" ) const ( idDir = "ID" indexDir = "index" ) var ( dbEndpoint = path.Join(indexDir, "db") modulesEndpoint = path.Join(indexDir, "modules") ) func entryEndpoint(id string) string { return path.Join(idDir, id) } // dbMeta contains metadata about the database itself. type dbMeta struct { // Modified is the time the database was last modified, calculated // as the most recent time any single OSV entry was modified. Modified time.Time `json:"modified"` } // moduleMeta contains metadata about a Go module that has one // or more vulnerabilities in the database. // // Found in the "index/modules" endpoint of the vulnerability database. type moduleMeta struct { // Path is the module path. Path string `json:"path"` // Vulns is a list of vulnerabilities that affect this module. Vulns []moduleVuln `json:"vulns"` } // moduleVuln contains metadata about a vulnerability that affects // a certain module. type moduleVuln struct { // ID is a unique identifier for the vulnerability. // The Go vulnerability database issues IDs of the form // GO-<YEAR>-<ENTRYID>. ID string `json:"id"` // Modified is the time the vuln was last modified. Modified time.Time `json:"modified"` // Fixed is the latest version that introduces a fix for the // vulnerability, in SemVer 2.0.0 format, with no leading "v" prefix. Fixed string `json:"fixed,omitempty"` } // modulesIndex represents an in-memory modules index. type modulesIndex map[string]*moduleMeta func (m modulesIndex) MarshalJSON() ([]byte, error) { modules := make([]*moduleMeta, 0, len(m)) for _, module := range m { modules = append(modules, module) } sort.SliceStable(modules, func(i, j int) bool { return modules[i].Path < modules[j].Path }) for _, module := range modules { sort.SliceStable(module.Vulns, func(i, j int) bool { return module.Vulns[i].ID < module.Vulns[j].ID }) } return json.Marshal(modules) }
client
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/client_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package client import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "time" "github.com/google/go-cmp/cmp" "golang.org/x/vuln/internal/osv" "golang.org/x/vuln/internal/web" ) var ( testLegacyVulndb = filepath.Join("testdata", "vulndb-legacy") testLegacyVulndbFileURL = localURL(testLegacyVulndb) testVulndb = filepath.Join("testdata", "vulndb-v1") testVulndbFileURL = localURL(testVulndb) testFlatVulndb = filepath.Join("testdata", "vulndb-v1", "ID") testFlatVulndbFileURL = localURL(testFlatVulndb) testIDs = []string{ "GO-2021-0159", "GO-2022-0229", "GO-2022-0463", "GO-2022-0569", "GO-2022-0572", "GO-2021-0068", "GO-2022-0475", "GO-2022-0476", "GO-2021-0240", "GO-2021-0264", "GO-2022-0273", } ) func newTestServer(dir string) *httptest.Server { mux := http.NewServeMux() mux.Handle("/", http.FileServer(http.Dir(dir))) return httptest.NewServer(mux) } func entries(ids []string) ([]*osv.Entry, error) { if len(ids) == 0 { return nil, nil } entries := make([]*osv.Entry, len(ids)) for i, id := range ids { b, err := os.ReadFile(filepath.Join(testVulndb, idDir, id+".json")) if err != nil { return nil, err } var entry osv.Entry if err := json.Unmarshal(b, &entry); err != nil { return nil, err } entries[i] = &entry } return entries, nil } func localURL(dir string) string { absDir, err := filepath.Abs(dir) if err != nil { panic(fmt.Sprintf("failed to read %s: %v", dir, err)) } u, err := web.URLFromFilePath(absDir) if err != nil { panic(fmt.Sprintf("failed to read %s: %v", dir, err)) } return u.String() } func TestNewClient(t *testing.T) { t.Run("vuln.go.dev", func(t *testing.T) { src := "https://vuln.go.dev" c, err := NewClient(src, nil) if err != nil { t.Fatal(err) } if c == nil { t.Errorf("NewClient(%s) = nil, want instantiated *Client", src) } }) t.Run("http/v1", func(t *testing.T) { srv := newTestServer(testVulndb) t.Cleanup(srv.Close) c, err := NewClient(srv.URL, &Options{HTTPClient: srv.Client()}) if err != nil { t.Fatal(err) } if c == nil { t.Errorf("NewClient(%s) = nil, want instantiated *Client", srv.URL) } }) t.Run("http/legacy", func(t *testing.T) { srv := newTestServer(testLegacyVulndb) t.Cleanup(srv.Close) _, err := NewClient(srv.URL, &Options{HTTPClient: srv.Client()}) if err == nil || !errors.Is(err, errUnknownSchema) { t.Errorf("NewClient() = %s, want error %s", err, errUnknownSchema) } }) t.Run("local/v1", func(t *testing.T) { src := testVulndbFileURL c, err := NewClient(src, nil) if err != nil { t.Fatal(err) } if c == nil { t.Errorf("NewClient(%s) = nil, want instantiated *Client", src) } }) t.Run("local/flat", func(t *testing.T) { src := testFlatVulndbFileURL c, err := NewClient(src, nil) if err != nil { t.Fatal(err) } if c == nil { t.Errorf("NewClient(%s) = nil, want instantiated *Client", src) } }) t.Run("local/legacy", func(t *testing.T) { src := testLegacyVulndbFileURL _, err := NewClient(src, nil) if err == nil || !errors.Is(err, errUnknownSchema) { t.Errorf("NewClient() = %s, want error %s", err, errUnknownSchema) } }) } func TestLastModifiedTime(t *testing.T) { test := func(t *testing.T, c *Client) { got, err := c.LastModifiedTime(context.Background()) if err != nil { t.Fatal(err) } want, err := time.Parse(time.RFC3339, "2023-04-03T15:57:51Z") if err != nil { t.Fatal(err) } if got != want { t.Errorf("LastModifiedTime = %s, want %s", got, want) } } testAllClientTypes(t, test) } func TestByModules(t *testing.T) { tcs := []struct { module *ModuleRequest wantIDs []string }{ { module: &ModuleRequest{ Path: "github.com/beego/beego", }, wantIDs: []string{"GO-2022-0463", "GO-2022-0569", "GO-2022-0572"}, }, { module: &ModuleRequest{ Path: "github.com/beego/beego", // "GO-2022-0463" not affected at this version. Version: "1.12.10", }, wantIDs: []string{"GO-2022-0569", "GO-2022-0572"}, }, { module: &ModuleRequest{ Path: "stdlib", }, wantIDs: []string{"GO-2021-0159", "GO-2021-0240", "GO-2021-0264", "GO-2022-0229", "GO-2022-0273"}, }, { module: &ModuleRequest{ Path: "stdlib", Version: "go1.17", }, wantIDs: []string{"GO-2021-0264", "GO-2022-0273"}, }, { module: &ModuleRequest{ Path: "toolchain", }, wantIDs: []string{"GO-2021-0068", "GO-2022-0475", "GO-2022-0476"}, }, { module: &ModuleRequest{ Path: "toolchain", // All vulns affected at this version. Version: "1.14.13", }, wantIDs: []string{"GO-2021-0068", "GO-2022-0475", "GO-2022-0476"}, }, { module: &ModuleRequest{ Path: "golang.org/x/crypto", }, wantIDs: []string{"GO-2022-0229"}, }, { module: &ModuleRequest{ Path: "golang.org/x/crypto", // Vuln was fixed at exactly this version. Version: "1.13.7", }, wantIDs: nil, }, { module: &ModuleRequest{ Path: "does.not/exist", }, wantIDs: nil, }, { module: &ModuleRequest{ Path: "does.not/exist", Version: "1.0.0", }, wantIDs: nil, }, } // Test each case as an individual call to ByModules. for _, tc := range tcs { t.Run(tc.module.Path+"@"+tc.module.Version, func(t *testing.T) { test := func(t *testing.T, c *Client) { got, err := c.ByModules(context.Background(), []*ModuleRequest{tc.module}) if err != nil { t.Fatal(err) } wantEntries, err := entries(tc.wantIDs) if err != nil { t.Fatal(err) } want := []*ModuleResponse{{ Path: tc.module.Path, Version: tc.module.Version, Entries: wantEntries, }} if diff := cmp.Diff(want, got); diff != "" { t.Errorf("ByModule() mismatch (-want +got):\n%s", diff) } } testAllClientTypes(t, test) }) } // Now create a single test that makes all the requests // in a single call to ByModules. reqs := make([]*ModuleRequest, len(tcs)) want := make([]*ModuleResponse, len(tcs)) for i, tc := range tcs { reqs[i] = tc.module wantEntries, err := entries(tc.wantIDs) if err != nil { t.Fatal(err) } want[i] = &ModuleResponse{ Path: tc.module.Path, Version: tc.module.Version, Entries: wantEntries, } } t.Run("all", func(t *testing.T) { test := func(t *testing.T, c *Client) { got, err := c.ByModules(context.Background(), reqs) if err != nil { t.Fatal(err) } if diff := cmp.Diff(want, got); diff != "" { t.Errorf("ByModules() mismatch (-want +got):\n%s", diff) } } testAllClientTypes(t, test) }) } // testAllClientTypes runs a given test for all client types. func testAllClientTypes(t *testing.T, test func(t *testing.T, c *Client)) { t.Run("http", func(t *testing.T) { srv := newTestServer(testVulndb) t.Cleanup(srv.Close) hc, err := NewClient(srv.URL, &Options{HTTPClient: srv.Client()}) if err != nil { t.Fatal(err) } test(t, hc) }) t.Run("local", func(t *testing.T) { fc, err := NewClient(testVulndbFileURL, nil) if err != nil { t.Fatal(err) } test(t, fc) }) t.Run("hybrid", func(t *testing.T) { fc, err := NewClient(testFlatVulndbFileURL, nil) if err != nil { t.Fatal(err) } test(t, fc) }) t.Run("in-memory", func(t *testing.T) { testEntries, err := entries(testIDs) if err != nil { t.Fatal(err) } mc, err := NewInMemoryClient(testEntries) if err != nil { t.Fatal(err) } test(t, mc) }) }
client
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/index.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package client import ( "encoding/json" "fmt" "io/fs" "os" "path/filepath" "golang.org/x/vuln/internal/osv" isem "golang.org/x/vuln/internal/semver" ) // indexFromDir returns a raw index created from a directory // containing OSV entries. // It skips any non-JSON files but errors if any of the JSON files // cannot be unmarshaled into OSV, or have a filename other than <ID>.json. func indexFromDir(dir string) (map[string][]byte, error) { idx := newIndex() f := os.DirFS(dir) if err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { fname := d.Name() ext := filepath.Ext(fname) switch { case err != nil: return err case d.IsDir(): return nil case ext != ".json": return nil } b, err := fs.ReadFile(f, d.Name()) if err != nil { return err } var entry osv.Entry if err := json.Unmarshal(b, &entry); err != nil { return err } if fname != entry.ID+".json" { return fmt.Errorf("OSV entries must have filename of the form <ID>.json, got %s", fname) } idx.add(&entry) return nil }); err != nil { return nil, err } return idx.raw() } func indexFromEntries(entries []*osv.Entry) (map[string][]byte, error) { idx := newIndex() for _, entry := range entries { idx.add(entry) } return idx.raw() } type index struct { db *dbMeta modules modulesIndex } func newIndex() *index { return &index{ db: &dbMeta{}, modules: make(map[string]*moduleMeta), } } func (i *index) add(entry *osv.Entry) { // Add to db index. if entry.Modified.After(i.db.Modified) { i.db.Modified = entry.Modified } // Add to modules index. for _, affected := range entry.Affected { modulePath := affected.Module.Path if _, ok := i.modules[modulePath]; !ok { i.modules[modulePath] = &moduleMeta{ Path: modulePath, Vulns: []moduleVuln{}, } } module := i.modules[modulePath] module.Vulns = append(module.Vulns, moduleVuln{ ID: entry.ID, Modified: entry.Modified, Fixed: isem.NonSupersededFix(affected.Ranges), }) } } func (i *index) raw() (map[string][]byte, error) { data := make(map[string][]byte) b, err := json.Marshal(i.db) if err != nil { return nil, err } data[dbEndpoint] = b b, err = json.Marshal(i.modules) if err != nil { return nil, err } data[modulesEndpoint] = b return data, nil }
client
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/source_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package client import ( "context" "os" "testing" ) func TestGet(t *testing.T) { tcs := []struct { endpoint string }{ { endpoint: "index/db", }, { endpoint: "index/modules", }, { endpoint: "ID/GO-2021-0068", }, } for _, tc := range tcs { test := func(t *testing.T, s source) { got, err := s.get(context.Background(), tc.endpoint) if err != nil { t.Fatal(err) } want, err := os.ReadFile(testVulndb + "/" + tc.endpoint + ".json") if err != nil { t.Fatal(err) } if string(got) != string(want) { t.Errorf("get(%s) = %s, want %s", tc.endpoint, got, want) } } testAllSourceTypes(t, test) } } // testAllSourceTypes runs a given test for all source types. func testAllSourceTypes(t *testing.T, test func(t *testing.T, s source)) { t.Run("http", func(t *testing.T) { srv := newTestServer(testVulndb) hs := newHTTPSource(srv.URL, &Options{HTTPClient: srv.Client()}) test(t, hs) }) t.Run("local", func(t *testing.T) { test(t, newLocalSource(testVulndb)) }) t.Run("in-memory", func(t *testing.T) { testEntries, err := entries(testIDs) if err != nil { t.Fatal(err) } ms, err := newInMemorySource(testEntries) if err != nil { t.Fatal(err) } test(t, ms) }) t.Run("hybrid", func(t *testing.T) { hs, err := newHybridSource(testFlatVulndb) if err != nil { t.Fatal(err) } test(t, hs) }) }
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0463.json
{"schema_version":"1.3.1","id":"GO-2022-0463","modified":"2023-04-03T15:57:51Z","published":"2022-07-01T20:06:59Z","aliases":["CVE-2022-31259","GHSA-qx32-f6g6-fcfr"],"details":"Routes in the beego HTTP router can match unintended patterns. This overly-broad matching may permit an attacker to bypass access controls.\n\nFor example, the pattern \"/a/b/:name\" can match the URL \"/a.xml/b/\". This may bypass access control applied to the prefix \"/a/\".","affected":[{"package":{"name":"github.com/astaxie/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/astaxie/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.12.9"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","Tree.match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego/v2","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"2.0.3"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego/v2/server/web","symbols":["AddNamespace","AddViewPath","Any","AutoPrefix","AutoRouter","BuildTemplate","Compare","CompareNot","Controller.Abort","Controller.Bind","Controller.BindForm","Controller.BindJSON","Controller.BindProtobuf","Controller.BindXML","Controller.BindYAML","Controller.CheckXSRFCookie","Controller.CustomAbort","Controller.Delete","Controller.DestroySession","Controller.Get","Controller.GetBool","Controller.GetFile","Controller.GetFloat","Controller.GetInt","Controller.GetInt16","Controller.GetInt32","Controller.GetInt64","Controller.GetInt8","Controller.GetSecureCookie","Controller.GetString","Controller.GetStrings","Controller.GetUint16","Controller.GetUint32","Controller.GetUint64","Controller.GetUint8","Controller.Head","Controller.Input","Controller.IsAjax","Controller.JSONResp","Controller.Options","Controller.ParseForm","Controller.Patch","Controller.Post","Controller.Put","Controller.Redirect","Controller.Render","Controller.RenderBytes","Controller.RenderString","Controller.Resp","Controller.SaveToFile","Controller.SaveToFileWithBuffer","Controller.ServeFormatted","Controller.ServeJSON","Controller.ServeJSONP","Controller.ServeXML","Controller.ServeYAML","Controller.SessionRegenerateID","Controller.SetData","Controller.SetSecureCookie","Controller.Trace","Controller.URLFor","Controller.XMLResp","Controller.XSRFFormHTML","Controller.XSRFToken","Controller.YamlResp","ControllerRegister.Add","ControllerRegister.AddAuto","ControllerRegister.AddAutoPrefix","ControllerRegister.AddMethod","ControllerRegister.AddRouterMethod","ControllerRegister.Any","ControllerRegister.CtrlAny","ControllerRegister.CtrlDelete","ControllerRegister.CtrlGet","ControllerRegister.CtrlHead","ControllerRegister.CtrlOptions","ControllerRegister.CtrlPatch","ControllerRegister.CtrlPost","ControllerRegister.CtrlPut","ControllerRegister.Delete","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.Get","ControllerRegister.GetContext","ControllerRegister.Handler","ControllerRegister.Head","ControllerRegister.Include","ControllerRegister.Init","ControllerRegister.InsertFilter","ControllerRegister.Options","ControllerRegister.Patch","ControllerRegister.Post","ControllerRegister.Put","ControllerRegister.ServeHTTP","ControllerRegister.URLFor","CtrlAny","CtrlDelete","CtrlGet","CtrlHead","CtrlOptions","CtrlPatch","CtrlPost","CtrlPut","Date","DateFormat","DateParse","Delete","Exception","ExecuteTemplate","ExecuteViewPathTemplate","FileSystem.Open","FilterRouter.ValidRouter","FlashData.Error","FlashData.Notice","FlashData.Set","FlashData.Store","FlashData.Success","FlashData.Warning","Get","GetConfig","HTML2str","Handler","Head","Htmlquote","Htmlunquote","HttpServer.Any","HttpServer.AutoPrefix","HttpServer.AutoRouter","HttpServer.CtrlAny","HttpServer.CtrlDelete","HttpServer.CtrlGet","HttpServer.CtrlHead","HttpServer.CtrlOptions","HttpServer.CtrlPatch","HttpServer.CtrlPost","HttpServer.CtrlPut","HttpServer.Delete","HttpServer.Get","HttpServer.Handler","HttpServer.Head","HttpServer.Include","HttpServer.InsertFilter","HttpServer.LogAccess","HttpServer.Options","HttpServer.Patch","HttpServer.Post","HttpServer.PrintTree","HttpServer.Put","HttpServer.RESTRouter","HttpServer.Router","HttpServer.RouterWithOpts","HttpServer.Run","Include","InitBeegoBeforeTest","InsertFilter","LoadAppConfig","LogAccess","MapGet","Namespace.Any","Namespace.AutoPrefix","Namespace.AutoRouter","Namespace.Cond","Namespace.CtrlAny","Namespace.CtrlDelete","Namespace.CtrlGet","Namespace.CtrlHead","Namespace.CtrlOptions","Namespace.CtrlPatch","Namespace.CtrlPost","Namespace.CtrlPut","Namespace.Delete","Namespace.Filter","Namespace.Get","Namespace.Handler","Namespace.Head","Namespace.Include","Namespace.Namespace","Namespace.Options","Namespace.Patch","Namespace.Post","Namespace.Put","Namespace.Router","NewControllerRegister","NewControllerRegisterWithCfg","NewHttpServerWithCfg","NewHttpSever","NewNamespace","NotNil","Options","ParseForm","Patch","Policy","Post","PrintTree","Put","RESTRouter","ReadFromRequest","RenderForm","Router","RouterWithOpts","Run","RunWithMiddleWares","TestBeegoInit","Tree.AddRouter","Tree.AddTree","Tree.Match","Tree.match","URLFor","URLMap.GetMap","URLMap.GetMapData","Walk","adminApp.Run","adminController.AdminIndex","adminController.Healthcheck","adminController.ListConf","adminController.ProfIndex","adminController.PrometheusMetrics","adminController.QpsIndex","adminController.TaskStatus","beegoAppConfig.Bool","beegoAppConfig.DefaultBool"]}]}}],"references":[{"type":"FIX","url":"https://github.com/beego/beego/pull/4958"},{"type":"FIX","url":"https://github.com/beego/beego/commit/64cf44d725c8cc35d782327d333df9cbeb1bf2dd"},{"type":"WEB","url":"https://beego.vip"},{"type":"WEB","url":"https://github.com/beego/beego/issues/4946"},{"type":"WEB","url":"https://github.com/beego/beego/pull/4954"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0463"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0273.json
{"schema_version":"1.3.1","id":"GO-2022-0273","modified":"2023-04-03T15:57:51Z","published":"2022-05-18T18:23:31Z","aliases":["CVE-2021-39293"],"details":"The NewReader and OpenReader functions in archive/zip can cause a panic or an unrecoverable fatal error when reading an archive that claims to contain a large number of files, regardless of its actual size. This is caused by an incomplete fix for CVE-2021-33196.","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.16.8"},{"introduced":"1.17.0"},{"fixed":"1.17.1"}]}],"ecosystem_specific":{"imports":[{"path":"archive/zip","symbols":["NewReader","OpenReader"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/343434"},{"type":"FIX","url":"https://go.googlesource.com/go/+/bacbc33439b124ffd7392c91a5f5d96eca8c0c0b"},{"type":"REPORT","url":"https://go.dev/issue/47801"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/dx9d7IOseHw"}],"credits":[{"name":"OSS-Fuzz Project and Emmanuel Odeke"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0273"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2021-0240.json
{"schema_version":"1.3.1","id":"GO-2021-0240","modified":"2023-04-03T15:57:51Z","published":"2022-02-17T17:33:25Z","aliases":["CVE-2021-33196"],"details":"NewReader and OpenReader can cause a panic or an unrecoverable fatal error when reading an archive that claims to contain a large number of files, regardless of its actual size.","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.15.13"},{"introduced":"1.16.0"},{"fixed":"1.16.5"}]}],"ecosystem_specific":{"imports":[{"path":"archive/zip","symbols":["Reader.init"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/318909"},{"type":"FIX","url":"https://go.googlesource.com/go/+/74242baa4136c7a9132a8ccd9881354442788c8c"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/RgCMkAEQjSI"},{"type":"REPORT","url":"https://go.dev/issue/46242"}],"credits":[{"name":"the OSS-Fuzz project for discovering this issue and\nEmmanuel Odeke for reporting it\n"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0240"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2021-0264.json
{"schema_version":"1.3.1","id":"GO-2021-0264","modified":"2023-04-03T15:57:51Z","published":"2022-01-13T20:54:43Z","aliases":["CVE-2021-41772"],"details":"Previously, opening a zip with (*Reader).Open could result in a panic if the zip contained a file whose name was exclusively made up of slash characters or \"..\" path elements.\n\nOpen could also panic if passed the empty string directly as an argument.\n\nNow, any files in the zip whose name could not be made valid for fs.FS.Open will be skipped, and no longer added to the fs.FS file list, although they are still accessible through (*Reader).File.\n\nNote that it was already the case that a file could be accessible from (*Reader).Open with a name different from the one in (*Reader).File, as the former is the cleaned name, while the latter is the original one.\n\nFinally, the actual panic site was made robust as a defense-in-depth measure.","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.16.10"},{"introduced":"1.17.0"},{"fixed":"1.17.3"}]}],"ecosystem_specific":{"imports":[{"path":"archive/zip","symbols":["Reader.Open","split"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/349770"},{"type":"FIX","url":"https://go.googlesource.com/go/+/b24687394b55a93449e2be4e6892ead58ea9a10f"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/0fM21h43arc"},{"type":"REPORT","url":"https://go.dev/issue/48085"}],"credits":[{"name":"Colin Arnott, SiteHost and Noah Santschi-Cooney, Sourcegraph Code Intelligence Team"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0264"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0476.json
{"schema_version":"1.3.1","id":"GO-2022-0476","modified":"2023-04-03T15:57:51Z","published":"2022-07-28T17:24:43Z","aliases":["CVE-2020-28367"],"details":"The go command may execute arbitrary code at build time when cgo is in use. This may occur when running go get on a malicious package, or any other command that builds untrusted code.\n\nThis can be caused by malicious gcc flags specified via a cgo directive.","affected":[{"package":{"name":"toolchain","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.14.12"},{"introduced":"1.15.0"},{"fixed":"1.15.5"}]}],"ecosystem_specific":{"imports":[{"path":"cmd/go","symbols":["validCompilerFlags"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/267277"},{"type":"FIX","url":"https://go.googlesource.com/go/+/da7aa86917811a571e6634b45a457f918b8e6561"},{"type":"REPORT","url":"https://go.dev/issue/42556"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/NpBGTTmKzpM"}],"credits":[{"name":"Imre Rad"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0476"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2021-0068.json
{"schema_version":"1.3.1","id":"GO-2021-0068","modified":"2023-04-03T15:57:51Z","published":"2021-04-14T20:04:52Z","aliases":["CVE-2021-3115"],"details":"The go command may execute arbitrary code at build time when using cgo on Windows. This can be triggered by running go get on a malicious module, or any other time the code is built.","affected":[{"package":{"name":"toolchain","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.14.14"},{"introduced":"1.15.0"},{"fixed":"1.15.7"}]}],"ecosystem_specific":{"imports":[{"path":"cmd/go","goos":["windows"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/284783"},{"type":"FIX","url":"https://go.googlesource.com/go/+/953d1feca9b21af075ad5fc8a3dad096d3ccc3a0"},{"type":"REPORT","url":"https://go.dev/issue/43783"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/mperVMGa98w/m/yo5W5wnvAAAJ"},{"type":"FIX","url":"https://go.dev/cl/284780"},{"type":"FIX","url":"https://go.googlesource.com/go/+/46e2e2e9d99925bbf724b12693c6d3e27a95d6a0"}],"credits":[{"name":"RyotaK"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0068"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0229.json
{"schema_version":"1.3.1","id":"GO-2022-0229","modified":"2023-04-03T15:57:51Z","published":"2022-07-06T18:23:48Z","aliases":["CVE-2020-7919","GHSA-cjjc-xp8v-855w"],"details":"On 32-bit architectures, a malformed input to crypto/x509 or the ASN.1 parsing functions of golang.org/x/crypto/cryptobyte can lead to a panic.\n\nThe malformed certificate can be delivered via a crypto/tls connection to a client, or to a server that accepts client certificates. net/http clients can be made to crash by an HTTPS server, while net/http servers that accept client certificates will recover the panic and are unaffected.","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.12.16"},{"introduced":"1.13.0"},{"fixed":"1.13.7"}]}],"ecosystem_specific":{"imports":[{"path":"crypto/x509"}]}},{"package":{"name":"golang.org/x/crypto","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"0.0.0-20200124225646-8b5121be2f68"}]}],"ecosystem_specific":{"imports":[{"path":"golang.org/x/crypto/cryptobyte"}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/216680"},{"type":"FIX","url":"https://go.googlesource.com/go/+/b13ce14c4a6aa59b7b041ad2b6eed2d23e15b574"},{"type":"FIX","url":"https://go.dev/cl/216677"},{"type":"REPORT","url":"https://go.dev/issue/36837"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/Hsw4mHYc470"}],"credits":[{"name":"Project Wycheproof"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0229"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0475.json
{"schema_version":"1.3.1","id":"GO-2022-0475","modified":"2023-04-03T15:57:51Z","published":"2022-07-28T17:24:30Z","aliases":["CVE-2020-28366"],"details":"The go command may execute arbitrary code at build time when cgo is in use. This may occur when running go get on a malicious package, or any other command that builds untrusted code.\n\nThis can be caused by malicious unquoted symbol name in a linked object file.","affected":[{"package":{"name":"toolchain","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.14.12"},{"introduced":"1.15.0"},{"fixed":"1.15.5"}]}],"ecosystem_specific":{"imports":[{"path":"cmd/go","symbols":["Builder.cgo"]},{"path":"cmd/cgo","symbols":["dynimport"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/269658"},{"type":"FIX","url":"https://go.googlesource.com/go/+/062e0e5ce6df339dc26732438ad771f73dbf2292"},{"type":"REPORT","url":"https://go.dev/issue/42559"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/NpBGTTmKzpM"}],"credits":[{"name":"Chris Brown and Tempus Ex"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0475"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0572.json
{"schema_version":"1.3.1","id":"GO-2022-0572","modified":"2023-04-03T15:57:51Z","published":"2022-08-22T17:56:17Z","aliases":["CVE-2021-30080","GHSA-28r6-jm5h-mrgg"],"details":"An issue was discovered in the route lookup process in beego which attackers to bypass access control.","affected":[{"package":{"name":"github.com/astaxie/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/astaxie/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego/v2","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"2.0.0"},{"fixed":"2.0.3"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego/v2/server/web","symbols":["AddNamespace","AddViewPath","Any","AutoPrefix","AutoRouter","BuildTemplate","Compare","CompareNot","Controller.Abort","Controller.CheckXSRFCookie","Controller.CustomAbort","Controller.Delete","Controller.DestroySession","Controller.Get","Controller.GetBool","Controller.GetFile","Controller.GetFloat","Controller.GetInt","Controller.GetInt16","Controller.GetInt32","Controller.GetInt64","Controller.GetInt8","Controller.GetSecureCookie","Controller.GetString","Controller.GetStrings","Controller.GetUint16","Controller.GetUint32","Controller.GetUint64","Controller.GetUint8","Controller.Head","Controller.Input","Controller.IsAjax","Controller.Options","Controller.ParseForm","Controller.Patch","Controller.Post","Controller.Put","Controller.Redirect","Controller.Render","Controller.RenderBytes","Controller.RenderString","Controller.SaveToFile","Controller.ServeFormatted","Controller.ServeJSON","Controller.ServeJSONP","Controller.ServeXML","Controller.ServeYAML","Controller.SessionRegenerateID","Controller.SetData","Controller.SetSecureCookie","Controller.Trace","Controller.URLFor","Controller.XSRFFormHTML","Controller.XSRFToken","ControllerRegister.Add","ControllerRegister.AddAuto","ControllerRegister.AddAutoPrefix","ControllerRegister.AddMethod","ControllerRegister.Any","ControllerRegister.Delete","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.Get","ControllerRegister.GetContext","ControllerRegister.Handler","ControllerRegister.Head","ControllerRegister.Include","ControllerRegister.InsertFilter","ControllerRegister.InsertFilterChain","ControllerRegister.Options","ControllerRegister.Patch","ControllerRegister.Post","ControllerRegister.Put","ControllerRegister.ServeHTTP","ControllerRegister.URLFor","Date","DateFormat","DateParse","Delete","Exception","ExecuteTemplate","ExecuteViewPathTemplate","FileSystem.Open","FilterRouter.ValidRouter","FlashData.Error","FlashData.Notice","FlashData.Set","FlashData.Store","FlashData.Success","FlashData.Warning","Get","GetConfig","HTML2str","Handler","Head","Htmlquote","Htmlunquote","HttpServer.Any","HttpServer.AutoPrefix","HttpServer.AutoRouter","HttpServer.Delete","HttpServer.Get","HttpServer.Handler","HttpServer.Head","HttpServer.Include","HttpServer.InsertFilter","HttpServer.InsertFilterChain","HttpServer.LogAccess","HttpServer.Options","HttpServer.Patch","HttpServer.Post","HttpServer.PrintTree","HttpServer.Put","HttpServer.RESTRouter","HttpServer.Router","HttpServer.Run","Include","InitBeegoBeforeTest","InsertFilter","InsertFilterChain","LoadAppConfig","LogAccess","MapGet","Namespace.Any","Namespace.AutoPrefix","Namespace.AutoRouter","Namespace.Cond","Namespace.Delete","Namespace.Filter","Namespace.Get","Namespace.Handler","Namespace.Head","Namespace.Include","Namespace.Namespace","Namespace.Options","Namespace.Patch","Namespace.Post","Namespace.Put","Namespace.Router","NewControllerRegister","NewControllerRegisterWithCfg","NewHttpServerWithCfg","NewHttpSever","NewNamespace","NotNil","Options","ParseForm","Patch","Policy","Post","PrintTree","Put","RESTRouter","ReadFromRequest","RenderForm","Router","Run","RunWithMiddleWares","TestBeegoInit","Tree.AddRouter","Tree.AddTree","Tree.Match","URLFor","URLMap.GetMap","URLMap.GetMapData","Walk","adminApp.Run","adminController.AdminIndex","adminController.Healthcheck","adminController.ListConf","adminController.ProfIndex","adminController.PrometheusMetrics","adminController.QpsIndex","adminController.TaskStatus","beegoAppConfig.Bool","beegoAppConfig.DefaultBool"]}]}}],"references":[{"type":"FIX","url":"https://github.com/beego/beego/pull/4459"},{"type":"FIX","url":"https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0572"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2022-0569.json
{"schema_version":"1.3.1","id":"GO-2022-0569","modified":"2023-04-03T15:57:51Z","published":"2022-08-23T13:24:17Z","aliases":["CVE-2022-31836","GHSA-95f9-94vc-665h"],"details":"The leafInfo.match() function uses path.join() to deal with wildcard values which can lead to cross directory risk.","affected":[{"package":{"name":"github.com/astaxie/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/astaxie/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.12.11"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego","symbols":["App.Run","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.ServeHTTP","FilterRouter.ValidRouter","InitBeegoBeforeTest","Run","RunWithMiddleWares","TestBeegoInit","Tree.Match","adminApp.Run"]}]}},{"package":{"name":"github.com/beego/beego/v2","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"2.0.0"},{"fixed":"2.0.4"}]}],"ecosystem_specific":{"imports":[{"path":"github.com/beego/beego/v2/server/web","symbols":["AddNamespace","AddViewPath","Any","AutoPrefix","AutoRouter","BuildTemplate","Compare","CompareNot","Controller.Abort","Controller.Bind","Controller.BindForm","Controller.BindJSON","Controller.BindProtobuf","Controller.BindXML","Controller.BindYAML","Controller.CheckXSRFCookie","Controller.CustomAbort","Controller.Delete","Controller.DestroySession","Controller.Get","Controller.GetBool","Controller.GetFile","Controller.GetFloat","Controller.GetInt","Controller.GetInt16","Controller.GetInt32","Controller.GetInt64","Controller.GetInt8","Controller.GetSecureCookie","Controller.GetString","Controller.GetStrings","Controller.GetUint16","Controller.GetUint32","Controller.GetUint64","Controller.GetUint8","Controller.Head","Controller.Input","Controller.IsAjax","Controller.JSONResp","Controller.Options","Controller.ParseForm","Controller.Patch","Controller.Post","Controller.Put","Controller.Redirect","Controller.Render","Controller.RenderBytes","Controller.RenderString","Controller.Resp","Controller.SaveToFile","Controller.SaveToFileWithBuffer","Controller.ServeFormatted","Controller.ServeJSON","Controller.ServeJSONP","Controller.ServeXML","Controller.ServeYAML","Controller.SessionRegenerateID","Controller.SetData","Controller.SetSecureCookie","Controller.Trace","Controller.URLFor","Controller.XMLResp","Controller.XSRFFormHTML","Controller.XSRFToken","Controller.YamlResp","ControllerRegister.Add","ControllerRegister.AddAuto","ControllerRegister.AddAutoPrefix","ControllerRegister.AddMethod","ControllerRegister.AddRouterMethod","ControllerRegister.Any","ControllerRegister.CtrlAny","ControllerRegister.CtrlDelete","ControllerRegister.CtrlGet","ControllerRegister.CtrlHead","ControllerRegister.CtrlOptions","ControllerRegister.CtrlPatch","ControllerRegister.CtrlPost","ControllerRegister.CtrlPut","ControllerRegister.Delete","ControllerRegister.FindPolicy","ControllerRegister.FindRouter","ControllerRegister.Get","ControllerRegister.GetContext","ControllerRegister.Handler","ControllerRegister.Head","ControllerRegister.Include","ControllerRegister.Init","ControllerRegister.InsertFilter","ControllerRegister.Options","ControllerRegister.Patch","ControllerRegister.Post","ControllerRegister.Put","ControllerRegister.ServeHTTP","ControllerRegister.URLFor","CtrlAny","CtrlDelete","CtrlGet","CtrlHead","CtrlOptions","CtrlPatch","CtrlPost","CtrlPut","Date","DateFormat","DateParse","Delete","Exception","ExecuteTemplate","ExecuteViewPathTemplate","FileSystem.Open","FilterRouter.ValidRouter","FlashData.Error","FlashData.Notice","FlashData.Set","FlashData.Store","FlashData.Success","FlashData.Warning","Get","GetConfig","HTML2str","Handler","Head","Htmlquote","Htmlunquote","HttpServer.Any","HttpServer.AutoPrefix","HttpServer.AutoRouter","HttpServer.CtrlAny","HttpServer.CtrlDelete","HttpServer.CtrlGet","HttpServer.CtrlHead","HttpServer.CtrlOptions","HttpServer.CtrlPatch","HttpServer.CtrlPost","HttpServer.CtrlPut","HttpServer.Delete","HttpServer.Get","HttpServer.Handler","HttpServer.Head","HttpServer.Include","HttpServer.InsertFilter","HttpServer.LogAccess","HttpServer.Options","HttpServer.Patch","HttpServer.Post","HttpServer.PrintTree","HttpServer.Put","HttpServer.RESTRouter","HttpServer.Router","HttpServer.RouterWithOpts","HttpServer.Run","Include","InitBeegoBeforeTest","InsertFilter","LoadAppConfig","LogAccess","MapGet","Namespace.Any","Namespace.AutoPrefix","Namespace.AutoRouter","Namespace.Cond","Namespace.CtrlAny","Namespace.CtrlDelete","Namespace.CtrlGet","Namespace.CtrlHead","Namespace.CtrlOptions","Namespace.CtrlPatch","Namespace.CtrlPost","Namespace.CtrlPut","Namespace.Delete","Namespace.Filter","Namespace.Get","Namespace.Handler","Namespace.Head","Namespace.Include","Namespace.Namespace","Namespace.Options","Namespace.Patch","Namespace.Post","Namespace.Put","Namespace.Router","NewControllerRegister","NewControllerRegisterWithCfg","NewHttpServerWithCfg","NewHttpSever","NewNamespace","NotNil","Options","ParseForm","Patch","Policy","Post","PrintTree","Put","RESTRouter","ReadFromRequest","RenderForm","Router","RouterWithOpts","Run","RunWithMiddleWares","TestBeegoInit","Tree.AddRouter","Tree.AddTree","Tree.Match","URLFor","URLMap.GetMap","URLMap.GetMapData","Walk","adminApp.Run","adminController.AdminIndex","adminController.Healthcheck","adminController.ListConf","adminController.ProfIndex","adminController.PrometheusMetrics","adminController.QpsIndex","adminController.TaskStatus","beegoAppConfig.Bool","beegoAppConfig.DefaultBool"]}]}}],"references":[{"type":"FIX","url":"https://github.com/beego/beego/pull/5025"},{"type":"FIX","url":"https://github.com/beego/beego/pull/5025/commits/ea5ae58d40589d249cf577a053e490509de2bf57"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2022-0569"}}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/ID/GO-2021-0159.json
{"schema_version":"1.3.1","id":"GO-2021-0159","modified":"2023-04-03T15:57:51Z","published":"2022-01-05T21:39:14Z","aliases":["CVE-2015-5739","CVE-2015-5740","CVE-2015-5741"],"details":"HTTP headers were not properly parsed, which allows remote attackers to conduct HTTP request smuggling attacks via a request that contains Content-Length and Transfer-Encoding header fields.","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.4.3"}]}],"ecosystem_specific":{"imports":[{"path":"net/http","symbols":["CanonicalMIMEHeaderKey","body.readLocked","canonicalMIMEHeaderKey","chunkWriter.writeHeader","fixLength","fixTransferEncoding","readTransfer","transferWriter.shouldSendContentLength","validHeaderFieldByte"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/13148"},{"type":"FIX","url":"https://go.googlesource.com/go/+/26049f6f9171d1190f3bbe05ec304845cfe6399f"},{"type":"FIX","url":"https://go.dev/cl/11772"},{"type":"FIX","url":"https://go.dev/cl/11810"},{"type":"FIX","url":"https://go.dev/cl/12865"},{"type":"FIX","url":"https://go.googlesource.com/go/+/117ddcb83d7f42d6aa72241240af99ded81118e9"},{"type":"FIX","url":"https://go.googlesource.com/go/+/300d9a21583e7cf0149a778a0611e76ff7c6680f"},{"type":"FIX","url":"https://go.googlesource.com/go/+/c2db5f4ccc61ba7df96a747e268a277b802cbb87"},{"type":"REPORT","url":"https://go.dev/issue/12027"},{"type":"REPORT","url":"https://go.dev/issue/11930"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/iSIyW4lM4hY/m/ADuQR4DiDwAJ"}],"credits":[{"name":"Jed Denlea and Régis Leroy"}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0159"}}
index
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/index/modules.json
[{"path":"github.com/astaxie/beego","vulns":[{"id":"GO-2022-0463","modified":"2023-04-03T15:57:51Z"},{"id":"GO-2022-0569","modified":"2023-04-03T15:57:51Z"},{"id":"GO-2022-0572","modified":"2023-04-03T15:57:51Z"}]},{"path":"github.com/beego/beego","vulns":[{"id":"GO-2022-0463","modified":"2023-04-03T15:57:51Z","fixed":"1.12.9"},{"id":"GO-2022-0569","modified":"2023-04-03T15:57:51Z","fixed":"1.12.11"},{"id":"GO-2022-0572","modified":"2023-04-03T15:57:51Z"}]},{"path":"github.com/beego/beego/v2","vulns":[{"id":"GO-2022-0463","modified":"2023-04-03T15:57:51Z","fixed":"2.0.3"},{"id":"GO-2022-0569","modified":"2023-04-03T15:57:51Z","fixed":"2.0.4"},{"id":"GO-2022-0572","modified":"2023-04-03T15:57:51Z","fixed":"2.0.3"}]},{"path":"golang.org/x/crypto","vulns":[{"id":"GO-2022-0229","modified":"2023-04-03T15:57:51Z","fixed":"0.0.0-20200124225646-8b5121be2f68"}]},{"path":"stdlib","vulns":[{"id":"GO-2021-0159","modified":"2023-04-03T15:57:51Z","fixed":"1.4.3"},{"id":"GO-2021-0240","modified":"2023-04-03T15:57:51Z","fixed":"1.16.5"},{"id":"GO-2021-0264","modified":"2023-04-03T15:57:51Z","fixed":"1.17.3"},{"id":"GO-2022-0229","modified":"2023-04-03T15:57:51Z","fixed":"1.13.7"},{"id":"GO-2022-0273","modified":"2023-04-03T15:57:51Z","fixed":"1.17.1"}]},{"path":"toolchain","vulns":[{"id":"GO-2021-0068","modified":"2023-04-03T15:57:51Z","fixed":"1.15.7"},{"id":"GO-2022-0475","modified":"2023-04-03T15:57:51Z","fixed":"1.15.5"},{"id":"GO-2022-0476","modified":"2023-04-03T15:57:51Z","fixed":"1.15.5"}]}]
index
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/index/vulns.json
[{"id":"GO-2021-0068","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2021-3115"]},{"id":"GO-2021-0159","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2015-5739","CVE-2015-5740","CVE-2015-5741"]},{"id":"GO-2021-0240","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2021-33196"]},{"id":"GO-2021-0264","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2021-41772"]},{"id":"GO-2022-0229","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2020-7919","GHSA-cjjc-xp8v-855w"]},{"id":"GO-2022-0273","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2021-39293"]},{"id":"GO-2022-0463","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2022-31259","GHSA-qx32-f6g6-fcfr"]},{"id":"GO-2022-0475","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2020-28366"]},{"id":"GO-2022-0476","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2020-28367"]},{"id":"GO-2022-0569","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2022-31836","GHSA-95f9-94vc-665h"]},{"id":"GO-2022-0572","modified":"2023-04-03T15:57:51Z","aliases":["CVE-2021-30080","GHSA-28r6-jm5h-mrgg"]}]
index
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-v1/index/db.json
{"modified":"2023-04-03T15:57:51Z"}
vulndb-legacy
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/aliases.json
{ "CVE-2013-10005": [ "GO-2020-0024" ], "CVE-2014-125026": [ "GO-2020-0022" ], "CVE-2014-7189": [ "GO-2021-0154" ], "CVE-2014-8681": [ "GO-2020-0021" ], "CVE-2015-10004": [ "GO-2020-0023" ], "CVE-2015-1340": [ "GO-2021-0071" ], "CVE-2015-5305": [ "GO-2022-0701" ], "CVE-2015-5739": [ "GO-2021-0157", "GO-2021-0159" ], "CVE-2015-5740": [ "GO-2021-0159" ], "CVE-2015-5741": [ "GO-2021-0159" ], "CVE-2015-8618": [ "GO-2021-0160" ], "CVE-2016-15005": [ "GO-2020-0045" ], "CVE-2016-3697": [ "GO-2021-0070" ], "CVE-2016-3958": [ "GO-2021-0163" ], "CVE-2016-3959": [ "GO-2022-0166" ], "CVE-2016-5386": [ "GO-2022-0761" ], "CVE-2016-9121": [ "GO-2020-0010" ], "CVE-2016-9122": [ "GO-2020-0011", "GO-2022-0945" ], "CVE-2016-9123": [ "GO-2020-0009" ], "CVE-2017-1000097": [ "GO-2022-0171" ], "CVE-2017-1000098": [ "GO-2021-0172" ], "CVE-2017-11468": [ "GO-2021-0072" ], "CVE-2017-11480": [ "GO-2022-0643" ], "CVE-2017-15041": [ "GO-2022-0177" ], "CVE-2017-15042": [ "GO-2021-0178" ], "CVE-2017-15133": [ "GO-2020-0006" ], "CVE-2017-17831": [ "GO-2021-0073" ], "CVE-2017-18367": [ "GO-2020-0007" ], "CVE-2017-20146": [ "GO-2020-0020" ], "CVE-2017-3204": [ "GO-2020-0013" ], "CVE-2017-8932": [ "GO-2022-0187" ], "CVE-2018-1103": [ "GO-2020-0026" ], "CVE-2018-12018": [ "GO-2021-0075" ], "CVE-2018-14632": [ "GO-2021-0076" ], "CVE-2018-16873": [ "GO-2022-0189" ], "CVE-2018-16874": [ "GO-2022-0190" ], "CVE-2018-16875": [ "GO-2022-0191" ], "CVE-2018-16886": [ "GO-2021-0077" ], "CVE-2018-17075": [ "GO-2021-0078" ], "CVE-2018-17142": [ "GO-2022-0192" ], "CVE-2018-17143": [ "GO-2022-0193" ], "CVE-2018-17419": [ "GO-2020-0028" ], "CVE-2018-17846": [ "GO-2020-0014" ], "CVE-2018-17847": [ "GO-2022-0197" ], "CVE-2018-17848": [ "GO-2022-0197" ], "CVE-2018-18206": [ "GO-2021-0079" ], "CVE-2018-21246": [ "GO-2020-0043" ], "CVE-2018-25046": [ "GO-2020-0025" ], "CVE-2018-6558": [ "GO-2020-0027" ], "CVE-2018-6574": [ "GO-2022-0201" ], "CVE-2018-7187": [ "GO-2022-0203" ], "CVE-2019-0210": [ "GO-2021-0101" ], "CVE-2019-10214": [ "GO-2021-0081" ], "CVE-2019-10223": [ "GO-2022-0621" ], "CVE-2019-11250": [ "GO-2021-0065" ], "CVE-2019-11254": [ "GO-2020-0036" ], "CVE-2019-11289": [ "GO-2021-0102" ], "CVE-2019-11840": [ "GO-2022-0209" ], "CVE-2019-11939": [ "GO-2021-0082" ], "CVE-2019-12496": [ "GO-2021-0083" ], "CVE-2019-13209": [ "GO-2022-0755" ], "CVE-2019-14809": [ "GO-2022-0211" ], "CVE-2019-16276": [ "GO-2022-0212" ], "CVE-2019-16354": [ "GO-2021-0084" ], "CVE-2019-16884": [ "GO-2021-0085" ], "CVE-2019-17110": [ "GO-2022-0621" ], "CVE-2019-17596": [ "GO-2022-0213" ], "CVE-2019-19619": [ "GO-2021-0086" ], "CVE-2019-19794": [ "GO-2020-0008" ], "CVE-2019-19921": [ "GO-2021-0087" ], "CVE-2019-20786": [ "GO-2020-0038" ], "CVE-2019-25072": [ "GO-2020-0037" ], "CVE-2019-25073": [ "GO-2020-0032" ], "CVE-2019-3564": [ "GO-2021-0088" ], "CVE-2019-6486": [ "GO-2022-0217" ], "CVE-2019-9512": [ "GO-2022-0536" ], "CVE-2019-9514": [ "GO-2022-0536" ], "CVE-2019-9634": [ "GO-2022-0220" ], "CVE-2020-0601": [ "GO-2022-0535" ], "CVE-2020-10675": [ "GO-2021-0089" ], "CVE-2020-12666": [ "GO-2020-0039" ], "CVE-2020-14039": [ "GO-2021-0223" ], "CVE-2020-14040": [ "GO-2020-0015" ], "CVE-2020-15091": [ "GO-2021-0090" ], "CVE-2020-15106": [ "GO-2020-0005" ], "CVE-2020-15111": [ "GO-2021-0091", "GO-2021-0108" ], "CVE-2020-15112": [ "GO-2020-0005" ], "CVE-2020-15216": [ "GO-2020-0050" ], "CVE-2020-15222": [ "GO-2021-0092", "GO-2021-0110" ], "CVE-2020-15223": [ "GO-2021-0109" ], "CVE-2020-15586": [ "GO-2021-0224" ], "CVE-2020-16845": [ "GO-2021-0142" ], "CVE-2020-24553": [ "GO-2021-0226" ], "CVE-2020-25614": [ "GO-2020-0048" ], "CVE-2020-26160": [ "GO-2020-0017" ], "CVE-2020-26242": [ "GO-2021-0103" ], "CVE-2020-26264": [ "GO-2021-0063" ], "CVE-2020-26265": [ "GO-2021-0105" ], "CVE-2020-26290": [ "GO-2020-0050" ], "CVE-2020-26521": [ "GO-2022-0402" ], "CVE-2020-26892": [ "GO-2022-0380" ], "CVE-2020-27813": [ "GO-2020-0019" ], "CVE-2020-27846": [ "GO-2021-0058" ], "CVE-2020-27847": [ "GO-2020-0050" ], "CVE-2020-28362": [ "GO-2021-0069" ], "CVE-2020-28366": [ "GO-2022-0475" ], "CVE-2020-28367": [ "GO-2022-0476" ], "CVE-2020-28483": [ "GO-2020-0029", "GO-2021-0052" ], "CVE-2020-29242": [ "GO-2021-0097" ], "CVE-2020-29243": [ "GO-2021-0097" ], "CVE-2020-29244": [ "GO-2021-0097" ], "CVE-2020-29245": [ "GO-2021-0097" ], "CVE-2020-29509": [ "GO-2021-0060" ], "CVE-2020-29529": [ "GO-2021-0094" ], "CVE-2020-29652": [ "GO-2021-0227" ], "CVE-2020-35380": [ "GO-2021-0059" ], "CVE-2020-35381": [ "GO-2021-0057" ], "CVE-2020-36066": [ "GO-2022-0957" ], "CVE-2020-36067": [ "GO-2021-0054" ], "CVE-2020-36559": [ "GO-2020-0033" ], "CVE-2020-36560": [ "GO-2020-0034" ], "CVE-2020-36561": [ "GO-2020-0035" ], "CVE-2020-36562": [ "GO-2020-0040" ], "CVE-2020-36563": [ "GO-2020-0047" ], "CVE-2020-36564": [ "GO-2020-0049" ], "CVE-2020-36565": [ "GO-2021-0051" ], "CVE-2020-36566": [ "GO-2021-0106" ], "CVE-2020-36567": [ "GO-2020-0001" ], "CVE-2020-36568": [ "GO-2020-0003" ], "CVE-2020-36569": [ "GO-2020-0004" ], "CVE-2020-7664": [ "GO-2021-0228" ], "CVE-2020-7667": [ "GO-2020-0042" ], "CVE-2020-7668": [ "GO-2020-0041" ], "CVE-2020-7711": [ "GO-2020-0046" ], "CVE-2020-7919": [ "GO-2022-0229" ], "CVE-2020-8564": [ "GO-2021-0066" ], "CVE-2020-8565": [ "GO-2021-0064" ], "CVE-2020-8568": [ "GO-2022-0629" ], "CVE-2020-8911": [ "GO-2022-0646" ], "CVE-2020-8918": [ "GO-2021-0095" ], "CVE-2020-8945": [ "GO-2020-0002", "GO-2020-0031", "GO-2021-0096" ], "CVE-2020-9283": [ "GO-2020-0012" ], "CVE-2021-20206": [ "GO-2022-0230" ], "CVE-2021-20291": [ "GO-2021-0100" ], "CVE-2021-20329": [ "GO-2021-0111", "GO-2021-0112" ], "CVE-2021-21237": [ "GO-2021-0098" ], "CVE-2021-21272": [ "GO-2021-0099" ], "CVE-2021-22133": [ "GO-2022-0706" ], "CVE-2021-23409": [ "GO-2022-0233" ], "CVE-2021-23772": [ "GO-2022-0272" ], "CVE-2021-27918": [ "GO-2021-0234" ], "CVE-2021-27919": [ "GO-2021-0067" ], "CVE-2021-28681": [ "GO-2021-0104" ], "CVE-2021-29272": [ "GO-2022-0762" ], "CVE-2021-29482": [ "GO-2020-0016" ], "CVE-2021-30080": [ "GO-2022-0572" ], "CVE-2021-3114": [ "GO-2021-0235" ], "CVE-2021-3115": [ "GO-2021-0068" ], "CVE-2021-3121": [ "GO-2021-0053" ], "CVE-2021-3127": [ "GO-2022-0386" ], "CVE-2021-31525": [ "GO-2022-0236" ], "CVE-2021-32690": [ "GO-2022-0384" ], "CVE-2021-32721": [ "GO-2021-0237" ], "CVE-2021-33194": [ "GO-2021-0238" ], "CVE-2021-33195": [ "GO-2021-0239" ], "CVE-2021-33196": [ "GO-2021-0240" ], "CVE-2021-33197": [ "GO-2021-0241" ], "CVE-2021-33198": [ "GO-2021-0242" ], "CVE-2021-34558": [ "GO-2021-0243" ], "CVE-2021-3538": [ "GO-2020-0018", "GO-2022-0244" ], "CVE-2021-3602": [ "GO-2022-0345" ], "CVE-2021-36221": [ "GO-2021-0245" ], "CVE-2021-3761": [ "GO-2022-0246" ], "CVE-2021-3762": [ "GO-2022-0346" ], "CVE-2021-38297": [ "GO-2022-0247" ], "CVE-2021-38561": [ "GO-2021-0113" ], "CVE-2021-3907": [ "GO-2022-0248" ], "CVE-2021-3910": [ "GO-2022-0251" ], "CVE-2021-3911": [ "GO-2022-0252" ], "CVE-2021-3912": [ "GO-2022-0253" ], "CVE-2021-39137": [ "GO-2022-0254" ], "CVE-2021-39293": [ "GO-2022-0273" ], "CVE-2021-41173": [ "GO-2022-0256" ], "CVE-2021-41230": [ "GO-2021-0258" ], "CVE-2021-41771": [ "GO-2021-0263" ], "CVE-2021-41772": [ "GO-2021-0264" ], "CVE-2021-42248": [ "GO-2021-0265" ], "CVE-2021-4235": [ "GO-2021-0061" ], "CVE-2021-4236": [ "GO-2021-0107" ], "CVE-2021-4238": [ "GO-2022-0411" ], "CVE-2021-4239": [ "GO-2022-0425" ], "CVE-2021-42576": [ "GO-2022-0588" ], "CVE-2021-42836": [ "GO-2021-0265" ], "CVE-2021-43784": [ "GO-2022-0274" ], "CVE-2021-44716": [ "GO-2022-0288" ], "CVE-2021-44717": [ "GO-2022-0289" ], "CVE-2021-46398": [ "GO-2022-0563" ], "CVE-2022-0317": [ "GO-2022-0294" ], "CVE-2022-1227": [ "GO-2022-0558" ], "CVE-2022-1705": [ "GO-2022-0525" ], "CVE-2022-1962": [ "GO-2022-0515" ], "CVE-2022-1996": [ "GO-2022-0619" ], "CVE-2022-21221": [ "GO-2022-0355" ], "CVE-2022-21235": [ "GO-2022-0414" ], "CVE-2022-21698": [ "GO-2022-0322" ], "CVE-2022-21708": [ "GO-2022-0300" ], "CVE-2022-23628": [ "GO-2022-0316" ], "CVE-2022-23772": [ "GO-2021-0317" ], "CVE-2022-23773": [ "GO-2022-0318" ], "CVE-2022-23806": [ "GO-2021-0319" ], "CVE-2022-24675": [ "GO-2022-0433" ], "CVE-2022-24778": [ "GO-2021-0412" ], "CVE-2022-24912": [ "GO-2022-0534" ], "CVE-2022-24921": [ "GO-2021-0347" ], "CVE-2022-24968": [ "GO-2021-0321", "GO-2022-0370", "GO-2022-0947" ], "CVE-2022-2582": [ "GO-2022-0391" ], "CVE-2022-2583": [ "GO-2022-0400" ], "CVE-2022-2584": [ "GO-2022-0422" ], "CVE-2022-25856": [ "GO-2022-0492" ], "CVE-2022-25891": [ "GO-2022-0528" ], "CVE-2022-26945": [ "GO-2022-0586" ], "CVE-2022-27191": [ "GO-2021-0356" ], "CVE-2022-27536": [ "GO-2022-0434" ], "CVE-2022-27651": [ "GO-2022-0417" ], "CVE-2022-28131": [ "GO-2022-0521" ], "CVE-2022-28327": [ "GO-2022-0435" ], "CVE-2022-28946": [ "GO-2022-0587" ], "CVE-2022-28948": [ "GO-2022-0603" ], "CVE-2022-29173": [ "GO-2022-0444" ], "CVE-2022-29189": [ "GO-2022-0461" ], "CVE-2022-29190": [ "GO-2022-0460" ], "CVE-2022-29222": [ "GO-2022-0462" ], "CVE-2022-29526": [ "GO-2022-0493" ], "CVE-2022-29804": [ "GO-2022-0533" ], "CVE-2022-29810": [ "GO-2022-0438" ], "CVE-2022-30321": [ "GO-2022-0586" ], "CVE-2022-30322": [ "GO-2022-0586" ], "CVE-2022-30323": [ "GO-2022-0586" ], "CVE-2022-30580": [ "GO-2022-0532" ], "CVE-2022-30629": [ "GO-2022-0531" ], "CVE-2022-30630": [ "GO-2022-0527" ], "CVE-2022-30631": [ "GO-2022-0524" ], "CVE-2022-30632": [ "GO-2022-0522" ], "CVE-2022-30633": [ "GO-2022-0523" ], "CVE-2022-30634": [ "GO-2022-0477" ], "CVE-2022-30635": [ "GO-2022-0526" ], "CVE-2022-3064": [ "GO-2022-0956" ], "CVE-2022-31022": [ "GO-2022-0470" ], "CVE-2022-31053": [ "GO-2022-0564" ], "CVE-2022-31145": [ "GO-2022-0519" ], "CVE-2022-31259": [ "GO-2022-0463" ], "CVE-2022-31836": [ "GO-2022-0569" ], "CVE-2022-32148": [ "GO-2022-0520" ], "CVE-2022-32189": [ "GO-2022-0537" ], "CVE-2022-33082": [ "GO-2022-0574" ], "CVE-2022-36009": [ "GO-2022-0952" ], "CVE-2022-37315": [ "GO-2022-0942" ], "GHSA-25xm-hr59-7c27": [ "GO-2020-0016" ], "GHSA-27rq-4943-qcwp": [ "GO-2022-0438" ], "GHSA-28r2-q6m8-9hpx": [ "GO-2022-0586" ], "GHSA-28r6-jm5h-mrgg": [ "GO-2022-0572" ], "GHSA-2c64-vj8g-vwrq": [ "GO-2022-0380" ], "GHSA-2m4x-4q9j-w97g": [ "GO-2022-0574" ], "GHSA-2v6x-frw8-7r7f": [ "GO-2022-0621" ], "GHSA-2x32-jm95-2cpx": [ "GO-2020-0050" ], "GHSA-3fx4-7f69-5mmg": [ "GO-2020-0009" ], "GHSA-3x58-xr87-2fcj": [ "GO-2022-0762" ], "GHSA-3xh2-74w9-5vxm": [ "GO-2020-0019" ], "GHSA-44r7-7p62-q3fr": [ "GO-2020-0008" ], "GHSA-477v-w82m-634j": [ "GO-2022-0528" ], "GHSA-4hq8-gmxx-h6w9": [ "GO-2021-0058" ], "GHSA-4w5x-x539-ppf5": [ "GO-2022-0380" ], "GHSA-56hp-xqp3-w2jf": [ "GO-2022-0384" ], "GHSA-5796-p3m6-9qj4": [ "GO-2021-0102" ], "GHSA-58v3-j75h-xr49": [ "GO-2020-0007" ], "GHSA-59hh-656j-3p7v": [ "GO-2022-0256" ], "GHSA-5cgx-vhfp-6cf9": [ "GO-2022-0629" ], "GHSA-5gjg-jgh4-gppm": [ "GO-2021-0107" ], "GHSA-5mxh-2qfv-4g7j": [ "GO-2022-0251" ], "GHSA-5rcv-m4m3-hfh7": [ "GO-2020-0015" ], "GHSA-5x29-3hr9-6wpw": [ "GO-2021-0095" ], "GHSA-62mh-w5cv-p88c": [ "GO-2022-0386" ], "GHSA-6635-c626-vj4r": [ "GO-2022-0414" ], "GHSA-66vw-v2x9-hw75": [ "GO-2022-0558" ], "GHSA-66x3-6cw3-v5gj": [ "GO-2022-0444" ], "GHSA-6jqj-f58p-mrw3": [ "GO-2021-0090" ], "GHSA-72wf-hwcq-65h9": [ "GO-2022-0563" ], "GHSA-733f-44f3-3frw": [ "GO-2020-0039" ], "GHSA-74xm-qj29-cq8p": [ "GO-2021-0104" ], "GHSA-75rw-34q6-72cr": [ "GO-2022-0564" ], "GHSA-7638-r9r3-rmjj": [ "GO-2022-0345" ], "GHSA-76wf-9vgp-pj7w": [ "GO-2022-0391" ], "GHSA-77gc-fj98-665h": [ "GO-2020-0011", "GO-2022-0945" ], "GHSA-7gfg-6934-mqq2": [ "GO-2020-0038" ], "GHSA-7jr6-prv4-5wf5": [ "GO-2022-0384" ], "GHSA-7mqr-2v3q-v2wm": [ "GO-2021-0109" ], "GHSA-7qw8-847f-pggm": [ "GO-2021-0100" ], "GHSA-85p9-j7c9-v4gr": [ "GO-2021-0081" ], "GHSA-86r9-39j9-99wp": [ "GO-2020-0010" ], "GHSA-88jf-7rch-32qc": [ "GO-2020-0041" ], "GHSA-8c26-wmh5-6g9v": [ "GO-2021-0356" ], "GHSA-8v99-48m9-c8pm": [ "GO-2021-0412" ], "GHSA-8vrw-m3j9-j27c": [ "GO-2021-0057" ], "GHSA-9423-6c93-gpp8": [ "GO-2020-0042" ], "GHSA-95f9-94vc-665h": [ "GO-2022-0569" ], "GHSA-9856-9gg9-qcmq": [ "GO-2022-0254" ], "GHSA-99cg-575x-774p": [ "GO-2022-0294" ], "GHSA-9cx9-x2gp-9qvh": [ "GO-2021-0091", "GO-2021-0108" ], "GHSA-9jcx-pr2f-qvq5": [ "GO-2020-0028" ], "GHSA-9q3g-m353-cp4p": [ "GO-2022-0643" ], "GHSA-9r5x-fjv3-q6h4": [ "GO-2022-0386" ], "GHSA-9w9f-6mg8-jp7w": [ "GO-2022-0470" ], "GHSA-9x4h-8wgm-8xfg": [ "GO-2022-0503" ], "GHSA-c3g4-w6cv-6v7h": [ "GO-2022-0417" ], "GHSA-c3h9-896r-86jm": [ "GO-2021-0053" ], "GHSA-c8xp-8mf3-62h9": [ "GO-2022-0246" ], "GHSA-c9gm-7rfj-8w5h": [ "GO-2021-0265" ], "GHSA-cg3q-j54f-5p7p": [ "GO-2022-0322" ], "GHSA-cjjc-xp8v-855w": [ "GO-2022-0229" ], "GHSA-cjr4-fv6c-f3mv": [ "GO-2022-0586" ], "GHSA-cm8f-h6j3-p25c": [ "GO-2022-0460" ], "GHSA-cqh2-vc2f-q4fh": [ "GO-2022-0248" ], "GHSA-cx3w-xqmc-84g5": [ "GO-2021-0098" ], "GHSA-cx94-mrg9-rq4j": [ "GO-2022-0461" ], "GHSA-f5pg-7wfw-84q9": [ "GO-2022-0646" ], "GHSA-f6mq-5m25-4r72": [ "GO-2021-0111", "GO-2021-0112" ], "GHSA-f6px-w8rh-7r89": [ "GO-2021-0084" ], "GHSA-fcgg-rvwg-jv58": [ "GO-2022-0586" ], "GHSA-ffhg-7mh4-33c4": [ "GO-2020-0012" ], "GHSA-fgv8-vj5c-2ppq": [ "GO-2021-0085" ], "GHSA-fh74-hm69-rqjw": [ "GO-2021-0087" ], "GHSA-fx95-883v-4q4h": [ "GO-2022-0355" ], "GHSA-g3vv-g2j5-45f2": [ "GO-2022-0422" ], "GHSA-g5v4-5x39-vwhx": [ "GO-2021-0099" ], "GHSA-g9mp-8g3h-3c5c": [ "GO-2022-0425" ], "GHSA-g9wh-3vrx-r7hg": [ "GO-2022-0253" ], "GHSA-h289-x5wc-xcv8": [ "GO-2022-0370" ], "GHSA-h2fg-54x9-5qhq": [ "GO-2022-0402" ], "GHSA-h2x7-2ff6-v32p": [ "GO-2022-0400" ], "GHSA-h395-qcrw-5vmq": [ "GO-2020-0029", "GO-2021-0052" ], "GHSA-h3qm-jrrf-cgj3": [ "GO-2022-0942" ], "GHSA-h6xx-pmxh-3wgp": [ "GO-2021-0077" ], "GHSA-hcw3-j74m-qc58": [ "GO-2022-0316" ], "GHSA-hmm9-r2m2-qg9w": [ "GO-2022-0402" ], "GHSA-hp87-p4gw-j4gq": [ "GO-2022-0603" ], "GHSA-j6wp-3859-vxfg": [ "GO-2021-0258" ], "GHSA-j756-f273-xhp4": [ "GO-2022-0386" ], "GHSA-jcxc-rh6w-wf49": [ "GO-2022-0272" ], "GHSA-jm5c-rv3w-w83m": [ "GO-2021-0103" ], "GHSA-jp32-vmm6-3vf5": [ "GO-2022-0701" ], "GHSA-jq7p-26h5-w78r": [ "GO-2021-0101" ], "GHSA-jxqv-jcvh-7gr4": [ "GO-2022-0534" ], "GHSA-m658-p24x-p74r": [ "GO-2021-0321", "GO-2022-0370", "GO-2022-0947" ], "GHSA-m6wg-2mwg-4rfq": [ "GO-2020-0002", "GO-2020-0031", "GO-2021-0096" ], "GHSA-m9hp-7r99-94h5": [ "GO-2020-0050" ], "GHSA-mh3m-8c74-74xh": [ "GO-2022-0300" ], "GHSA-mj9r-wwm8-7q52": [ "GO-2021-0237" ], "GHSA-mq47-6wwv-v79w": [ "GO-2022-0346" ], "GHSA-mr6h-chqp-p9g2": [ "GO-2020-0021" ], "GHSA-p55x-7x9v-q8m4": [ "GO-2020-0006" ], "GHSA-ppj4-34rq-v8j9": [ "GO-2021-0265" ], "GHSA-q3j5-32m5-58c2": [ "GO-2021-0070" ], "GHSA-q547-gmf8-8jr7": [ "GO-2020-0050" ], "GHSA-q6gq-997w-f55g": [ "GO-2021-0142" ], "GHSA-qj26-7grj-whg3": [ "GO-2020-0027" ], "GHSA-qpgx-64h2-gc3c": [ "GO-2022-0492" ], "GHSA-qq97-vm5h-rrhg": [ "GO-2022-0379" ], "GHSA-qqc5-rgcc-cjqh": [ "GO-2022-0706" ], "GHSA-qwrj-9hmp-gpxh": [ "GO-2022-0519" ], "GHSA-qx32-f6g6-fcfr": [ "GO-2022-0463" ], "GHSA-r33q-22hv-j29q": [ "GO-2021-0063" ], "GHSA-r48q-9g5r-8q2h": [ "GO-2022-0619" ], "GHSA-rmh2-65xw-9m6q": [ "GO-2021-0089" ], "GHSA-v3q9-2p3m-7g43": [ "GO-2021-0092", "GO-2021-0110" ], "GHSA-v95c-p5hm-xq8f": [ "GO-2022-0274" ], "GHSA-vc3x-gx6c-g99f": [ "GO-2021-0079" ], "GHSA-vpx7-vm66-qx8r": [ "GO-2021-0228" ], "GHSA-w45j-f832-hxvh": [ "GO-2022-0462" ], "GHSA-w6ww-fmfx-2x22": [ "GO-2022-0252" ], "GHSA-w73w-5m7g-f7qc": [ "GO-2020-0017" ], "GHSA-w942-gw6m-p62c": [ "GO-2021-0059" ], "GHSA-wjm3-fq3r-5x46": [ "GO-2022-0957" ], "GHSA-wmwp-pggc-h4mj": [ "GO-2021-0086" ], "GHSA-wxc4-f4m6-wwqv": [ "GO-2020-0036" ], "GHSA-x24g-9w7v-vprh": [ "GO-2022-0586" ], "GHSA-x4rg-4545-4w7w": [ "GO-2021-0088" ], "GHSA-x7f3-62pm-9p38": [ "GO-2022-0587" ], "GHSA-x95h-979x-cf3j": [ "GO-2022-0588" ], "GHSA-xcf7-q56x-78gh": [ "GO-2022-0233" ], "GHSA-xg2h-wx96-xgxr": [ "GO-2022-0411" ], "GHSA-xhg2-rvm8-w2jh": [ "GO-2022-0755" ], "GHSA-xhqq-x44f-9fgg": [ "GO-2021-0060" ], "GHSA-xjqr-g762-pxwp": [ "GO-2022-0230" ], "GHSA-xw37-57qp-9mm4": [ "GO-2021-0105" ] }
vulndb-legacy
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/index.json
{ "github.com/BeeGo/beego": "2022-08-23T19:54:38Z", "github.com/tidwall/gjson": "2022-08-23T19:54:38Z" }
!bee!go
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/github.com/!bee!go/beego.json
[ { "id": "GO-2022-0463", "published": "2022-07-01T20:06:59Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2022-31259", "GHSA-qx32-f6g6-fcfr" ], "details": "Routes in the beego HTTP router can match unintended patterns.\nThis overly-broad matching may permit an attacker to bypass access\ncontrols.\n\nFor example, the pattern \"/a/b/:name\" can match the URL \"/a.xml/b/\".\nThis may bypass access control applied to the prefix \"/a/\".\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.12.9" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0463" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "App.Run", "ControllerRegister.FindPolicy", "ControllerRegister.FindRouter", "ControllerRegister.ServeHTTP", "FilterRouter.ValidRouter", "InitBeegoBeforeTest", "Run", "RunWithMiddleWares", "TestBeegoInit", "Tree.Match", "Tree.match", "adminApp.Run" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "2.0.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0463" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "AddNamespace", "Any", "AutoPrefix", "AutoRouter", "Compare", "CompareNot", "Controller.Bind", "Controller.BindForm", "Controller.BindXML", "Controller.BindYAML", "Controller.GetSecureCookie", "Controller.ParseForm", "Controller.Render", "Controller.RenderBytes", "Controller.RenderString", "Controller.Resp", "Controller.SaveToFile", "Controller.ServeFormatted", "Controller.ServeXML", "Controller.ServeYAML", "Controller.SetSecureCookie", "Controller.Trace", "Controller.URLFor", "Controller.XMLResp", "Controller.XSRFFormHTML", "Controller.XSRFToken", "Controller.YamlResp", "ControllerRegister.Add", "ControllerRegister.AddAuto", "ControllerRegister.AddAutoPrefix", "ControllerRegister.AddMethod", "ControllerRegister.AddRouterMethod", "ControllerRegister.Any", "ControllerRegister.CtrlAny", "ControllerRegister.CtrlDelete", "ControllerRegister.CtrlGet", "ControllerRegister.CtrlHead", "ControllerRegister.CtrlOptions", "ControllerRegister.CtrlPatch", "ControllerRegister.CtrlPost", "ControllerRegister.CtrlPut", "ControllerRegister.Delete", "ControllerRegister.FindPolicy", "ControllerRegister.FindRouter", "ControllerRegister.Get", "ControllerRegister.Handler", "ControllerRegister.Head", "ControllerRegister.Include", "ControllerRegister.Init", "ControllerRegister.InsertFilter", "ControllerRegister.Options", "ControllerRegister.Patch", "ControllerRegister.Post", "ControllerRegister.Put", "ControllerRegister.ServeHTTP", "ControllerRegister.URLFor", "CtrlAny", "CtrlDelete", "CtrlGet", "CtrlHead", "CtrlOptions", "CtrlPatch", "CtrlPost", "CtrlPut", "Date", "DateParse", "Delete", "Exception", "ExecuteTemplate", "ExecuteViewPathTemplate", "FilterRouter.ValidRouter", "FlashData.Error", "FlashData.Notice", "FlashData.Set", "FlashData.Store", "FlashData.Success", "FlashData.Warning", "Get", "GetConfig", "HTML2str", "Handler", "Head", "Htmlquote", "Htmlunquote", "HttpServer.Any", "HttpServer.AutoPrefix", "HttpServer.AutoRouter", "HttpServer.CtrlAny", "HttpServer.CtrlDelete", "HttpServer.CtrlGet", "HttpServer.CtrlHead", "HttpServer.CtrlOptions", "HttpServer.CtrlPatch", "HttpServer.CtrlPost", "HttpServer.CtrlPut", "HttpServer.Delete", "HttpServer.Get", "HttpServer.Handler", "HttpServer.Head", "HttpServer.Include", "HttpServer.InsertFilter", "HttpServer.Options", "HttpServer.Patch", "HttpServer.Post", "HttpServer.PrintTree", "HttpServer.Put", "HttpServer.RESTRouter", "HttpServer.Router", "HttpServer.RouterWithOpts", "HttpServer.Run", "Include", "InitBeegoBeforeTest", "InsertFilter", "LoadAppConfig", "MapGet", "Namespace.Any", "Namespace.AutoPrefix", "Namespace.AutoRouter", "Namespace.Cond", "Namespace.CtrlAny", "Namespace.CtrlDelete", "Namespace.CtrlGet", "Namespace.CtrlHead", "Namespace.CtrlOptions", "Namespace.CtrlPatch", "Namespace.CtrlPost", "Namespace.CtrlPut", "Namespace.Delete", "Namespace.Filter", "Namespace.Get", "Namespace.Handler", "Namespace.Head", "Namespace.Include", "Namespace.Namespace", "Namespace.Options", "Namespace.Patch", "Namespace.Post", "Namespace.Put", "Namespace.Router", "NewControllerRegister", "NewControllerRegisterWithCfg", "NewHttpServerWithCfg", "NewHttpSever", "NewNamespace", "NotNil", "Options", "ParseForm", "Patch", "Policy", "Post", "PrintTree", "Put", "RESTRouter", "ReadFromRequest", "RenderForm", "Router", "RouterWithOpts", "Run", "RunWithMiddleWares", "TestBeegoInit", "Tree.AddRouter", "Tree.AddTree", "Tree.Match", "Tree.match", "URLFor", "URLMap.GetMap", "URLMap.GetMapData", "adminApp.Run", "adminController.AdminIndex", "adminController.Healthcheck", "adminController.ListConf", "adminController.ProfIndex", "adminController.PrometheusMetrics", "adminController.QpsIndex", "adminController.TaskStatus", "beegoAppConfig.Bool", "beegoAppConfig.DefaultBool" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/4958" }, { "type": "FIX", "url": "https://github.com/beego/beego/commit/64cf44d725c8cc35d782327d333df9cbeb1bf2dd" }, { "type": "WEB", "url": "https://beego.vip" }, { "type": "WEB", "url": "https://github.com/beego/beego/issues/4946" }, { "type": "WEB", "url": "https://github.com/beego/beego/pull/4954" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31259" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-qx32-f6g6-fcfr" } ] }, { "id": "GO-2022-0569", "published": "2022-08-23T13:24:17Z", "modified": "2022-08-23T13:24:17Z", "aliases": [ "CVE-2022-31836", "GHSA-95f9-94vc-665h" ], "details": "The leafInfo.match() function uses path.join()\nto deal with wildcard values which can lead to cross directory risk.\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.12.11" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0569" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "Tree.Match" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "2.0.0" }, { "fixed": "2.0.4" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0569" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "Tree.Match" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/5025" }, { "type": "FIX", "url": "https://github.com/beego/beego/pull/5025/commits/ea5ae58d40589d249cf577a053e490509de2bf57" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31836" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-95f9-94vc-665h" } ] }, { "id": "GO-2022-0572", "published": "2022-08-22T17:56:17Z", "modified": "2022-08-23T19:54:38Z", "aliases": [ "CVE-2021-30080", "GHSA-28r6-jm5h-mrgg" ], "details": "An issue was discovered in the route lookup process in\nbeego which attackers to bypass access control.\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0572" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "Tree.Match" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "2.0.0" }, { "fixed": "2.0.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0572" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "Tree.Match" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/4459" }, { "type": "FIX", "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30080" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-28r6-jm5h-mrgg" } ] } ]
tidwall
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/github.com/tidwall/gjson.json
[ {"id": "GO-2021-0054", "published": "2021-04-14T20:04:52Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2020-36067" ], "details": "Due to improper bounds checking, maliciously crafted JSON objects can cause an out-of-bounds panic. If parsing user input, this may be used as a denial of service vector.", "affected": [ { "package": { "name": "github.com/tidwall/gjson", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.6.6" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2021-0054" }, "ecosystem_specific": { "imports": [ { "path": "github.com/tidwall/gjson", "symbols": [ "Result.ForEach", "unwrap" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/tidwall/gjson/commit/bf4efcb3c18d1825b2988603dea5909140a5302b" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/issues/196" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36067" } ] }, { "id": "GO-2021-0059", "published": "2021-04-14T20:04:52Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2020-35380", "GHSA-w942-gw6m-p62c" ], "details": "Due to improper bounds checking, maliciously crafted JSON objects can cause an out-of-bounds panic. If parsing user input, this may be used as a denial of service vector.", "affected": [ { "package": { "name": "github.com/tidwall/gjson", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.6.4" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2021-0059" }, "ecosystem_specific": { "imports": [ { "path": "github.com/tidwall/gjson", "symbols": [ "sqaush" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/tidwall/gjson/commit/f0ee9ebde4b619767ae4ac03e8e42addb530f6bc" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/issues/192" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-35380" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-w942-gw6m-p62c" } ] }, { "id": "GO-2021-0265", "published": "2022-01-14T17:30:24Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2020-36066", "CVE-2021-42836", "GHSA-ppj4-34rq-v8j9", "GHSA-wjm3-fq3r-5x46" ], "details": "GJSON allowed a ReDoS (regular expression denial of service) attack.", "affected": [ { "package": { "name": "github.com/tidwall/gjson", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.9.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2021-0265" }, "ecosystem_specific": { "imports": [ { "path": "github.com/tidwall/gjson", "symbols": [ "match.Match" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/tidwall/gjson/commit/590010fdac311cc8990ef5c97448d4fec8f29944" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/compare/v1.9.2...v1.9.3" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/issues/236" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/issues/237" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36066" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42836" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-ppj4-34rq-v8j9" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-wjm3-fq3r-5x46" } ] }, { "id": "GO-2022-0592", "published": "2022-08-15T18:06:07Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2021-42248", "GHSA-c9gm-7rfj-8w5h" ], "details": "A maliciously crafted path can cause Get and other query functions to consume excessive amounts of CPU and time.", "affected": [ { "package": { "name": "github.com/tidwall/gjson", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.9.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0592" }, "ecosystem_specific": { "imports": [ { "path": "github.com/tidwall/gjson", "symbols": [ "Get", "GetBytes", "GetMany", "GetManyBytes", "Result.Get", "queryMatches" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/tidwall/gjson/commit/77a57fda87dca6d0d7d4627d512a630f89a91c96" }, { "type": "WEB", "url": "https://github.com/tidwall/gjson/issues/237" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42248" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-c9gm-7rfj-8w5h" } ] } ]
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/GO-2022-0463.json
{ "id": "GO-2022-0463", "published": "2022-07-01T20:06:59Z", "modified": "2022-08-19T22:21:47Z", "aliases": [ "CVE-2022-31259", "GHSA-qx32-f6g6-fcfr" ], "details": "Routes in the beego HTTP router can match unintended patterns.\nThis overly-broad matching may permit an attacker to bypass access\ncontrols.\n\nFor example, the pattern \"/a/b/:name\" can match the URL \"/a.xml/b/\".\nThis may bypass access control applied to the prefix \"/a/\".\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.12.9" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0463" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "App.Run", "ControllerRegister.FindPolicy", "ControllerRegister.FindRouter", "ControllerRegister.ServeHTTP", "FilterRouter.ValidRouter", "InitBeegoBeforeTest", "Run", "RunWithMiddleWares", "TestBeegoInit", "Tree.Match", "Tree.match", "adminApp.Run" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "2.0.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0463" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "AddNamespace", "Any", "AutoPrefix", "AutoRouter", "Compare", "CompareNot", "Controller.Bind", "Controller.BindForm", "Controller.BindXML", "Controller.BindYAML", "Controller.GetSecureCookie", "Controller.ParseForm", "Controller.Render", "Controller.RenderBytes", "Controller.RenderString", "Controller.Resp", "Controller.SaveToFile", "Controller.ServeFormatted", "Controller.ServeXML", "Controller.ServeYAML", "Controller.SetSecureCookie", "Controller.Trace", "Controller.URLFor", "Controller.XMLResp", "Controller.XSRFFormHTML", "Controller.XSRFToken", "Controller.YamlResp", "ControllerRegister.Add", "ControllerRegister.AddAuto", "ControllerRegister.AddAutoPrefix", "ControllerRegister.AddMethod", "ControllerRegister.AddRouterMethod", "ControllerRegister.Any", "ControllerRegister.CtrlAny", "ControllerRegister.CtrlDelete", "ControllerRegister.CtrlGet", "ControllerRegister.CtrlHead", "ControllerRegister.CtrlOptions", "ControllerRegister.CtrlPatch", "ControllerRegister.CtrlPost", "ControllerRegister.CtrlPut", "ControllerRegister.Delete", "ControllerRegister.FindPolicy", "ControllerRegister.FindRouter", "ControllerRegister.Get", "ControllerRegister.Handler", "ControllerRegister.Head", "ControllerRegister.Include", "ControllerRegister.Init", "ControllerRegister.InsertFilter", "ControllerRegister.Options", "ControllerRegister.Patch", "ControllerRegister.Post", "ControllerRegister.Put", "ControllerRegister.ServeHTTP", "ControllerRegister.URLFor", "CtrlAny", "CtrlDelete", "CtrlGet", "CtrlHead", "CtrlOptions", "CtrlPatch", "CtrlPost", "CtrlPut", "Date", "DateParse", "Delete", "Exception", "ExecuteTemplate", "ExecuteViewPathTemplate", "FilterRouter.ValidRouter", "FlashData.Error", "FlashData.Notice", "FlashData.Set", "FlashData.Store", "FlashData.Success", "FlashData.Warning", "Get", "GetConfig", "HTML2str", "Handler", "Head", "Htmlquote", "Htmlunquote", "HttpServer.Any", "HttpServer.AutoPrefix", "HttpServer.AutoRouter", "HttpServer.CtrlAny", "HttpServer.CtrlDelete", "HttpServer.CtrlGet", "HttpServer.CtrlHead", "HttpServer.CtrlOptions", "HttpServer.CtrlPatch", "HttpServer.CtrlPost", "HttpServer.CtrlPut", "HttpServer.Delete", "HttpServer.Get", "HttpServer.Handler", "HttpServer.Head", "HttpServer.Include", "HttpServer.InsertFilter", "HttpServer.Options", "HttpServer.Patch", "HttpServer.Post", "HttpServer.PrintTree", "HttpServer.Put", "HttpServer.RESTRouter", "HttpServer.Router", "HttpServer.RouterWithOpts", "HttpServer.Run", "Include", "InitBeegoBeforeTest", "InsertFilter", "LoadAppConfig", "MapGet", "Namespace.Any", "Namespace.AutoPrefix", "Namespace.AutoRouter", "Namespace.Cond", "Namespace.CtrlAny", "Namespace.CtrlDelete", "Namespace.CtrlGet", "Namespace.CtrlHead", "Namespace.CtrlOptions", "Namespace.CtrlPatch", "Namespace.CtrlPost", "Namespace.CtrlPut", "Namespace.Delete", "Namespace.Filter", "Namespace.Get", "Namespace.Handler", "Namespace.Head", "Namespace.Include", "Namespace.Namespace", "Namespace.Options", "Namespace.Patch", "Namespace.Post", "Namespace.Put", "Namespace.Router", "NewControllerRegister", "NewControllerRegisterWithCfg", "NewHttpServerWithCfg", "NewHttpSever", "NewNamespace", "NotNil", "Options", "ParseForm", "Patch", "Policy", "Post", "PrintTree", "Put", "RESTRouter", "ReadFromRequest", "RenderForm", "Router", "RouterWithOpts", "Run", "RunWithMiddleWares", "TestBeegoInit", "Tree.AddRouter", "Tree.AddTree", "Tree.Match", "Tree.match", "URLFor", "URLMap.GetMap", "URLMap.GetMapData", "adminApp.Run", "adminController.AdminIndex", "adminController.Healthcheck", "adminController.ListConf", "adminController.ProfIndex", "adminController.PrometheusMetrics", "adminController.QpsIndex", "adminController.TaskStatus", "beegoAppConfig.Bool", "beegoAppConfig.DefaultBool" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/4958" }, { "type": "FIX", "url": "https://github.com/beego/beego/commit/64cf44d725c8cc35d782327d333df9cbeb1bf2dd" }, { "type": "WEB", "url": "https://beego.vip" }, { "type": "WEB", "url": "https://github.com/beego/beego/issues/4946" }, { "type": "WEB", "url": "https://github.com/beego/beego/pull/4954" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31259" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-qx32-f6g6-fcfr" } ] }
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/GO-2021-0157.json
{"id":"GO-2021-0157","published":"2022-01-05T20:00:00Z","modified":"2022-08-29T16:50:59Z","aliases":["CVE-2015-5739"],"details":"The MIME header parser treated spaces and hyphens\nas equivalent, which can permit HTTP request smuggling.\n","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.4.3"}]}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0157"},"ecosystem_specific":{"imports":[{"path":"net/textproto","symbols":["CanonicalMIMEHeaderKey","canonicalMIMEHeaderKey"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/11772"},{"type":"FIX","url":"https://go.googlesource.com/go/+/117ddcb83d7f42d6aa72241240af99ded81118e9"},{"type":"REPORT","url":"https://go.dev/issue/53035"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/iSIyW4lM4hY/m/ADuQR4DiDwAJ"}]}
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/GO-2022-0572.json
{ "id": "GO-2022-0572", "published": "2022-08-22T17:56:17Z", "modified": "2022-08-23T19:54:38Z", "aliases": [ "CVE-2021-30080", "GHSA-28r6-jm5h-mrgg" ], "details": "An issue was discovered in the route lookup process in\nbeego which attackers to bypass access control.\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0572" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "Tree.Match" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "2.0.0" }, { "fixed": "2.0.3" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0572" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "Tree.Match" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/4459" }, { "type": "FIX", "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-30080" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-28r6-jm5h-mrgg" } ] }
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/GO-2022-0569.json
{ "id": "GO-2022-0569", "published": "2022-08-23T13:24:17Z", "modified": "2022-08-23T13:24:17Z", "aliases": [ "CVE-2022-31836", "GHSA-95f9-94vc-665h" ], "details": "The leafInfo.match() function uses path.join()\nto deal with wildcard values which can lead to cross directory risk.\n", "affected": [ { "package": { "name": "github.com/beego/beego", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.12.11" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0569" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego", "symbols": [ "Tree.Match" ] } ] } }, { "package": { "name": "github.com/beego/beego/v2", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "2.0.0" }, { "fixed": "2.0.4" } ] } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2022-0569" }, "ecosystem_specific": { "imports": [ { "path": "github.com/beego/beego/v2/server/web", "symbols": [ "Tree.Match" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/beego/beego/pull/5025" }, { "type": "FIX", "url": "https://github.com/beego/beego/pull/5025/commits/ea5ae58d40589d249cf577a053e490509de2bf57" }, { "type": "WEB", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31836" }, { "type": "WEB", "url": "https://github.com/advisories/GHSA-95f9-94vc-665h" } ] }
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/index.json
[ "GO-2022-0463", "GO-2022-0569", "GO-2022-0572" ]
ID
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/client/testdata/vulndb-legacy/ID/GO-2021-0159.json
{"id":"GO-2021-0159","published":"2022-01-05T21:39:14Z","modified":"2022-08-29T16:50:59Z","aliases":["CVE-2015-5739","CVE-2015-5740","CVE-2015-5741"],"details":"HTTP headers were not properly parsed, which allows remote attackers to\nconduct HTTP request smuggling attacks via a request that contains\nContent-Length and Transfer-Encoding header fields.\n","affected":[{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.4.3"}]}],"database_specific":{"url":"https://pkg.go.dev/vuln/GO-2021-0159"},"ecosystem_specific":{"imports":[{"path":"net/http","symbols":["CanonicalMIMEHeaderKey","body.readLocked","canonicalMIMEHeaderKey","chunkWriter.writeHeader","fixLength","fixTransferEncoding","readTransfer","transferWriter.shouldSendContentLength","validHeaderFieldByte"]}]}}],"references":[{"type":"FIX","url":"https://go.dev/cl/13148"},{"type":"FIX","url":"https://go.googlesource.com/go/+/26049f6f9171d1190f3bbe05ec304845cfe6399f"},{"type":"FIX","url":"https://go.dev/cl/11772"},{"type":"FIX","url":"https://go.dev/cl/11810"},{"type":"FIX","url":"https://go.dev/cl/12865"},{"type":"FIX","url":"https://go.googlesource.com/go/+/117ddcb83d7f42d6aa72241240af99ded81118e9"},{"type":"FIX","url":"https://go.googlesource.com/go/+/300d9a21583e7cf0149a778a0611e76ff7c6680f"},{"type":"FIX","url":"https://go.googlesource.com/go/+/c2db5f4ccc61ba7df96a747e268a277b802cbb87"},{"type":"REPORT","url":"https://go.dev/issue/12027"},{"type":"REPORT","url":"https://go.dev/issue/11930"},{"type":"WEB","url":"https://groups.google.com/g/golang-announce/c/iSIyW4lM4hY/m/ADuQR4DiDwAJ"}]}
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/fixed_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package semver import ( "testing" "golang.org/x/vuln/internal/osv" ) func TestNonSupersededFix(t *testing.T) { tests := []struct { name string ranges []osv.Range want string }{ { name: "empty", ranges: []osv.Range{}, want: "", }, { name: "no fix", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ { Introduced: "0", }, }, }}, want: "", }, { name: "no latest fix", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ {Introduced: "0"}, {Fixed: "1.0.4"}, {Introduced: "1.1.2"}, }, }}, want: "", }, { name: "unsorted no latest fix", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ {Fixed: "1.0.4"}, {Introduced: "0"}, {Introduced: "1.1.2"}, {Introduced: "1.5.0"}, {Fixed: "1.1.4"}, }, }}, want: "", }, { name: "unsorted with fix", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ { Fixed: "1.0.0", }, { Introduced: "0", }, { Fixed: "0.1.0", }, { Introduced: "0.5.0", }, }, }}, want: "1.0.0", }, { name: "multiple ranges", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ { Introduced: "0", }, { Fixed: "0.1.0", }, }, }, { Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ { Introduced: "0", }, { Fixed: "0.2.0", }, }, }}, want: "0.2.0", }, { name: "pseudoversion", ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{ { Introduced: "0", }, { Fixed: "0.0.0-20220824120805-abc", }, { Introduced: "0.0.0-20230824120805-efg", }, { Fixed: "0.0.0-20240824120805-hij", }, }, }}, want: "0.0.0-20240824120805-hij", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := NonSupersededFix(test.ranges) if got != test.want { t.Errorf("want %q; got %q", test.want, got) } }) } }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/semver_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package semver import ( "testing" ) func TestCanonicalize(t *testing.T) { for _, test := range []struct { v string want string }{ {"v1.2.3", "v1.2.3"}, {"1.2.3", "v1.2.3"}, {"go1.2.3", "v1.2.3"}, } { got := canonicalizeSemverPrefix(test.v) if got != test.want { t.Errorf("want %s; got %s", test.want, got) } } } func TestGoTagToSemver(t *testing.T) { for _, test := range []struct { v string want string }{ {"go1.19", "v1.19.0"}, {"go1.20-pre4", "v1.20.0-pre.4"}, } { got := GoTagToSemver(test.v) if got != test.want { t.Errorf("want %s; got %s", test.want, got) } } } func TestLess(t *testing.T) { for _, test := range []struct { v1 string v2 string want bool }{ {"go1.19", "go1.19", false}, {"go1.19.1", "go1.19", false}, {"v0.2.1", "v0.3.0", true}, {"go1.12.2", "go1.18", true}, {"v1.20.0-pre4", "v1.20.0-pre.4", false}, {"v1.20.0-pre4", "v1.20.0-pre4.4", true}, } { if got := Less(test.v1, test.v2); got != test.want { t.Errorf("want Less(%s, %s)=%t; got %t", test.v1, test.v2, test.want, got) } } }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/affects_test.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package semver import ( "testing" "golang.org/x/vuln/internal/osv" ) func TestAffectsSemver(t *testing.T) { cases := []struct { affects []osv.Range version string want bool }{ { // empty []Range indicates everything is affected affects: []osv.Range{}, version: "v0.0.0", want: true, }, { // []Range containing an empty SEMVER range also indicates // everything is affected affects: []osv.Range{{Type: osv.RangeTypeSemver}}, version: "v0.0.0", want: true, }, { // []Range containing a SEMVER range with only an "introduced":"0" // also indicates everything is affected affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}}}}, version: "v0.0.0", want: true, }, { // v1.0.0 < v2.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Fixed: "2.0.0"}}}}, version: "v1.0.0", want: true, }, { // v0.0.1 <= v1.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0.0.1"}}}}, version: "v1.0.0", want: true, }, { // v1.0.0 <= v1.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "1.0.0"}}}}, version: "v1.0.0", want: true, }, { // v1.0.0 <= v1.0.0 < v2.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "1.0.0"}, {Fixed: "2.0.0"}}}}, version: "v1.0.0", want: true, }, { // v0.0.1 <= v1.0.0 < v2.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0.0.1"}, {Fixed: "2.0.0"}}}}, version: "v1.0.0", want: true, }, { // v2.0.0 < v3.0.0 affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "1.0.0"}, {Fixed: "2.0.0"}}}}, version: "v3.0.0", want: false, }, { // Multiple ranges affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "1.0.0"}, {Fixed: "2.0.0"}, {Introduced: "3.0.0"}}}}, version: "v3.0.0", want: true, }, { affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Fixed: "1.18.6"}, {Introduced: "1.19.0"}, {Fixed: "1.19.1"}}}}, version: "v1.18.6", want: false, }, { affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Introduced: "1.19.0"}, {Fixed: "1.19.1"}}}}, version: "v1.18.6", want: true, }, { // Multiple non-sorted ranges. affects: []osv.Range{{Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "1.19.0"}, {Fixed: "1.19.1"}, {Introduced: "0"}, {Fixed: "1.18.6"}}}}, version: "v1.18.1", want: true, }, { // Wrong type range affects: []osv.Range{{Type: osv.RangeType("unspecified"), Events: []osv.RangeEvent{{Introduced: "3.0.0"}}}}, version: "v3.0.0", want: true, }, { // Semver ranges don't match affects: []osv.Range{ {Type: osv.RangeType("unspecified"), Events: []osv.RangeEvent{{Introduced: "3.0.0"}}}, {Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "4.0.0"}}}, }, version: "v3.0.0", want: false, }, { // Semver ranges do match affects: []osv.Range{ {Type: osv.RangeType("unspecified"), Events: []osv.RangeEvent{{Introduced: "3.0.0"}}}, {Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "3.0.0"}}}, }, version: "v3.0.0", want: true, }, { // Semver ranges match (go prefix) affects: []osv.Range{ {Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "3.0.0"}}}, }, version: "go3.0.1", want: true, }, } for _, c := range cases { got := Affects(c.affects, c.version) if c.want != got { t.Errorf("%#v.AffectsSemver(%s): want %t, got %t", c.affects, c.version, c.want, got) } } }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/fixed.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package semver import "golang.org/x/vuln/internal/osv" // NonSupersededFix returns a fixed version from ranges // that is not superseded by any other fix or any other // introduction of a vulnerability. Returns "" in case // there is no such fixed version. func NonSupersededFix(ranges []osv.Range) string { var latestFixed string for _, r := range ranges { if r.Type == "SEMVER" { for _, e := range r.Events { fixed := e.Fixed if fixed != "" && Less(latestFixed, fixed) { latestFixed = fixed } } // If the vulnerability was re-introduced after the latest fix // we found, there is no latest fix for this range. for _, e := range r.Events { introduced := e.Introduced if introduced != "" && introduced != "0" && Less(latestFixed, introduced) { latestFixed = "" break } } } } return latestFixed }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/affects.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package semver import ( "sort" "golang.org/x/vuln/internal/osv" ) func Affects(a []osv.Range, v string) bool { if len(a) == 0 { // No ranges implies all versions are affected return true } var semverRangePresent bool for _, r := range a { if r.Type != osv.RangeTypeSemver { continue } semverRangePresent = true if ContainsSemver(r, v) { return true } } // If there were no semver ranges present we // assume that all semvers are affected, similarly // to how to we assume all semvers are affected // if there are no ranges at all. return !semverRangePresent } // ContainsSemver checks if semver version v is in the // range encoded by ar. If ar is not a semver range, // returns false. A range is interpreted as a left-closed // and right-open interval. // // Assumes that // - exactly one of Introduced or Fixed fields is set // - ranges in ar are not overlapping // - beginning of time is encoded with .Introduced="0" // - no-fix is not an event, as opposed to being an // event where Introduced="" and Fixed="" func ContainsSemver(ar osv.Range, v string) bool { if ar.Type != osv.RangeTypeSemver { return false } if len(ar.Events) == 0 { return true } // Strip and then add the semver prefix so we can support bare versions, // versions prefixed with 'v', and versions prefixed with 'go'. v = canonicalizeSemverPrefix(v) // Sort events by semver versions. Event for beginning // of time, if present, always comes first. sort.SliceStable(ar.Events, func(i, j int) bool { e1 := ar.Events[i] v1 := e1.Introduced if v1 == "0" { // -inf case. return true } if e1.Fixed != "" { v1 = e1.Fixed } e2 := ar.Events[j] v2 := e2.Introduced if v2 == "0" { // -inf case. return false } if e2.Fixed != "" { v2 = e2.Fixed } return Less(v1, v2) }) var affected bool for _, e := range ar.Events { if !affected && e.Introduced != "" { affected = e.Introduced == "0" || !Less(v, e.Introduced) } else if affected && e.Fixed != "" { affected = Less(v, e.Fixed) } } return affected }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/semver/semver.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package semver provides shared utilities for manipulating // Go semantic versions. package semver import ( "regexp" "strings" "golang.org/x/mod/semver" ) // addSemverPrefix adds a 'v' prefix to s if it isn't already prefixed // with 'v' or 'go'. This allows us to easily test go-style SEMVER // strings against normal SEMVER strings. func addSemverPrefix(s string) string { if !strings.HasPrefix(s, "v") && !strings.HasPrefix(s, "go") { return "v" + s } return s } // removeSemverPrefix removes the 'v' or 'go' prefixes from go-style // SEMVER strings, for usage in the public vulnerability format. func removeSemverPrefix(s string) string { s = strings.TrimPrefix(s, "v") s = strings.TrimPrefix(s, "go") return s } // canonicalizeSemverPrefix turns a SEMVER string into the canonical // representation using the 'v' prefix, as used by the OSV format. // Input may be a bare SEMVER ("1.2.3"), Go prefixed SEMVER ("go1.2.3"), // or already canonical SEMVER ("v1.2.3"). func canonicalizeSemverPrefix(s string) string { return addSemverPrefix(removeSemverPrefix(s)) } // Less returns whether v1 < v2, where v1 and v2 are // semver versions with either a "v", "go" or no prefix. func Less(v1, v2 string) bool { return semver.Compare(canonicalizeSemverPrefix(v1), canonicalizeSemverPrefix(v2)) < 0 } // Valid returns whether v is valid semver, allowing // either a "v", "go" or no prefix. func Valid(v string) bool { return semver.IsValid(canonicalizeSemverPrefix(v)) } var ( // Regexp for matching go tags. The groups are: // 1 the major.minor version // 2 the patch version, or empty if none // 3 the entire prerelease, if present // 4 the prerelease type ("beta" or "rc") // 5 the prerelease number tagRegexp = regexp.MustCompile(`^go(\d+\.\d+)(\.\d+|)((beta|rc|-pre)(\d+))?$`) ) // This is a modified copy of pkgsite/internal/stdlib:VersionForTag. func GoTagToSemver(tag string) string { if tag == "" { return "" } tag = strings.Fields(tag)[0] // Special cases for go1. if tag == "go1" { return "v1.0.0" } if tag == "go1.0" { return "" } m := tagRegexp.FindStringSubmatch(tag) if m == nil { return "" } version := "v" + m[1] if m[2] != "" { version += m[2] } else { version += ".0" } if m[3] != "" { if !strings.HasPrefix(m[4], "-") { version += "-" } version += m[4] + "." + m[5] } return version }
testenv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/testenv/testenv.go
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package testenv import ( "errors" "flag" "fmt" "os" "os/exec" "path/filepath" "runtime" "sync" "testing" ) var origEnv = os.Environ() // NeedsExec checks that the current system can start new processes // using os.StartProcess or (more commonly) exec.Command. // If not, NeedsExec calls t.Skip with an explanation. // // On some platforms NeedsExec checks for exec support by re-executing the // current executable, which must be a binary built by 'go test'. // We intentionally do not provide a HasExec function because of the risk of // inappropriate recursion in TestMain functions. func NeedsExec(t testing.TB) { tryExecOnce.Do(func() { tryExecErr = tryExec() }) if tryExecErr != nil { t.Helper() t.Skipf("skipping test: cannot exec subprocess on %s/%s: %v", runtime.GOOS, runtime.GOARCH, tryExecErr) } } var ( tryExecOnce sync.Once tryExecErr error ) func tryExec() error { switch runtime.GOOS { case "aix", "android", "darwin", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "plan9", "solaris", "windows": // Known OS that isn't ios or wasm; assume that exec works. return nil default: } // ios has an exec syscall but on real iOS devices it might return a // permission error. In an emulated environment (such as a Corellium host) // it might succeed, so if we need to exec we'll just have to try it and // find out. // // As of 2023-04-19 wasip1 and js don't have exec syscalls at all, but we // may as well use the same path so that this branch can be tested without // an ios environment. if flag.Lookup("test.list") == nil { // This isn't a standard 'go test' binary, so we don't know how to // self-exec in a way that should succeed without side effects. // Just forget it. return errors.New("can't probe for exec support with a non-test executable") } // We know that this is a test executable. We should be able to run it with a // no-op flag to check for overall exec support. exe, err := os.Executable() if err != nil { return fmt.Errorf("can't probe for exec support: %w", err) } cmd := exec.Command(exe, "-test.list=^$") cmd.Env = origEnv return cmd.Run() } func NeedsGoBuild(t testing.TB) { goBuildOnce.Do(func() { dir, err := os.MkdirTemp("", "testenv-*") if err != nil { goBuildErr = err return } defer os.RemoveAll(dir) mainGo := filepath.Join(dir, "main.go") if err := os.WriteFile(mainGo, []byte("package main\nfunc main() {}\n"), 0644); err != nil { t.Fatal(err) } cmd := exec.Command("go", "build", "-o", os.DevNull, mainGo) cmd.Dir = dir if err := cmd.Run(); err != nil { goBuildErr = fmt.Errorf("%v: %v", cmd, err) } }) if goBuildErr != nil { t.Helper() t.Skipf("skipping test: 'go build' not supported on %s/%s", runtime.GOOS, runtime.GOARCH) } } var ( goBuildOnce sync.Once goBuildErr error ) // NeedsLocalhostNet skips t if networking does not work for ports opened // with "localhost". func NeedsLocalhostNet(t testing.TB) { switch runtime.GOOS { case "js", "wasip1": t.Skipf(`Listening on "localhost" fails on %s; see https://go.dev/issue/59718`, runtime.GOOS) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/binary.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "context" "encoding/json" "errors" "os" "runtime/debug" "golang.org/x/tools/go/packages" "golang.org/x/vuln/internal/buildinfo" "golang.org/x/vuln/internal/client" "golang.org/x/vuln/internal/derrors" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/vulncheck" ) // runBinary detects presence of vulnerable symbols in an executable or its minimal blob representation. func runBinary(ctx context.Context, handler govulncheck.Handler, cfg *config, client *client.Client) (err error) { defer derrors.Wrap(&err, "govulncheck") bin, err := createBin(cfg.patterns[0]) if err != nil { return err } p := &govulncheck.Progress{Message: binaryProgressMessage} if err := handler.Progress(p); err != nil { return err } return vulncheck.Binary(ctx, handler, bin, &cfg.Config, client) } func createBin(path string) (*vulncheck.Bin, error) { // First check if the path points to a Go binary. Otherwise, blob // parsing might json decode a Go binary which takes time. // // TODO(#64716): use fingerprinting to make this precise, clean, and fast. mods, packageSymbols, bi, err := buildinfo.ExtractPackagesAndSymbols(path) if err == nil { var main *packages.Module if bi.Main.Path != "" { main = &packages.Module{ Path: bi.Main.Path, Version: bi.Main.Version, } } return &vulncheck.Bin{ Path: bi.Path, Main: main, Modules: mods, PkgSymbols: packageSymbols, GoVersion: bi.GoVersion, GOOS: findSetting("GOOS", bi), GOARCH: findSetting("GOARCH", bi), }, nil } // Otherwise, see if the path points to a valid blob. bin := parseBlob(path) if bin != nil { return bin, nil } return nil, errors.New("unrecognized binary format") } // parseBlob extracts vulncheck.Bin from a valid blob at path. // If it cannot recognize a valid blob, returns nil. func parseBlob(path string) *vulncheck.Bin { from, err := os.Open(path) if err != nil { return nil } defer from.Close() dec := json.NewDecoder(from) var h header if err := dec.Decode(&h); err != nil { return nil // no header } else if h.Name != extractModeID || h.Version != extractModeVersion { return nil // invalid header } var b vulncheck.Bin if err := dec.Decode(&b); err != nil { return nil // no body } if dec.More() { return nil // we want just header and body, nothing else } return &b } // findSetting returns value of setting from bi if present. // Otherwise, returns "". func findSetting(setting string, bi *debug.BuildInfo) string { for _, s := range bi.Settings { if s.Key == setting { return s.Value } } return "" }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/source.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "context" "fmt" "golang.org/x/tools/go/packages" "golang.org/x/vuln/internal/client" "golang.org/x/vuln/internal/derrors" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/vulncheck" ) // runSource reports vulnerabilities that affect the analyzed packages. // // Vulnerabilities can be called (affecting the package, because a vulnerable // symbol is actually exercised) or just imported by the package // (likely having a non-affecting outcome). func runSource(ctx context.Context, handler govulncheck.Handler, cfg *config, client *client.Client, dir string) (err error) { defer derrors.Wrap(&err, "govulncheck") if cfg.ScanLevel.WantPackages() && len(cfg.patterns) == 0 { return nil // don't throw an error here } if !gomodExists(dir) { return errNoGoMod } graph := vulncheck.NewPackageGraph(cfg.GoVersion) pkgConfig := &packages.Config{ Dir: dir, Tests: cfg.test, Env: cfg.env, } if err := graph.LoadPackagesAndMods(pkgConfig, cfg.tags, cfg.patterns, cfg.ScanLevel == govulncheck.ScanLevelSymbol); err != nil { if isGoVersionMismatchError(err) { return fmt.Errorf("%v\n\n%v", errGoVersionMismatch, err) } return fmt.Errorf("loading packages: %w", err) } if err := handler.Progress(sourceProgressMessage(graph, cfg.ScanLevel)); err != nil { return err } if cfg.ScanLevel.WantPackages() && len(graph.TopPkgs()) == 0 { return nil // early exit } return vulncheck.Source(ctx, handler, &cfg.Config, client, graph) } // sourceProgressMessage returns a string of the form // // "Scanning your code and P packages across M dependent modules for known vulnerabilities..." // // P is the number of strictly dependent packages of // graph.TopPkgs() and Y is the number of their modules. // If P is 0, then the following message is returned // // "No packages matching the provided pattern." func sourceProgressMessage(graph *vulncheck.PackageGraph, mode govulncheck.ScanLevel) *govulncheck.Progress { var pkgsPhrase, modsPhrase string mods := uniqueAnalyzableMods(graph) if mode.WantPackages() { if len(graph.TopPkgs()) == 0 { // The package pattern is valid, but no packages are matching. // Example is pkg/strace/... (see #59623). return &govulncheck.Progress{Message: "No packages matching the provided pattern."} } pkgs := len(graph.DepPkgs()) pkgsPhrase = fmt.Sprintf(" and %d package%s", pkgs, choose(pkgs != 1, "s", "")) } modsPhrase = fmt.Sprintf(" %d dependent module%s", mods, choose(mods != 1, "s", "")) msg := fmt.Sprintf("Scanning your code%s across%s for known vulnerabilities...", pkgsPhrase, modsPhrase) return &govulncheck.Progress{Message: msg} } // uniqueAnalyzableMods returns the number of unique modules // that are analyzable. Those are basically all modules except // those that are replaced. The latter won't be analyzed as // their code is never reachable. func uniqueAnalyzableMods(graph *vulncheck.PackageGraph) int { replaced := 0 mods := graph.Modules() for _, m := range mods { if m.Replace == nil { continue } if m.Path == m.Replace.Path { // If the replacing path is the same as // the one being replaced, then only one // of these modules is in mods. continue } replaced++ } return len(mods) - replaced - 1 // don't include stdlib }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/text.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "fmt" "io" "sort" "strings" "golang.org/x/vuln/internal" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/osv" "golang.org/x/vuln/internal/vulncheck" ) type style int const ( defaultStyle = style(iota) osvCalledStyle osvImportedStyle detailsStyle sectionStyle keyStyle valueStyle ) // NewtextHandler returns a handler that writes govulncheck output as text. func NewTextHandler(w io.Writer) *TextHandler { return &TextHandler{w: w} } type TextHandler struct { w io.Writer osvs []*osv.Entry findings []*findingSummary scanLevel govulncheck.ScanLevel scanMode govulncheck.ScanMode err error showColor bool showTraces bool showVersion bool showVerbose bool } const ( detailsMessage = `For details, see https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck.` binaryProgressMessage = `Scanning your binary for known vulnerabilities...` noVulnsMessage = `No vulnerabilities found.` noOtherVulnsMessage = `No other vulnerabilities found.` verboseMessage = `'-show verbose' for more details` symbolMessage = `'-scan symbol' for more fine grained vulnerability detection` ) func (h *TextHandler) Flush() error { if len(h.findings) == 0 { h.print(noVulnsMessage + "\n") } else { fixupFindings(h.osvs, h.findings) counters := h.allVulns(h.findings) h.summary(counters) } if h.err != nil { return h.err } // We found vulnerabilities when the findings' level matches the scan level. if (isCalled(h.findings) && h.scanLevel == govulncheck.ScanLevelSymbol) || (isImported(h.findings) && h.scanLevel == govulncheck.ScanLevelPackage) || (isRequired(h.findings) && h.scanLevel == govulncheck.ScanLevelModule) { return errVulnerabilitiesFound } return nil } // Config writes version information only if --version was set. func (h *TextHandler) Config(config *govulncheck.Config) error { h.scanLevel = config.ScanLevel h.scanMode = config.ScanMode if !h.showVersion { return nil } if config.GoVersion != "" { h.style(keyStyle, "Go: ") h.print(config.GoVersion, "\n") } if config.ScannerName != "" { h.style(keyStyle, "Scanner: ") h.print(config.ScannerName) if config.ScannerVersion != "" { h.print(`@`, config.ScannerVersion) } h.print("\n") } if config.DB != "" { h.style(keyStyle, "DB: ") h.print(config.DB, "\n") if config.DBLastModified != nil { h.style(keyStyle, "DB updated: ") h.print(*config.DBLastModified, "\n") } } h.print("\n") return h.err } // Progress writes progress updates during govulncheck execution. func (h *TextHandler) Progress(progress *govulncheck.Progress) error { if h.showVerbose { h.print(progress.Message, "\n\n") } return h.err } // OSV gathers osv entries to be written. func (h *TextHandler) OSV(entry *osv.Entry) error { h.osvs = append(h.osvs, entry) return nil } // Finding gathers vulnerability findings to be written. func (h *TextHandler) Finding(finding *govulncheck.Finding) error { if err := validateFindings(finding); err != nil { return err } h.findings = append(h.findings, newFindingSummary(finding)) return nil } func (h *TextHandler) allVulns(findings []*findingSummary) summaryCounters { byVuln := groupByVuln(findings) var called, imported, required [][]*findingSummary mods := map[string]struct{}{} stdlibCalled := false for _, findings := range byVuln { switch { case isCalled(findings): called = append(called, findings) if isStdFindings(findings) { stdlibCalled = true } else { mods[findings[0].Trace[0].Module] = struct{}{} } case isImported(findings): imported = append(imported, findings) default: required = append(required, findings) } } if h.scanLevel.WantSymbols() { h.style(sectionStyle, "=== Symbol Results ===\n\n") if len(called) == 0 { h.print(noVulnsMessage, "\n\n") } for index, findings := range called { h.vulnerability(index, findings) } } if h.scanLevel == govulncheck.ScanLevelPackage || (h.scanLevel.WantPackages() && h.showVerbose) { h.style(sectionStyle, "=== Package Results ===\n\n") if len(imported) == 0 { h.print(choose(!h.scanLevel.WantSymbols(), noVulnsMessage, noOtherVulnsMessage), "\n\n") } for index, findings := range imported { h.vulnerability(index, findings) } } if h.showVerbose || h.scanLevel == govulncheck.ScanLevelModule { h.style(sectionStyle, "=== Module Results ===\n\n") if len(required) == 0 { h.print(choose(!h.scanLevel.WantPackages(), noVulnsMessage, noOtherVulnsMessage), "\n\n") } for index, findings := range required { h.vulnerability(index, findings) } } return summaryCounters{ VulnerabilitiesCalled: len(called), VulnerabilitiesImported: len(imported), VulnerabilitiesRequired: len(required), ModulesCalled: len(mods), StdlibCalled: stdlibCalled, } } func (h *TextHandler) vulnerability(index int, findings []*findingSummary) { h.style(keyStyle, "Vulnerability") h.print(" #", index+1, ": ") if isCalled(findings) { h.style(osvCalledStyle, findings[0].OSV.ID) } else { h.style(osvImportedStyle, findings[0].OSV.ID) } h.print("\n") h.style(detailsStyle) description := findings[0].OSV.Summary if description == "" { description = findings[0].OSV.Details } h.wrap(" ", description, 80) h.style(defaultStyle) h.print("\n") h.style(keyStyle, " More info:") h.print(" ", findings[0].OSV.DatabaseSpecific.URL, "\n") byModule := groupByModule(findings) first := true for _, module := range byModule { // Note: there can be several findingSummaries for the same vulnerability // emitted during streaming for different scan levels. // The module is same for all finding summaries. lastFrame := module[0].Trace[0] mod := lastFrame.Module // For stdlib, try to show package path as module name where // the scan level allows it. // TODO: should this be done in byModule as well? path := lastFrame.Module if stdPkg := h.pkg(module); path == internal.GoStdModulePath && stdPkg != "" { path = stdPkg } // All findings on a module are found and fixed at the same version foundVersion := moduleVersionString(lastFrame.Module, lastFrame.Version) fixedVersion := moduleVersionString(lastFrame.Module, module[0].FixedVersion) if !first { h.print("\n") } first = false h.print(" ") if mod == internal.GoStdModulePath { h.print("Standard library") } else { h.style(keyStyle, "Module: ") h.print(mod) } h.print("\n ") h.style(keyStyle, "Found in: ") h.print(path, "@", foundVersion, "\n ") h.style(keyStyle, "Fixed in: ") if fixedVersion != "" { h.print(path, "@", fixedVersion) } else { h.print("N/A") } h.print("\n") platforms := platforms(mod, module[0].OSV) if len(platforms) > 0 { h.style(keyStyle, " Platforms: ") for ip, p := range platforms { if ip > 0 { h.print(", ") } h.print(p) } h.print("\n") } h.traces(module) } h.print("\n") } // pkg gives the package information for findings summaries // if one exists. This is only used to print package path // instead of a module for stdlib vulnerabilities at symbol // and package scan level. func (h *TextHandler) pkg(summaries []*findingSummary) string { for _, f := range summaries { if pkg := f.Trace[0].Package; pkg != "" { return pkg } } return "" } // traces prints out the most precise trace information // found in the given summaries. func (h *TextHandler) traces(traces []*findingSummary) { // Sort the traces by the vulnerable symbol. This // guarantees determinism since we are currently // showing only one trace per symbol. sort.SliceStable(traces, func(i, j int) bool { return symbol(traces[i].Trace[0], true) < symbol(traces[j].Trace[0], true) }) // compacts are finding summaries with compact traces // suitable for non-verbose textual output. Currently, // only traces produced by symbol analysis. var compacts []*findingSummary for _, t := range traces { if t.Compact != "" { compacts = append(compacts, t) } } // binLimit is a limit on the number of binary traces // to show. Traces for binaries are less interesting // as users cannot act on them and they can hence // spam users. const binLimit = 5 for i, entry := range compacts { if i == 0 { if h.scanMode == govulncheck.ScanModeBinary { h.style(keyStyle, " Vulnerable symbols found:\n") } else { h.style(keyStyle, " Example traces found:\n") } } // skip showing all symbols in binary mode unless '-show traces' is on. if h.scanMode == govulncheck.ScanModeBinary && (i+1) > binLimit && !h.showTraces { h.print(" Use '-show traces' to see the other ", len(compacts)-binLimit, " found symbols\n") break } h.print(" #", i+1, ": ") if !h.showTraces { h.print(entry.Compact, "\n") } else { h.print("for function ", symbol(entry.Trace[0], false), "\n") for i := len(entry.Trace) - 1; i >= 0; i-- { t := entry.Trace[i] h.print(" ") if t.Position != nil { h.print(posToString(t.Position), ": ") } h.print(symbol(t, false), "\n") } } } } func (h *TextHandler) summary(c summaryCounters) { // print short summary of findings identified at the desired level of scan precision var vulnCount int h.print("Your code ", choose(h.scanLevel.WantSymbols(), "is", "may be"), " affected by ") switch h.scanLevel { case govulncheck.ScanLevelSymbol: vulnCount = c.VulnerabilitiesCalled case govulncheck.ScanLevelPackage: vulnCount = c.VulnerabilitiesImported case govulncheck.ScanLevelModule: vulnCount = c.VulnerabilitiesRequired } h.style(valueStyle, vulnCount) h.print(choose(vulnCount == 1, ` vulnerability`, ` vulnerabilities`)) if h.scanLevel.WantSymbols() { h.print(choose(c.ModulesCalled > 0 || c.StdlibCalled, ` from `, ``)) if c.ModulesCalled > 0 { h.style(valueStyle, c.ModulesCalled) h.print(choose(c.ModulesCalled == 1, ` module`, ` modules`)) } if c.StdlibCalled { if c.ModulesCalled != 0 { h.print(` and `) } h.print(`the Go standard library`) } } h.print(".\n") // print summary for vulnerabilities found at other levels of scan precision if other := h.summaryOtherVulns(c); other != "" { h.wrap("", other, 80) h.print("\n") } // print suggested flags for more/better info depending on scan level and if in verbose mode if sugg := h.summarySuggestion(); sugg != "" { h.wrap("", sugg, 80) h.print("\n") } } func (h *TextHandler) summaryOtherVulns(c summaryCounters) string { var summary strings.Builder if c.VulnerabilitiesRequired+c.VulnerabilitiesImported == 0 { summary.WriteString("This scan found no other vulnerabilities in ") if h.scanLevel.WantSymbols() { summary.WriteString("packages you import or ") } summary.WriteString("modules you require.") } else { summary.WriteString(choose(h.scanLevel.WantPackages(), "This scan also found ", "")) if h.scanLevel.WantSymbols() { summary.WriteString(fmt.Sprint(c.VulnerabilitiesImported)) summary.WriteString(choose(c.VulnerabilitiesImported == 1, ` vulnerability `, ` vulnerabilities `)) summary.WriteString("in packages you import and ") } if h.scanLevel.WantPackages() { summary.WriteString(fmt.Sprint(c.VulnerabilitiesRequired)) summary.WriteString(choose(c.VulnerabilitiesRequired == 1, ` vulnerability `, ` vulnerabilities `)) summary.WriteString("in modules you require") summary.WriteString(choose(h.scanLevel.WantSymbols(), ", but your code doesn't appear to call these vulnerabilities.", ".")) } } return summary.String() } func (h *TextHandler) summarySuggestion() string { var sugg strings.Builder switch h.scanLevel { case govulncheck.ScanLevelSymbol: if !h.showVerbose { sugg.WriteString("Use " + verboseMessage + ".") } case govulncheck.ScanLevelPackage: sugg.WriteString("Use " + symbolMessage) if !h.showVerbose { sugg.WriteString(" and " + verboseMessage) } sugg.WriteString(".") case govulncheck.ScanLevelModule: sugg.WriteString("Use " + symbolMessage + ".") } return sugg.String() } func (h *TextHandler) style(style style, values ...any) { if h.showColor { switch style { default: h.print(colorReset) case osvCalledStyle: h.print(colorBold, fgRed) case osvImportedStyle: h.print(colorBold, fgGreen) case detailsStyle: h.print(colorFaint) case sectionStyle: h.print(fgBlue) case keyStyle: h.print(colorFaint, fgYellow) case valueStyle: h.print(colorBold, fgCyan) } } h.print(values...) if h.showColor && len(values) > 0 { h.print(colorReset) } } func (h *TextHandler) print(values ...any) int { total, w := 0, 0 for _, v := range values { if h.err != nil { return total } // do we need to specialize for some types, like time? w, h.err = fmt.Fprint(h.w, v) total += w } return total } // wrap wraps s to fit in maxWidth by breaking it into lines at whitespace. If a // single word is longer than maxWidth, it is retained as its own line. func (h *TextHandler) wrap(indent string, s string, maxWidth int) { w := 0 for _, f := range strings.Fields(s) { if w > 0 && w+len(f)+1 > maxWidth { // line would be too long with this word h.print("\n") w = 0 } if w == 0 { // first field on line, indent w = h.print(indent) } else { // not first word, space separate w += h.print(" ") } // now write the word w += h.print(f) } } func choose[t any](b bool, yes, no t) t { if b { return yes } return no } func isStdFindings(findings []*findingSummary) bool { for _, f := range findings { if vulncheck.IsStdPackage(f.Trace[0].Package) || f.Trace[0].Module == internal.GoStdModulePath { return true } } return false }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/filepath_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "path/filepath" "testing" ) func TestAbsRelShorter(t *testing.T) { thisFileAbs, _ := filepath.Abs("filepath_test.go") for _, test := range []struct { l string want string }{ {"filepath_test.go", "filepath_test.go"}, {thisFileAbs, "filepath_test.go"}, } { if got := AbsRelShorter(test.l); got != test.want { t.Errorf("want %s; got %s", test.want, got) } } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/run.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "context" "fmt" "io" "os/exec" "path" "path/filepath" "runtime/debug" "strings" "time" "golang.org/x/telemetry/counter" "golang.org/x/vuln/internal/client" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/openvex" "golang.org/x/vuln/internal/sarif" ) // RunGovulncheck performs main govulncheck functionality and exits the // program upon success with an appropriate exit status. Otherwise, // returns an error. func RunGovulncheck(ctx context.Context, env []string, r io.Reader, stdout io.Writer, stderr io.Writer, args []string) error { cfg := &config{env: env} if err := parseFlags(cfg, stderr, args); err != nil { return err } client, err := client.NewClient(cfg.db, nil) if err != nil { return fmt.Errorf("creating client: %w", err) } prepareConfig(ctx, cfg, client) var handler govulncheck.Handler switch cfg.format { case formatJSON: handler = govulncheck.NewJSONHandler(stdout) case formatSarif: handler = sarif.NewHandler(stdout) case formatOpenVEX: handler = openvex.NewHandler(stdout) default: th := NewTextHandler(stdout) cfg.show.Update(th) handler = th } if err := handler.Config(&cfg.Config); err != nil { return err } incTelemetryFlagCounters(cfg) switch cfg.ScanMode { case govulncheck.ScanModeSource: dir := filepath.FromSlash(cfg.dir) err = runSource(ctx, handler, cfg, client, dir) case govulncheck.ScanModeBinary: err = runBinary(ctx, handler, cfg, client) case govulncheck.ScanModeExtract: return runExtract(cfg, stdout) case govulncheck.ScanModeQuery: err = runQuery(ctx, handler, cfg, client) case govulncheck.ScanModeConvert: err = govulncheck.HandleJSON(r, handler) } if err != nil { return err } return Flush(handler) } func prepareConfig(ctx context.Context, cfg *config, client *client.Client) { cfg.ProtocolVersion = govulncheck.ProtocolVersion cfg.DB = cfg.db if cfg.ScanMode == govulncheck.ScanModeSource && cfg.GoVersion == "" { const goverPrefix = "GOVERSION=" for _, env := range cfg.env { if val := strings.TrimPrefix(env, goverPrefix); val != env { cfg.GoVersion = val } } if cfg.GoVersion == "" { if out, err := exec.Command("go", "env", "GOVERSION").Output(); err == nil { cfg.GoVersion = strings.TrimSpace(string(out)) } } } if bi, ok := debug.ReadBuildInfo(); ok { scannerVersion(cfg, bi) } if mod, err := client.LastModifiedTime(ctx); err == nil { cfg.DBLastModified = &mod } } // scannerVersion reconstructs the current version of // this binary used from the build info. func scannerVersion(cfg *config, bi *debug.BuildInfo) { if bi.Path != "" { cfg.ScannerName = path.Base(bi.Path) } if bi.Main.Version != "" && bi.Main.Version != "(devel)" { cfg.ScannerVersion = bi.Main.Version return } // TODO(https://go.dev/issue/29228): we need to manually construct the // version string when it is "(devel)" until #29228 is resolved. var revision, at string for _, s := range bi.Settings { if s.Key == "vcs.revision" { revision = s.Value } if s.Key == "vcs.time" { at = s.Value } } buf := strings.Builder{} buf.WriteString("v0.0.0") if revision != "" { buf.WriteString("-") buf.WriteString(revision[:12]) } if at != "" { // commit time is of the form 2023-01-25T19:57:54Z p, err := time.Parse(time.RFC3339, at) if err == nil { buf.WriteString("-") buf.WriteString(p.Format("20060102150405")) } } cfg.ScannerVersion = buf.String() } func incTelemetryFlagCounters(cfg *config) { counter.Inc(fmt.Sprintf("govulncheck/mode:%s", cfg.ScanMode)) counter.Inc(fmt.Sprintf("govulncheck/scan:%s", cfg.ScanLevel)) counter.Inc(fmt.Sprintf("govulncheck/format:%s", cfg.format)) if len(cfg.show) == 0 { counter.Inc("govulncheck/show:none") } for _, s := range cfg.show { counter.Inc(fmt.Sprintf("govulncheck/show:%s", s)) } } func Flush(h govulncheck.Handler) error { if th, ok := h.(interface{ Flush() error }); ok { return th.Flush() } return nil }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/run_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "runtime/debug" "testing" ) func TestGovulncheckVersion(t *testing.T) { bi := &debug.BuildInfo{ Settings: []debug.BuildSetting{ {Key: "vcs.revision", Value: "1234567890001234"}, {Key: "vcs.time", Value: "2023-01-25T19:57:54Z"}, }, } want := "v0.0.0-123456789000-20230125195754" got := &config{} scannerVersion(got, bi) if got.ScannerVersion != want { t.Errorf("got %s; want %s", got.ScannerVersion, want) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/flags.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "errors" "flag" "fmt" "io" "os" "strings" "golang.org/x/tools/go/buildutil" "golang.org/x/vuln/internal/govulncheck" ) type config struct { govulncheck.Config patterns []string db string dir string tags buildutil.TagsFlag test bool show ShowFlag format FormatFlag env []string } func parseFlags(cfg *config, stderr io.Writer, args []string) error { var version bool var json bool var scanFlag ScanFlag var modeFlag ModeFlag flags := flag.NewFlagSet("", flag.ContinueOnError) flags.SetOutput(stderr) flags.BoolVar(&json, "json", false, "output JSON (Go compatible legacy flag, see format flag)") flags.BoolVar(&cfg.test, "test", false, "analyze test files (only valid for source mode, default false)") flags.StringVar(&cfg.dir, "C", "", "change to `dir` before running govulncheck") flags.StringVar(&cfg.db, "db", "https://vuln.go.dev", "vulnerability database `url`") flags.Var(&modeFlag, "mode", "supports 'source', 'binary', and 'extract' (default 'source')") flags.Var(&cfg.tags, "tags", "comma-separated `list` of build tags") flags.Var(&cfg.show, "show", "enable display of additional information specified by the comma separated `list`\nThe supported values are 'traces','color', 'version', and 'verbose'") flags.Var(&cfg.format, "format", "specify format output\nThe supported values are 'text', 'json', 'sarif', and 'openvex' (default 'text')") flags.BoolVar(&version, "version", false, "print the version information") flags.Var(&scanFlag, "scan", "set the scanning level desired, one of 'module', 'package', or 'symbol' (default 'symbol')") // We don't want to print the whole usage message on each flags // error, so we set to a no-op and do the printing ourselves. flags.Usage = func() {} usage := func() { fmt.Fprint(flags.Output(), `Govulncheck reports known vulnerabilities in dependencies. Usage: govulncheck [flags] [patterns] govulncheck -mode=binary [flags] [binary] `) flags.PrintDefaults() fmt.Fprintf(flags.Output(), "\n%s\n", detailsMessage) } if err := flags.Parse(args); err != nil { if err == flag.ErrHelp { usage() // print usage only on help return errHelp } return errUsage } cfg.patterns = flags.Args() if version { cfg.show = append(cfg.show, "version") } cfg.ScanLevel = govulncheck.ScanLevel(scanFlag) cfg.ScanMode = govulncheck.ScanMode(modeFlag) if err := validateConfig(cfg, json); err != nil { fmt.Fprintln(flags.Output(), err) return errUsage } return nil } func validateConfig(cfg *config, json bool) error { // take care of default values if cfg.ScanMode == "" { cfg.ScanMode = govulncheck.ScanModeSource } if cfg.ScanLevel == "" { cfg.ScanLevel = govulncheck.ScanLevelSymbol } if json { if cfg.format != formatUnset { return fmt.Errorf("the -json flag cannot be used with -format flag") } cfg.format = formatJSON } else { if cfg.format == formatUnset { cfg.format = formatText } } // show flag is only supported with text output if cfg.format != formatText && len(cfg.show) > 0 { return fmt.Errorf("the -show flag is not supported for %s output", cfg.format) } switch cfg.ScanMode { case govulncheck.ScanModeSource: if len(cfg.patterns) == 1 && isFile(cfg.patterns[0]) { return fmt.Errorf("%q is a file.\n\n%v", cfg.patterns[0], errNoBinaryFlag) } if cfg.ScanLevel == govulncheck.ScanLevelModule && len(cfg.patterns) != 0 { return fmt.Errorf("patterns are not accepted for module only scanning") } case govulncheck.ScanModeBinary: if cfg.test { return fmt.Errorf("the -test flag is not supported in binary mode") } if len(cfg.tags) > 0 { return fmt.Errorf("the -tags flag is not supported in binary mode") } if len(cfg.patterns) != 1 { return fmt.Errorf("only 1 binary can be analyzed at a time") } if !isFile(cfg.patterns[0]) { return fmt.Errorf("%q is not a file", cfg.patterns[0]) } case govulncheck.ScanModeExtract: if cfg.test { return fmt.Errorf("the -test flag is not supported in extract mode") } if len(cfg.tags) > 0 { return fmt.Errorf("the -tags flag is not supported in extract mode") } if len(cfg.patterns) != 1 { return fmt.Errorf("only 1 binary can be extracted at a time") } if cfg.format == formatJSON { return fmt.Errorf("the json format must be off in extract mode") } if !isFile(cfg.patterns[0]) { return fmt.Errorf("%q is not a file (source extraction is not supported)", cfg.patterns[0]) } case govulncheck.ScanModeConvert: if len(cfg.patterns) != 0 { return fmt.Errorf("patterns are not accepted in convert mode") } if cfg.dir != "" { return fmt.Errorf("the -C flag is not supported in convert mode") } if cfg.test { return fmt.Errorf("the -test flag is not supported in convert mode") } if len(cfg.tags) > 0 { return fmt.Errorf("the -tags flag is not supported in convert mode") } case govulncheck.ScanModeQuery: if cfg.test { return fmt.Errorf("the -test flag is not supported in query mode") } if len(cfg.tags) > 0 { return fmt.Errorf("the -tags flag is not supported in query mode") } if cfg.format != formatJSON { return fmt.Errorf("the json format must be set in query mode") } for _, pattern := range cfg.patterns { // Parse the input here so that we can catch errors before // outputting the Config. if _, _, err := parseModuleQuery(pattern); err != nil { return err } } } return nil } func isFile(path string) bool { s, err := os.Stat(path) if err != nil { return false } return !s.IsDir() } var errFlagParse = errors.New("see -help for details") // ShowFlag is used for parsing and validation of // govulncheck -show flag. type ShowFlag []string var supportedShows = map[string]bool{ "traces": true, "color": true, "verbose": true, "version": true, } func (v *ShowFlag) Set(s string) error { if s == "" { return nil } for _, show := range strings.Split(s, ",") { sh := strings.TrimSpace(show) if _, ok := supportedShows[sh]; !ok { return errFlagParse } *v = append(*v, sh) } return nil } func (v *ShowFlag) Get() interface{} { return *v } func (v *ShowFlag) String() string { return "" } // Update the text handler h with values of the flag. func (v ShowFlag) Update(h *TextHandler) { for _, show := range v { switch show { case "traces": h.showTraces = true case "color": h.showColor = true case "version": h.showVersion = true case "verbose": h.showVerbose = true } } } // FormatFlag is used for parsing and validation of // govulncheck -format flag. type FormatFlag string const ( formatUnset = "" formatJSON = "json" formatText = "text" formatSarif = "sarif" formatOpenVEX = "openvex" ) var supportedFormats = map[string]bool{ formatJSON: true, formatText: true, formatSarif: true, formatOpenVEX: true, } func (f *FormatFlag) Get() interface{} { return *f } func (f *FormatFlag) Set(s string) error { if _, ok := supportedFormats[s]; !ok { return errFlagParse } *f = FormatFlag(s) return nil } func (f *FormatFlag) String() string { return "" } // ModeFlag is used for parsing and validation of // govulncheck -mode flag. type ModeFlag string var supportedModes = map[string]bool{ govulncheck.ScanModeSource: true, govulncheck.ScanModeBinary: true, govulncheck.ScanModeConvert: true, govulncheck.ScanModeQuery: true, govulncheck.ScanModeExtract: true, } func (f *ModeFlag) Get() interface{} { return *f } func (f *ModeFlag) Set(s string) error { if _, ok := supportedModes[s]; !ok { return errFlagParse } *f = ModeFlag(s) return nil } func (f *ModeFlag) String() string { return "" } // ScanFlag is used for parsing and validation of // govulncheck -scan flag. type ScanFlag string var supportedLevels = map[string]bool{ govulncheck.ScanLevelModule: true, govulncheck.ScanLevelPackage: true, govulncheck.ScanLevelSymbol: true, } func (f *ScanFlag) Get() interface{} { return *f } func (f *ScanFlag) Set(s string) error { if _, ok := supportedLevels[s]; !ok { return errFlagParse } *f = ScanFlag(s) return nil } func (f *ScanFlag) String() string { return "" }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/util.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "fmt" "os" "os/exec" "strings" "golang.org/x/vuln/internal" "golang.org/x/vuln/internal/govulncheck" ) // validateFindings checks that the supplied findings all obey the protocol // rules. func validateFindings(findings ...*govulncheck.Finding) error { for _, f := range findings { if f.OSV == "" { return fmt.Errorf("invalid finding: all findings must have an associated OSV") } if len(f.Trace) < 1 { return fmt.Errorf("invalid finding: all callstacks must have at least one frame") } for _, frame := range f.Trace { if frame.Version != "" && frame.Module == "" { return fmt.Errorf("invalid finding: if Frame.Version (%s) is set, Frame.Module must also be", frame.Version) } if frame.Package != "" && frame.Module == "" { return fmt.Errorf("invalid finding: if Frame.Package (%s) is set, Frame.Module must also be", frame.Package) } if frame.Function != "" && frame.Package == "" { return fmt.Errorf("invalid finding: if Frame.Function (%s) is set, Frame.Package must also be", frame.Function) } } } return nil } func moduleVersionString(modulePath, version string) string { if version == "" { return "" } if modulePath == internal.GoStdModulePath || modulePath == internal.GoCmdModulePath { version = semverToGoTag(version) } return version } func gomodExists(dir string) bool { cmd := exec.Command("go", "env", "GOMOD") cmd.Dir = dir out, err := cmd.Output() output := strings.TrimSpace(string(out)) // If module-aware mode is enabled, but there is no go.mod, GOMOD will be os.DevNull // If module-aware mode is disabled, GOMOD will be the empty string. return err == nil && !(output == os.DevNull || output == "") }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/stdlib.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "fmt" "strings" "golang.org/x/mod/semver" ) // Support functions for standard library packages. // These are copied from the internal/stdlib package in the pkgsite repo. // semverToGoTag returns the Go standard library repository tag corresponding // to semver, a version string without the initial "v". // Go tags differ from standard semantic versions in a few ways, // such as beginning with "go" instead of "v". func semverToGoTag(v string) string { if strings.HasPrefix(v, "v0.0.0") { return "master" } // Special case: v1.0.0 => go1. if v == "v1.0.0" { return "go1" } if !semver.IsValid(v) { return fmt.Sprintf("<!%s:invalid semver>", v) } goVersion := semver.Canonical(v) prerelease := semver.Prerelease(goVersion) versionWithoutPrerelease := strings.TrimSuffix(goVersion, prerelease) patch := strings.TrimPrefix(versionWithoutPrerelease, semver.MajorMinor(goVersion)+".") if patch == "0" { versionWithoutPrerelease = strings.TrimSuffix(versionWithoutPrerelease, ".0") } goVersion = fmt.Sprintf("go%s", strings.TrimPrefix(versionWithoutPrerelease, "v")) if prerelease != "" { // Go prereleases look like "beta1" instead of "beta.1". // "beta1" is bad for sorting (since beta10 comes before beta9), so // require the dot form. i := finalDigitsIndex(prerelease) if i >= 1 { if prerelease[i-1] != '.' { return fmt.Sprintf("<!%s:final digits in a prerelease must follow a period>", v) } // Remove the dot. prerelease = prerelease[:i-1] + prerelease[i:] } goVersion += strings.TrimPrefix(prerelease, "-") } return goVersion } // finalDigitsIndex returns the index of the first digit in the sequence of digits ending s. // If s doesn't end in digits, it returns -1. func finalDigitsIndex(s string) int { // Assume ASCII (since the semver package does anyway). var i int for i = len(s) - 1; i >= 0; i-- { if s[i] < '0' || s[i] > '9' { break } } if i == len(s)-1 { return -1 } return i + 1 }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/query.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "context" "fmt" "regexp" "golang.org/x/vuln/internal/client" "golang.org/x/vuln/internal/govulncheck" isem "golang.org/x/vuln/internal/semver" ) // runQuery reports vulnerabilities that apply to the queries in the config. func runQuery(ctx context.Context, handler govulncheck.Handler, cfg *config, c *client.Client) error { reqs := make([]*client.ModuleRequest, len(cfg.patterns)) for i, query := range cfg.patterns { mod, ver, err := parseModuleQuery(query) if err != nil { return err } if err := handler.Progress(queryProgressMessage(mod, ver)); err != nil { return err } reqs[i] = &client.ModuleRequest{ Path: mod, Version: ver, } } resps, err := c.ByModules(ctx, reqs) if err != nil { return err } ids := make(map[string]bool) for _, resp := range resps { for _, entry := range resp.Entries { if _, ok := ids[entry.ID]; !ok { err := handler.OSV(entry) if err != nil { return err } ids[entry.ID] = true } } } return nil } func queryProgressMessage(module, version string) *govulncheck.Progress { return &govulncheck.Progress{ Message: fmt.Sprintf("Looking up vulnerabilities in %s at %s...", module, version), } } var modQueryRegex = regexp.MustCompile(`(.+)@(.+)`) func parseModuleQuery(pattern string) (_ string, _ string, err error) { matches := modQueryRegex.FindStringSubmatch(pattern) // matches should be [module@version, module, version] if len(matches) != 3 { return "", "", fmt.Errorf("invalid query %s: must be of the form module@version", pattern) } mod, ver := matches[1], matches[2] if !isem.Valid(ver) { return "", "", fmt.Errorf("version %s is not valid semver", ver) } return mod, ver, nil }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/errors.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "errors" "strings" ) //lint:file-ignore ST1005 Ignore staticcheck message about error formatting var ( // ErrVulnerabilitiesFound indicates that vulnerabilities were detected // when running govulncheck. This returns exit status 3 when running // without the -json flag. errVulnerabilitiesFound = &exitCodeError{message: "vulnerabilities found", code: 3} // errHelp indicates that usage help was requested. errHelp = &exitCodeError{message: "help requested", code: 0} // errUsage indicates that there was a usage error on the command line. // // In this case, we assume that the user does not know how to run // govulncheck and exit with status 2. errUsage = &exitCodeError{message: "invalid usage", code: 2} // errGoVersionMismatch is used to indicate that there is a mismatch between // the Go version used to build govulncheck and the one currently on PATH. errGoVersionMismatch = errors.New(`Loading packages failed, possibly due to a mismatch between the Go version used to build govulncheck and the Go version on PATH. Consider rebuilding govulncheck with the current Go version.`) // errNoGoMod indicates that a go.mod file was not found in this module. errNoGoMod = errors.New(`no go.mod file govulncheck only works with Go modules. Try navigating to your module directory. Otherwise, run go mod init to make your project a module. See https://go.dev/doc/modules/managing-dependencies for more information.`) // errNoBinaryFlag indicates that govulncheck was run on a file, without // the -mode=binary flag. errNoBinaryFlag = errors.New(`By default, govulncheck runs source analysis on Go modules. Did you mean to run govulncheck with -mode=binary? For details, run govulncheck -h.`) ) type exitCodeError struct { message string code int } func (e *exitCodeError) Error() string { return e.message } func (e *exitCodeError) ExitCode() int { return e.code } // isGoVersionMismatchError checks if err is due to mismatch between // the Go version used to build govulncheck and the one currently // on PATH. func isGoVersionMismatchError(err error) bool { msg := err.Error() // See golang.org/x/tools/go/packages/packages.go. return strings.Contains(msg, "This application uses version go") && strings.Contains(msg, "It may fail to process source files") }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/result_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "strings" "testing" "golang.org/x/vuln/internal/govulncheck" ) func TestFrame(t *testing.T) { for _, test := range []struct { name string frame *govulncheck.Frame short bool wantFunc string wantPos string }{ { name: "position and function", frame: &govulncheck.Frame{ Package: "golang.org/x/vuln/internal/vulncheck", Function: "Foo", Position: &govulncheck.Position{Filename: "some/path/file.go", Line: 12}, }, wantFunc: "golang.org/x/vuln/internal/vulncheck.Foo", wantPos: "some/path/file.go:12", }, { name: "receiver", frame: &govulncheck.Frame{ Package: "golang.org/x/vuln/internal/vulncheck", Receiver: "Bar", Function: "Foo", }, wantFunc: "golang.org/x/vuln/internal/vulncheck.Bar.Foo", }, { name: "function and receiver", frame: &govulncheck.Frame{Receiver: "*ServeMux", Function: "Handle"}, wantFunc: "ServeMux.Handle", }, { name: "package and function", frame: &govulncheck.Frame{Package: "net/http", Function: "Get"}, wantFunc: "net/http.Get", }, { name: "package, function and receiver", frame: &govulncheck.Frame{Package: "net/http", Receiver: "*ServeMux", Function: "Handle"}, wantFunc: "net/http.ServeMux.Handle", }, { name: "short", frame: &govulncheck.Frame{Package: "net/http", Function: "Get"}, short: true, wantFunc: "http.Get", }, } { t.Run(test.name, func(t *testing.T) { buf := &strings.Builder{} addSymbolName(buf, test.frame, test.short) got := buf.String() if got != test.wantFunc { t.Errorf("want %v func name; got %v", test.wantFunc, got) } if got := posToString(test.frame.Position); got != test.wantPos { t.Errorf("want %v call position; got %v", test.wantPos, got) } }) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/extract.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "encoding/json" "fmt" "io" "sort" "golang.org/x/vuln/internal/derrors" "golang.org/x/vuln/internal/vulncheck" ) const ( // extractModeID is the unique name of the extract mode protocol extractModeID = "govulncheck-extract" extractModeVersion = "0.1.0" ) // header information for the blob output. type header struct { Name string `json:"name"` Version string `json:"version"` } // runExtract dumps the extracted abstraction of binary at cfg.patterns to out. // It prints out exactly two blob messages, one with the header and one with // the vulncheck.Bin as the body. func runExtract(cfg *config, out io.Writer) (err error) { defer derrors.Wrap(&err, "govulncheck") bin, err := createBin(cfg.patterns[0]) if err != nil { return err } sortBin(bin) // sort for easier testing and validation header := header{ Name: extractModeID, Version: extractModeVersion, } enc := json.NewEncoder(out) if err := enc.Encode(header); err != nil { return fmt.Errorf("marshaling blob header: %v", err) } if err := enc.Encode(bin); err != nil { return fmt.Errorf("marshaling blob body: %v", err) } return nil } func sortBin(bin *vulncheck.Bin) { sort.SliceStable(bin.PkgSymbols, func(i, j int) bool { return bin.PkgSymbols[i].Pkg+"."+bin.PkgSymbols[i].Name < bin.PkgSymbols[j].Pkg+"."+bin.PkgSymbols[j].Name }) }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/query_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "context" "strings" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/vuln/internal/client" "golang.org/x/vuln/internal/osv" "golang.org/x/vuln/internal/test" ) func TestRunQuery(t *testing.T) { e := &osv.Entry{ ID: "GO-1999-0001", Affected: []osv.Affected{{ Module: osv.Module{Path: "bad.com"}, Ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Fixed: "1.2.3"}}, }}, EcosystemSpecific: osv.EcosystemSpecific{ Packages: []osv.Package{{ Path: "bad.com", }, { Path: "bad.com/bad", }}, }, }, { Module: osv.Module{Path: "unfixable.com"}, Ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}}, // no fix }}, EcosystemSpecific: osv.EcosystemSpecific{ Packages: []osv.Package{{ Path: "unfixable.com", }}, }, }}, } e2 := &osv.Entry{ ID: "GO-1999-0002", Affected: []osv.Affected{{ Module: osv.Module{Path: "bad.com"}, Ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Fixed: "1.2.0"}}, }}, EcosystemSpecific: osv.EcosystemSpecific{ Packages: []osv.Package{{ Path: "bad.com/pkg", }, }, }, }}, } stdlib := &osv.Entry{ ID: "GO-2000-0003", Affected: []osv.Affected{{ Module: osv.Module{Path: "stdlib"}, Ranges: []osv.Range{{ Type: osv.RangeTypeSemver, Events: []osv.RangeEvent{{Introduced: "0"}, {Fixed: "1.19.4"}}, }}, EcosystemSpecific: osv.EcosystemSpecific{ Packages: []osv.Package{{ Path: "net/http", }}, }, }}, } c, err := client.NewInMemoryClient([]*osv.Entry{e, e2, stdlib}) if err != nil { t.Fatal(err) } ctx := context.Background() for _, tc := range []struct { query []string want []*osv.Entry }{ { query: []string{"stdlib@go1.18"}, want: []*osv.Entry{stdlib}, }, { query: []string{"stdlib@1.18"}, want: []*osv.Entry{stdlib}, }, { query: []string{"stdlib@v1.18.0"}, want: []*osv.Entry{stdlib}, }, { query: []string{"bad.com@1.2.3"}, want: nil, }, { query: []string{"bad.com@v1.1.0"}, want: []*osv.Entry{e, e2}, }, { query: []string{"unfixable.com@2.0.0"}, want: []*osv.Entry{e}, }, { // each entry should only show up once query: []string{"bad.com@1.1.0", "unfixable.com@2.0.0"}, want: []*osv.Entry{e, e2}, }, { query: []string{"stdlib@1.18", "unfixable.com@2.0.0"}, want: []*osv.Entry{stdlib, e}, }, } { t.Run(strings.Join(tc.query, ","), func(t *testing.T) { h := test.NewMockHandler() err := runQuery(ctx, h, &config{patterns: tc.query}, c) if err != nil { t.Fatal(err) } if diff := cmp.Diff(h.OSVMessages, tc.want); diff != "" { t.Errorf("runQuery: unexpected diff:\n%s", diff) } }) } } func TestParseModuleQuery(t *testing.T) { for _, tc := range []struct { pattern, wantMod, wantVer string wantErr string }{ { pattern: "stdlib@go1.18", wantMod: "stdlib", wantVer: "go1.18", }, { pattern: "golang.org/x/tools@v0.0.0-20140414041502-123456789012", wantMod: "golang.org/x/tools", wantVer: "v0.0.0-20140414041502-123456789012", }, { pattern: "golang.org/x/tools", wantErr: "invalid query", }, { pattern: "golang.org/x/tools@1.0.0.2", wantErr: "not valid semver", }, } { t.Run(tc.pattern, func(t *testing.T) { gotMod, gotVer, err := parseModuleQuery(tc.pattern) if tc.wantErr == "" { if err != nil { t.Fatal(err) } if gotMod != tc.wantMod || gotVer != tc.wantVer { t.Errorf("parseModuleQuery = (%s, %s), want (%s, %s)", gotMod, gotVer, tc.wantMod, tc.wantVer) } } else { if err == nil || !strings.Contains(err.Error(), tc.wantErr) { t.Errorf("parseModuleQuery = %v, want err containing %s", err, tc.wantErr) } } }) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/template_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "testing" "github.com/google/go-cmp/cmp" "golang.org/x/vuln/internal/govulncheck" ) func TestCompactTrace(t *testing.T) { for _, tc := range []struct { trace []*govulncheck.Frame want string }{ { // binary mode []*govulncheck.Frame{{Function: "Foo"}}, "Foo", }, { []*govulncheck.Frame{ {Module: "vuln", Function: "V"}, {Module: "user", Function: "W"}, {Module: "user", Function: "U"}, }, "W calls V", }, { []*govulncheck.Frame{ {Module: "vuln", Function: "V"}, {Module: "interim", Function: "I"}, {Module: "user", Function: "U"}, {Module: "user", Function: "W"}, }, "U calls I, which calls V", }, { []*govulncheck.Frame{ {Module: "vuln", Function: "V"}, {Module: "x", Function: "X"}, {Module: "interim", Function: "K"}, {Module: "interim", Function: "J"}, {Module: "interim", Function: "I"}, {Module: "user", Function: "U"}, {Module: "user", Function: "W"}, }, "U calls I, which eventually calls V", }, } { tc := tc t.Run(tc.want, func(t *testing.T) { f := &govulncheck.Finding{Trace: tc.trace} got := compactTrace(f) if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("(-want got+) %s", diff) } }) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/color.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan const ( // These are all the constants for the terminal escape strings colorEscape = "\033[" colorEnd = "m" colorReset = colorEscape + "0" + colorEnd colorBold = colorEscape + "1" + colorEnd colorFaint = colorEscape + "2" + colorEnd colorUnderline = colorEscape + "4" + colorEnd colorBlink = colorEscape + "5" + colorEnd fgBlack = colorEscape + "30" + colorEnd fgRed = colorEscape + "31" + colorEnd fgGreen = colorEscape + "32" + colorEnd fgYellow = colorEscape + "33" + colorEnd fgBlue = colorEscape + "34" + colorEnd fgMagenta = colorEscape + "35" + colorEnd fgCyan = colorEscape + "36" + colorEnd fgWhite = colorEscape + "37" + colorEnd bgBlack = colorEscape + "40" + colorEnd bgRed = colorEscape + "41" + colorEnd bgGreen = colorEscape + "42" + colorEnd bgYellow = colorEscape + "43" + colorEnd bgBlue = colorEscape + "44" + colorEnd bgMagenta = colorEscape + "45" + colorEnd bgCyan = colorEscape + "46" + colorEnd bgWhite = colorEscape + "47" + colorEnd fgBlackHi = colorEscape + "90" + colorEnd fgRedHi = colorEscape + "91" + colorEnd fgGreenHi = colorEscape + "92" + colorEnd fgYellowHi = colorEscape + "93" + colorEnd fgBlueHi = colorEscape + "94" + colorEnd fgMagentaHi = colorEscape + "95" + colorEnd fgCyanHi = colorEscape + "96" + colorEnd fgWhiteHi = colorEscape + "97" + colorEnd bgBlackHi = colorEscape + "100" + colorEnd bgRedHi = colorEscape + "101" + colorEnd bgGreenHi = colorEscape + "102" + colorEnd bgYellowHi = colorEscape + "103" + colorEnd bgBlueHi = colorEscape + "104" + colorEnd bgMagentaHi = colorEscape + "105" + colorEnd bgCyanHi = colorEscape + "106" + colorEnd bgWhiteHi = colorEscape + "107" + colorEnd ) const ( _ = colorReset _ = colorBold _ = colorFaint _ = colorUnderline _ = colorBlink _ = fgBlack _ = fgRed _ = fgGreen _ = fgYellow _ = fgBlue _ = fgMagenta _ = fgCyan _ = fgWhite _ = fgBlackHi _ = fgRedHi _ = fgGreenHi _ = fgYellowHi _ = fgBlueHi _ = fgMagentaHi _ = fgCyanHi _ = fgWhiteHi _ = bgBlack _ = bgRed _ = bgGreen _ = bgYellow _ = bgBlue _ = bgMagenta _ = bgCyan _ = bgWhite _ = bgBlackHi _ = bgRedHi _ = bgGreenHi _ = bgYellowHi _ = bgBlueHi _ = bgMagentaHi _ = bgCyanHi _ = bgWhiteHi )
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/template.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "go/token" "io" "path" "sort" "strconv" "strings" "unicode" "unicode/utf8" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/osv" "golang.org/x/vuln/internal/traces" ) type findingSummary struct { *govulncheck.Finding Compact string OSV *osv.Entry } type summaryCounters struct { VulnerabilitiesCalled int ModulesCalled int VulnerabilitiesImported int VulnerabilitiesRequired int StdlibCalled bool } func fixupFindings(osvs []*osv.Entry, findings []*findingSummary) { for _, f := range findings { f.OSV = getOSV(osvs, f.Finding.OSV) } } func groupByVuln(findings []*findingSummary) [][]*findingSummary { return groupBy(findings, func(left, right *findingSummary) int { return -strings.Compare(left.OSV.ID, right.OSV.ID) }) } func groupByModule(findings []*findingSummary) [][]*findingSummary { return groupBy(findings, func(left, right *findingSummary) int { return strings.Compare(left.Trace[0].Module, right.Trace[0].Module) }) } func groupBy(findings []*findingSummary, compare func(left, right *findingSummary) int) [][]*findingSummary { switch len(findings) { case 0: return nil case 1: return [][]*findingSummary{findings} } sort.SliceStable(findings, func(i, j int) bool { return compare(findings[i], findings[j]) < 0 }) result := [][]*findingSummary{} first := 0 for i, next := range findings { if i == first { continue } if compare(findings[first], next) != 0 { result = append(result, findings[first:i]) first = i } } result = append(result, findings[first:]) return result } func isRequired(findings []*findingSummary) bool { for _, f := range findings { if f.Trace[0].Module != "" { return true } } return false } func isImported(findings []*findingSummary) bool { for _, f := range findings { if f.Trace[0].Package != "" { return true } } return false } func isCalled(findings []*findingSummary) bool { for _, f := range findings { if f.Trace[0].Function != "" { return true } } return false } func getOSV(osvs []*osv.Entry, id string) *osv.Entry { for _, entry := range osvs { if entry.ID == id { return entry } } return &osv.Entry{ ID: id, DatabaseSpecific: &osv.DatabaseSpecific{}, } } func newFindingSummary(f *govulncheck.Finding) *findingSummary { return &findingSummary{ Finding: f, Compact: compactTrace(f), } } // platforms returns a string describing the GOOS, GOARCH, // or GOOS/GOARCH pairs that the vuln affects for a particular // module mod. If it affects all of them, it returns the empty // string. // // When mod is an empty string, returns platform information for // all modules of e. func platforms(mod string, e *osv.Entry) []string { if e == nil { return nil } platforms := map[string]bool{} for _, a := range e.Affected { if mod != "" && a.Module.Path != mod { continue } for _, p := range a.EcosystemSpecific.Packages { for _, os := range p.GOOS { // In case there are no specific architectures, // just list the os entries. if len(p.GOARCH) == 0 { platforms[os] = true continue } // Otherwise, list all the os+arch combinations. for _, arch := range p.GOARCH { platforms[os+"/"+arch] = true } } // Cover the case where there are no specific // operating systems listed. if len(p.GOOS) == 0 { for _, arch := range p.GOARCH { platforms[arch] = true } } } } var keys []string for k := range platforms { keys = append(keys, k) } sort.Strings(keys) return keys } func posToString(p *govulncheck.Position) string { if p == nil || p.Line <= 0 { return "" } return token.Position{ Filename: AbsRelShorter(p.Filename), Offset: p.Offset, Line: p.Line, Column: p.Column, }.String() } func symbol(frame *govulncheck.Frame, short bool) string { buf := &strings.Builder{} addSymbolName(buf, frame, short) return buf.String() } // compactTrace returns a short description of the call stack. // It prefers to show you the edge from the top module to other code, along with // the vulnerable symbol. // Where the vulnerable symbol directly called by the users code, it will only // show those two points. // If the vulnerable symbol is in the users code, it will show the entry point // and the vulnerable symbol. func compactTrace(finding *govulncheck.Finding) string { compact := traces.Compact(finding) if len(compact) == 0 { return "" } l := len(compact) iTop := l - 1 buf := &strings.Builder{} topPos := posToString(compact[iTop].Position) if topPos != "" { buf.WriteString(topPos) buf.WriteString(": ") } if l > 1 { // print the root of the compact trace addSymbolName(buf, compact[iTop], true) buf.WriteString(" calls ") } if l > 2 { // print next element of the trace, if any addSymbolName(buf, compact[iTop-1], true) buf.WriteString(", which") if l > 3 { // don't print the third element, just acknowledge it buf.WriteString(" eventually") } buf.WriteString(" calls ") } addSymbolName(buf, compact[0], true) // print the vulnerable symbol return buf.String() } // notIdentifier reports whether ch is an invalid identifier character. func notIdentifier(ch rune) bool { return !('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '0' <= ch && ch <= '9' || ch == '_' || ch >= utf8.RuneSelf && (unicode.IsLetter(ch) || unicode.IsDigit(ch))) } // importPathToAssumedName is taken from goimports, it works out the natural imported name // for a package. // This is used to get a shorter identifier in the compact stack trace func importPathToAssumedName(importPath string) string { base := path.Base(importPath) if strings.HasPrefix(base, "v") { if _, err := strconv.Atoi(base[1:]); err == nil { dir := path.Dir(importPath) if dir != "." { base = path.Base(dir) } } } base = strings.TrimPrefix(base, "go-") if i := strings.IndexFunc(base, notIdentifier); i >= 0 { base = base[:i] } return base } func addSymbolName(w io.Writer, frame *govulncheck.Frame, short bool) { if frame.Function == "" { return } if frame.Package != "" { pkg := frame.Package if short { pkg = importPathToAssumedName(frame.Package) } io.WriteString(w, pkg) io.WriteString(w, ".") } if frame.Receiver != "" { if frame.Receiver[0] == '*' { io.WriteString(w, frame.Receiver[1:]) } else { io.WriteString(w, frame.Receiver) } io.WriteString(w, ".") } funcname := strings.Split(frame.Function, "$")[0] io.WriteString(w, funcname) }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/print_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan_test import ( "bytes" "flag" "io/fs" "os" "path/filepath" "strings" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/vuln/internal/govulncheck" "golang.org/x/vuln/internal/scan" ) var update = flag.Bool("update", false, "update test files with results") func TestPrinting(t *testing.T) { testdata := os.DirFS("testdata") inputs, err := fs.Glob(testdata, "*.json") if err != nil { t.Fatal(err) } for _, input := range inputs { name := strings.TrimSuffix(input, ".json") rawJSON, _ := fs.ReadFile(testdata, input) textfiles, err := fs.Glob(testdata, name+"*.txt") if err != nil { t.Fatal(err) } for _, textfile := range textfiles { textname := strings.TrimSuffix(textfile, ".txt") t.Run(textname, func(t *testing.T) { wantText, _ := fs.ReadFile(testdata, textfile) got := &bytes.Buffer{} handler := scan.NewTextHandler(got) scan.ShowFlag(strings.Split(textname, "_")[1:]).Update(handler) testRunHandler(t, rawJSON, handler) if diff := cmp.Diff(string(wantText), got.String()); diff != "" { if *update { // write the output back to the file os.WriteFile(filepath.Join("testdata", textfile), got.Bytes(), 0644) return } t.Errorf("Readable mismatch (-want, +got):\n%s", diff) } }) } t.Run(name+"_json", func(t *testing.T) { // this effectively tests that we can round trip the json got := &strings.Builder{} testRunHandler(t, rawJSON, govulncheck.NewJSONHandler(got)) if diff := cmp.Diff(strings.TrimSpace(string(rawJSON)), strings.TrimSpace(got.String())); diff != "" { t.Errorf("JSON mismatch (-want, +got):\n%s", diff) } }) } } func testRunHandler(t *testing.T, rawJSON []byte, handler govulncheck.Handler) { if err := govulncheck.HandleJSON(bytes.NewReader(rawJSON), handler); err != nil { t.Fatal(err) } err := scan.Flush(handler) switch e := err.(type) { case nil: case interface{ ExitCode() int }: if e.ExitCode() != 0 && e.ExitCode() != 3 { // not success or vulnerabilities found t.Fatal(err) } default: t.Fatal(err) } }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/filepath.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "path/filepath" "strings" ) // AbsRelShorter takes path and returns its path relative // to the current directory, if shorter. Returns path // when path is an empty string or upon any error. func AbsRelShorter(path string) string { if path == "" { return "" } c, err := filepath.Abs(".") if err != nil { return path } r, err := filepath.Rel(c, path) if err != nil { return path } rSegments := strings.Split(r, string(filepath.Separator)) pathSegments := strings.Split(path, string(filepath.Separator)) if len(rSegments) < len(pathSegments) { return r } return path }
scan
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/source_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "strings" "testing" "golang.org/x/vuln/internal/govulncheck" ) func TestSummarizeCallStack(t *testing.T) { for _, test := range []struct { in, want string }{ {"ma.a.F", "a.F"}, {"m1.p1.F", "p1.F"}, {"mv.v.V", "v.V"}, { "m1.p1.F mv.v.V", "p1.F calls v.V", }, { "m1.p1.F m1.p2.G mv.v.V1 mv.v.v2", "p2.G calls v.V1, which calls v.v2", }, { "m1.p1.F m1.p2.G mv.v.V$1 mv.v.V1", "p2.G calls v.V, which calls v.V1", }, { "m1.p1.F m1.p2.G$1 mv.v.V1", "p2.G calls v.V1", }, { "m1.p1.F m1.p2.G$1 mv.v.V$1 mv.v.V1", "p2.G calls v.V, which calls v.V1", }, { "m1.p1.F w.x.Y m1.p2.G ma.a.H mb.b.I mc.c.J mv.v.V", "p2.G calls a.H, which eventually calls v.V", }, { "m1.p1.F w.x.Y m1.p2.G ma.a.H mb.b.I mc.c.J mv.v.V$1 mv.v.V1", "p2.G calls a.H, which eventually calls v.V1", }, { "m1.p1.F m1.p1.F$1 ma.a.H mb.b.I mv.v.V1", "p1.F calls a.H, which eventually calls v.V1", }, } { in := stringToFinding(test.in) got := compactTrace(in) if got != test.want { t.Errorf("%s:\ngot %s\nwant %s", test.in, got, test.want) } } } func stringToFinding(s string) *govulncheck.Finding { f := &govulncheck.Finding{} entries := strings.Fields(s) for i := len(entries) - 1; i >= 0; i-- { e := entries[i] firstDot := strings.Index(e, ".") lastDot := strings.LastIndex(e, ".") f.Trace = append(f.Trace, &govulncheck.Frame{ Module: e[:firstDot], Package: e[:firstDot] + "/" + e[firstDot+1:lastDot], Function: e[lastDot+1:], }) } return f }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/module-vuln.txt
=== Module Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Your code may be affected by 1 vulnerability. Use '-scan symbol' for more fine grained vulnerability detection.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/multi-stack-modlevel.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "module" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1" } ] } } { "osv": { "id": "GO-0000-0002", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": {} } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0002" } } } { "finding": { "osv": "GO-0000-0002", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/module-vuln.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "module" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/binary.txt
=== Symbol Results === Vulnerability #1: GO-0000-0002 Stdlib vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0002 Standard library Found in: net/http@go0.0.1 Fixed in: N/A Example traces found: #1: http.Vuln2 Vulnerability #2: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Example traces found: #1: vmod.Vuln Your code is affected by 2 vulnerabilities from 1 module and the Go standard library. This scan found no other vulnerabilities in packages you import or modules you require. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/package-vuln.txt
=== Package Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Your code may be affected by 1 vulnerability. This scan also found 0 vulnerabilities in modules you require. Use '-scan symbol' for more fine grained vulnerability detection and '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-two-imports.txt
=== Symbol Results === No vulnerabilities found. Your code is affected by 0 vulnerabilities. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/source.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "vmod", "function": "Vuln" }, { "module": "golang.org/app", "version": "v0.0.1", "package": "main", "function": "main" } ] } } { "osv": { "id": "GO-0000-0002", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Stdlib vulnerability", "affected": [ { "package": { "name": "stdlib", "ecosystem": "" }, "ecosystem_specific": {} } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0002" } } } { "finding": { "osv": "GO-0000-0002", "trace": [ { "module": "stdlib", "version": "v0.0.1" } ] } } { "finding": { "osv": "GO-0000-0002", "trace": [ { "module": "stdlib", "version": "v0.0.1", "package": "net/http" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/binary.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod", "function": "Vuln" } ] } } { "osv": { "id": "GO-0000-0002", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Stdlib vulnerability", "affected": [ { "package": { "name": "stdlib", "ecosystem": "" }, "ecosystem_specific": {} } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0002" } } } { "finding": { "osv": "GO-0000-0002", "trace": [ { "module": "stdlib", "version": "v0.0.1" } ] } } { "finding": { "osv": "GO-0000-0002", "trace": [ { "module": "stdlib", "version": "v0.0.1", "package": "net/http" } ] } } { "finding": { "osv": "GO-0000-0002", "trace": [ { "module": "stdlib", "version": "v0.0.1", "package": "net/http", "function": "Vuln2" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-two-os-only.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "two-os-only", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "1.2.0" } ] } ], "ecosystem_specific": { "imports": [ { "goos": [ "windows, linux" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/two-os-only" } } } { "finding": { "osv": "two-os-only", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/multi-stack-modlevel.txt
=== Module Results === Vulnerability #1: GO-0000-0002 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0002 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Vulnerability #2: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Your code may be affected by 2 vulnerabilities. Use '-scan symbol' for more fine grained vulnerability detection.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-all.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "All", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "", "affected": null, "database_specific": { "url": "https://pkg.go.dev/vuln/All" } } } { "finding": { "osv": "All", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/package-vuln.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "package" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1" } ] } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/mixed-calls.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1" } ] } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod", "function": "VulnFoo" }, { "module": "golang.org/main", "version": "v0.0.1", "package": "golang.org/main", "function": "main" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/source_traces.txt
=== Symbol Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Example traces found: #1: for function vmod.Vuln main.main vmod.Vuln Your code is affected by 1 vulnerability from the Go standard library. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-one-arch-only.txt
=== Symbol Results === No vulnerabilities found. Your code is affected by 0 vulnerabilities. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-one-import.txt
=== Symbol Results === No vulnerabilities found. Your code is affected by 0 vulnerabilities. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-one-arch-only.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "one-arch-only", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "1.2.0" } ] } ], "ecosystem_specific": { "imports": [ { "goos": [ "amd64" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/one-arch-only" } } } { "finding": { "osv": "one-arch-only", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/source.txt
=== Symbol Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Example traces found: #1: main.main calls vmod.Vuln Your code is affected by 1 vulnerability from the Go standard library. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-two-imports.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "two-imports", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "1.2.0" } ] } ], "ecosystem_specific": { "imports": [ { "goos": [ "windows" ], "goarch": [ "amd64" ] }, { "goos": [ "linux" ], "goarch": [ "amd64" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/two-imports" } } } { "finding": { "osv": "two-imports", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-all.txt
=== Symbol Results === No vulnerabilities found. Your code is affected by 0 vulnerabilities. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/multi-stacks.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "GO-0000-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "Third-party vulnerability", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ecosystem_specific": { "imports": [ { "goos": [ "amd" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-0000-0001" } } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "vmod", "function": "Vuln" }, { "module": "golang.org/main", "version": "v0.0.1", "package": "main", "function": "main" } ] } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "vmod", "function": "VulnFoo" }, { "module": "golang.org/main", "version": "v0.0.1", "package": "main", "function": "main" } ] } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.0.4", "trace": [ { "module": "golang.org/vmod1", "version": "v0.0.3", "package": "vmod1", "function": "Vuln" }, { "module": "golang.org/other", "version": "v2.0.3", "package": "other", "function": "Foo" } ] } } { "finding": { "osv": "GO-0000-0001", "fixed_version": "v0.0.4", "trace": [ { "module": "golang.org/vmod1", "version": "v0.0.3", "package": "vmod1", "function": "VulnFoo" }, { "module": "golang.org/other", "version": "v2.0.3", "package": "other", "function": "Bar" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-one-import.json
{ "config": { "protocol_version": "v0.1.0", "scanner_name": "govulncheck", "scan_level": "symbol" } } { "osv": { "id": "one-import", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "", "affected": [ { "package": { "name": "golang.org/vmod", "ecosystem": "" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "1.2.0" } ] } ], "ecosystem_specific": { "imports": [ { "goos": [ "windows", "linux" ], "goarch": [ "amd64", "wasm" ] } ] } } ], "database_specific": { "url": "https://pkg.go.dev/vuln/one-import" } } } { "finding": { "osv": "one-import", "fixed_version": "v0.1.3", "trace": [ { "module": "golang.org/vmod", "version": "v0.0.1", "package": "golang.org/vmod" } ] } }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/mixed-calls.txt
=== Symbol Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Example traces found: #1: main.main calls vmod.VulnFoo Your code is affected by 1 vulnerability from 1 module. This scan found no other vulnerabilities in packages you import or modules you require. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/platform-two-os-only.txt
=== Symbol Results === No vulnerabilities found. Your code is affected by 0 vulnerabilities. This scan also found 1 vulnerability in packages you import and 0 vulnerabilities in modules you require, but your code doesn't appear to call these vulnerabilities. Use '-show verbose' for more details.
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/scan/testdata/multi-stacks.txt
=== Symbol Results === Vulnerability #1: GO-0000-0001 Third-party vulnerability More info: https://pkg.go.dev/vuln/GO-0000-0001 Module: golang.org/vmod Found in: golang.org/vmod@v0.0.1 Fixed in: golang.org/vmod@v0.1.3 Platforms: amd Example traces found: #1: main.main calls vmod.Vuln #2: main.main calls vmod.VulnFoo Module: golang.org/vmod1 Found in: golang.org/vmod1@v0.0.3 Fixed in: golang.org/vmod1@v0.0.4 Example traces found: #1: other.Foo calls vmod1.Vuln #2: other.Bar calls vmod1.VulnFoo Your code is affected by 1 vulnerability from the Go standard library. This scan found no other vulnerabilities in packages you import or modules you require. Use '-show verbose' for more details.
govulncheck
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/govulncheck/govulncheck.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package govulncheck contains the JSON output structs for govulncheck. // // govulncheck supports streaming JSON by emitting a series of Message // objects as it analyzes user code and discovers vulnerabilities. // Streaming JSON is useful for displaying progress in real-time for // large projects where govulncheck execution might take some time. // // govulncheck JSON emits configuration used to perform the analysis, // a user-friendly message about what is being analyzed, and the // vulnerability findings. Findings for the same vulnerability can // can be emitted several times. For instance, govulncheck JSON will // emit a finding when it sees that a vulnerable module is required // before proceeding to check if the vulnerability is imported or called. // Please see documentation on Message and related types for precise // details on the stream encoding. // // There are no guarantees on the order of messages. The pattern of emitted // messages can change in the future. Clients can follow code in handler.go // for consuming the streaming JSON programmatically. package govulncheck import ( "time" "golang.org/x/vuln/internal/osv" ) const ( // ProtocolVersion is the current protocol version this file implements ProtocolVersion = "v1.0.0" ) // Message is an entry in the output stream. It will always have exactly one // field filled in. type Message struct { Config *Config `json:"config,omitempty"` Progress *Progress `json:"progress,omitempty"` // OSV is emitted for every vulnerability in the current database // that applies to user modules regardless of their version. If a // module is being used at a vulnerable version, the corresponding // OSV will be referenced in Findings depending on the type of usage // and the desired scan level. OSV *osv.Entry `json:"osv,omitempty"` Finding *Finding `json:"finding,omitempty"` } // Config must occur as the first message of a stream and informs the client // about the information used to generate the findings. // The only required field is the protocol version. type Config struct { // ProtocolVersion specifies the version of the JSON protocol. ProtocolVersion string `json:"protocol_version"` // ScannerName is the name of the tool, for example, govulncheck. // // We expect this JSON format to be used by other tools that wrap // govulncheck, which will have a different name. ScannerName string `json:"scanner_name,omitempty"` // ScannerVersion is the version of the tool. ScannerVersion string `json:"scanner_version,omitempty"` // DB is the database used by the tool, for example, // vuln.go.dev. DB string `json:"db,omitempty"` // LastModified is the last modified time of the data source. DBLastModified *time.Time `json:"db_last_modified,omitempty"` // GoVersion is the version of Go used for analyzing standard library // vulnerabilities. GoVersion string `json:"go_version,omitempty"` // ScanLevel instructs govulncheck to analyze at a specific level of detail. // Valid values include module, package and symbol. ScanLevel ScanLevel `json:"scan_level,omitempty"` // ScanMode instructs govulncheck how to interpret the input and // what to do with it. Valid values are source, binary, query, // and extract. ScanMode ScanMode `json:"scan_mode,omitempty"` } // Progress messages are informational only, intended to allow users to monitor // the progress of a long running scan. // A stream must remain fully valid and able to be interpreted with all progress // messages removed. type Progress struct { // A time stamp for the message. Timestamp *time.Time `json:"time,omitempty"` // Message is the progress message. Message string `json:"message,omitempty"` } // Finding contains information on a discovered vulnerability. Each vulnerability // will likely have multiple findings in JSON mode. This is because govulncheck // emits findings as it does work, and therefore could emit one module level, // one package level, and potentially multiple symbol level findings depending // on scan level. // Multiple symbol level findings can be emitted when multiple symbols of the // same vuln are called or govulncheck decides to show multiple traces for the // same symbol. type Finding struct { // OSV is the id of the detected vulnerability. OSV string `json:"osv,omitempty"` // FixedVersion is the module version where the vulnerability was // fixed. This is empty if a fix is not available. // // If there are multiple fixed versions in the OSV report, this will // be the fixed version in the latest range event for the OSV report. // // For example, if the range events are // {introduced: 0, fixed: 1.0.0} and {introduced: 1.1.0}, the fixed version // will be empty. // // For the stdlib, we will show the fixed version closest to the // Go version that is used. For example, if a fix is available in 1.17.5 and // 1.18.5, and the GOVERSION is 1.17.3, 1.17.5 will be returned as the // fixed version. FixedVersion string `json:"fixed_version,omitempty"` // Trace contains an entry for each frame in the trace. // // Frames are sorted starting from the imported vulnerable symbol // until the entry point. The first frame in Frames should match // Symbol. // // In binary mode, trace will contain a single-frame with no position // information. // // For module level source findings, the trace will contain a single-frame // with no symbol, position, or package information. For package level source // findings, the trace will contain a single-frame with no symbol or position // information. Trace []*Frame `json:"trace,omitempty"` } // Frame represents an entry in a finding trace. type Frame struct { // Module is the module path of the module containing this symbol. // // Importable packages in the standard library will have the path "stdlib". Module string `json:"module"` // Version is the module version from the build graph. Version string `json:"version,omitempty"` // Package is the import path. Package string `json:"package,omitempty"` // Function is the function name. Function string `json:"function,omitempty"` // Receiver is the receiver type if the called symbol is a method. // // The client can create the final symbol name by // prepending Receiver to FuncName. Receiver string `json:"receiver,omitempty"` // Position describes an arbitrary source position // including the file, line, and column location. // A Position is valid if the line number is > 0. // // The filenames are relative to the directory of // the enclosing module and always use "/" for // portability. Position *Position `json:"position,omitempty"` } // Position represents arbitrary source position. type Position struct { Filename string `json:"filename,omitempty"` // filename, if any Offset int `json:"offset"` // byte offset, starting at 0 Line int `json:"line"` // line number, starting at 1 Column int `json:"column"` // column number, starting at 1 (byte count) } // ScanLevel represents the detail level at which a scan occurred. // This can be necessary to correctly interpret the findings, for instance if // a scan is at symbol level and a finding does not have a symbol it means the // vulnerability was imported but not called. If the scan however was at // "package" level, that determination cannot be made. type ScanLevel string const ( ScanLevelModule = "module" ScanLevelPackage = "package" ScanLevelSymbol = "symbol" ) // WantSymbols can be used to check whether the scan level is one that is able // to generate symbol-level findings. func (l ScanLevel) WantSymbols() bool { return l == ScanLevelSymbol } // WantPackages can be used to check whether the scan level is one that is able // to generate package-level findings. func (l ScanLevel) WantPackages() bool { return l == ScanLevelPackage || l == ScanLevelSymbol } // ScanMode represents the mode in which a scan occurred. This can // be necessary to correctly to interpret findings. For instance, // a binary can be checked for vulnerabilities or the user just wants // to extract minimal data necessary for the vulnerability check. type ScanMode string const ( ScanModeSource = "source" ScanModeBinary = "binary" ScanModeConvert = "convert" ScanModeQuery = "query" ScanModeExtract = "extract" // currently, only binary extraction is supported )
govulncheck
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/govulncheck/jsonhandler.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package govulncheck import ( "encoding/json" "io" "golang.org/x/vuln/internal/osv" ) type jsonHandler struct { enc *json.Encoder } // NewJSONHandler returns a handler that writes govulncheck output as json. func NewJSONHandler(w io.Writer) Handler { enc := json.NewEncoder(w) enc.SetIndent("", " ") return &jsonHandler{enc: enc} } // Config writes config block in JSON to the underlying writer. func (h *jsonHandler) Config(config *Config) error { return h.enc.Encode(Message{Config: config}) } // Progress writes a progress message in JSON to the underlying writer. func (h *jsonHandler) Progress(progress *Progress) error { return h.enc.Encode(Message{Progress: progress}) } // OSV writes an osv entry in JSON to the underlying writer. func (h *jsonHandler) OSV(entry *osv.Entry) error { return h.enc.Encode(Message{OSV: entry}) } // Finding writes a finding in JSON to the underlying writer. func (h *jsonHandler) Finding(finding *Finding) error { return h.enc.Encode(Message{Finding: finding}) }
govulncheck
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/govulncheck/govulncheck_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package govulncheck_test import ( "testing" "golang.org/x/vuln/internal/test" ) func TestImports(t *testing.T) { test.VerifyImports(t, "golang.org/x/vuln/internal/osv", // allowed to pull in the osv json entries ) }
govulncheck
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/govulncheck/handler.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package govulncheck import ( "encoding/json" "io" "golang.org/x/vuln/internal/osv" ) // Handler handles messages to be presented in a vulnerability scan output // stream. type Handler interface { // Config communicates introductory message to the user. Config(config *Config) error // Progress is called to display a progress message. Progress(progress *Progress) error // OSV is invoked for each osv Entry in the stream. OSV(entry *osv.Entry) error // Finding is called for each vulnerability finding in the stream. Finding(finding *Finding) error } // HandleJSON reads the json from the supplied stream and hands the decoded // output to the handler. func HandleJSON(from io.Reader, to Handler) error { dec := json.NewDecoder(from) for dec.More() { msg := Message{} // decode the next message in the stream if err := dec.Decode(&msg); err != nil { return err } // dispatch the message var err error if msg.Config != nil { err = to.Config(msg.Config) } if msg.Progress != nil { err = to.Progress(msg.Progress) } if msg.OSV != nil { err = to.OSV(msg.OSV) } if msg.Finding != nil { err = to.Finding(msg.Finding) } if err != nil { return err } } return nil }
goversion
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/goversion/asm.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package goversion import ( "encoding/binary" "fmt" "os" ) type matcher [][]uint32 const ( pWild uint32 = 0xff00 pAddr uint32 = 0x10000 pEnd uint32 = 0x20000 pRelAddr uint32 = 0x30000 opMaybe = 1 + iota opMust opDone opAnchor = 0x100 opSub8 = 0x200 opFlags = opAnchor | opSub8 ) var amd64Matcher = matcher{ {opMaybe | opAnchor, // __rt0_amd64_darwin: // JMP __rt0_amd64 0xe9, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xcc, 0xcc, 0xcc, }, {opMaybe, // _rt0_amd64_linux: // lea 0x8(%rsp), %rsi // mov (%rsp), %rdi // lea ADDR(%rip), %rax # main // jmpq *%rax 0x48, 0x8d, 0x74, 0x24, 0x08, 0x48, 0x8b, 0x3c, 0x24, 0x48, 0x8d, 0x05, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xff, 0xe0, }, {opMaybe, // _rt0_amd64_linux: // lea 0x8(%rsp), %rsi // mov (%rsp), %rdi // mov $ADDR, %eax # main // jmpq *%rax 0x48, 0x8d, 0x74, 0x24, 0x08, 0x48, 0x8b, 0x3c, 0x24, 0xb8, pWild | pAddr, pWild, pWild, pWild, 0xff, 0xe0, }, {opMaybe, // __rt0_amd64: // mov (%rsp), %rdi // lea 8(%rsp), %rsi // jmp runtime.rt0_g0 0x48, 0x8b, 0x3c, 0x24, 0x48, 0x8d, 0x74, 0x24, 0x08, 0xe9, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xcc, 0xcc, }, {opMaybe, // _start (toward end) // lea __libc_csu_fini(%rip), %r8 // lea __libc_csu_init(%rip), %rcx // lea ADDR(%rip), %rdi # main // callq *xxx(%rip) 0x4c, 0x8d, 0x05, pWild, pWild, pWild, pWild, 0x48, 0x8d, 0x0d, pWild, pWild, pWild, pWild, 0x48, 0x8d, 0x3d, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xff, 0x15, }, {opMaybe, // _start (toward end) // push %rsp (1) // mov $__libc_csu_fini, %r8 (7) // mov $__libc_csu_init, %rcx (7) // mov $ADDR, %rdi # main (7) // callq *xxx(%rip) 0x54, 0x49, 0xc7, 0xc0, pWild, pWild, pWild, pWild, 0x48, 0xc7, 0xc1, pWild, pWild, pWild, pWild, 0x48, 0xc7, 0xc7, pAddr | pWild, pWild, pWild, pWild, }, {opMaybe | opAnchor, // main: // lea ADDR(%rip), %rax # rt0_go // jmpq *%rax 0x48, 0x8d, 0x05, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xff, 0xe0, }, {opMaybe | opAnchor, // main: // mov $ADDR, %eax // jmpq *%rax 0xb8, pWild | pAddr, pWild, pWild, pWild, 0xff, 0xe0, }, {opMaybe | opAnchor, // main: // JMP runtime.rt0_go(SB) 0xe9, pWild | pAddr, pWild, pWild, pWild | pEnd, 0xcc, 0xcc, 0xcc, }, {opMust | opAnchor, // rt0_go: // mov %rdi, %rax // mov %rsi, %rbx // sub %0x27, %rsp // and $0xfffffffffffffff0,%rsp // mov %rax,0x10(%rsp) // mov %rbx,0x18(%rsp) 0x48, 0x89, 0xf8, 0x48, 0x89, 0xf3, 0x48, 0x83, 0xec, 0x27, 0x48, 0x83, 0xe4, 0xf0, 0x48, 0x89, 0x44, 0x24, 0x10, 0x48, 0x89, 0x5c, 0x24, 0x18, }, {opMust, // later in rt0_go: // mov %eax, (%rsp) // mov 0x18(%rsp), %rax // mov %rax, 0x8(%rsp) // callq runtime.args // callq runtime.osinit // callq runtime.schedinit (ADDR) 0x89, 0x04, 0x24, 0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x89, 0x44, 0x24, 0x08, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild, pWild, pWild, pWild, }, {opMaybe, // later in rt0_go: // mov %eax, (%rsp) // mov 0x18(%rsp), %rax // mov %rax, 0x8(%rsp) // callq runtime.args // callq runtime.osinit // callq runtime.schedinit (ADDR) // lea other(%rip), %rdi 0x89, 0x04, 0x24, 0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x89, 0x44, 0x24, 0x08, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild | pAddr, pWild, pWild, pWild | pEnd, 0x48, 0x8d, 0x05, }, {opMaybe, // later in rt0_go: // mov %eax, (%rsp) // mov 0x18(%rsp), %rax // mov %rax, 0x8(%rsp) // callq runtime.args // callq runtime.osinit // callq runtime.hashinit // callq runtime.schedinit (ADDR) // pushq $main.main 0x89, 0x04, 0x24, 0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x89, 0x44, 0x24, 0x08, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild, pWild, pWild, pWild, 0xe8, pWild | pAddr, pWild, pWild, pWild | pEnd, 0x68, }, {opDone | opSub8, // schedinit (toward end) // mov ADDR(%rip), %rax // test %rax, %rax // jne <short> // movq $0x7, ADDR(%rip) // 0x48, 0x8b, 0x05, pWild, pWild, pWild, pWild, 0x48, 0x85, 0xc0, 0x75, pWild, 0x48, 0xc7, 0x05, pWild | pAddr, pWild, pWild, pWild, 0x07, 0x00, 0x00, 0x00 | pEnd, }, {opDone | opSub8, // schedinit (toward end) // mov ADDR(%rip), %rbx // cmp $0x0, %rbx // jne <short> // lea "unknown"(%rip), %rbx // mov %rbx, ADDR(%rip) // movq $7, (ADDR+8)(%rip) 0x48, 0x8b, 0x1d, pWild, pWild, pWild, pWild, 0x48, 0x83, 0xfb, 0x00, 0x75, pWild, 0x48, 0x8d, 0x1d, pWild, pWild, pWild, pWild, 0x48, 0x89, 0x1d, pWild, pWild, pWild, pWild, 0x48, 0xc7, 0x05, pWild | pAddr, pWild, pWild, pWild, 0x07, 0x00, 0x00, 0x00 | pEnd, }, {opDone, // schedinit (toward end) // cmpq $0x0, ADDR(%rip) // jne <short> // lea "unknown"(%rip), %rax // mov %rax, ADDR(%rip) // lea ADDR(%rip), %rax // movq $7, 8(%rax) 0x48, 0x83, 0x3d, pWild | pAddr, pWild, pWild, pWild, 0x00, 0x75, pWild, 0x48, 0x8d, 0x05, pWild, pWild, pWild, pWild, 0x48, 0x89, 0x05, pWild, pWild, pWild, pWild, 0x48, 0x8d, 0x05, pWild | pAddr, pWild, pWild, pWild | pEnd, 0x48, 0xc7, 0x40, 0x08, 0x07, 0x00, 0x00, 0x00, }, {opDone, // schedinit (toward end) // cmpq $0x0, ADDR(%rip) // jne <short> // movq $0x7, ADDR(%rip) 0x48, 0x83, 0x3d, pWild | pAddr, pWild, pWild, pWild, 0x00, 0x75, pWild, 0x48, 0xc7, 0x05 | pEnd, pWild | pAddr, pWild, pWild, pWild, 0x07, 0x00, 0x00, 0x00, }, {opDone, // test %eax, %eax // jne <later> // lea "unknown"(RIP), %rax // mov %rax, ADDR(%rip) 0x48, 0x85, 0xc0, 0x75, pWild, 0x48, 0x8d, 0x05, pWild, pWild, pWild, pWild, 0x48, 0x89, 0x05, pWild | pAddr, pWild, pWild, pWild | pEnd, }, {opDone, // schedinit (toward end) // mov ADDR(%rip), %rcx // test %rcx, %rcx // jne <short> // movq $0x7, ADDR(%rip) // 0x48, 0x8b, 0x0d, pWild, pWild, pWild, pWild, 0x48, 0x85, 0xc9, 0x75, pWild, 0x48, 0xc7, 0x05 | pEnd, pWild | pAddr, pWild, pWild, pWild, 0x07, 0x00, 0x00, 0x00, }, } var DebugMatch bool func (m matcher) match(f exe, addr uint64) (uint64, bool) { data, err := f.ReadData(addr, 512) if DebugMatch { fmt.Fprintf(os.Stderr, "data @%#x: %x\n", addr, data[:16]) } if err != nil { if DebugMatch { fmt.Fprintf(os.Stderr, "match: %v\n", err) } return 0, false } if DebugMatch { fmt.Fprintf(os.Stderr, "data: %x\n", data[:32]) } Matchers: for pc, p := range m { op := p[0] p = p[1:] Search: for i := 0; i <= len(data)-len(p); i++ { a := -1 e := -1 if i > 0 && op&opAnchor != 0 { break } for j := 0; j < len(p); j++ { b := byte(p[j]) m := byte(p[j] >> 8) if data[i+j]&^m != b { continue Search } if p[j]&pAddr != 0 { a = j } if p[j]&pEnd != 0 { e = j + 1 } } // matched if DebugMatch { fmt.Fprintf(os.Stderr, "match (%d) %#x+%d %x %x\n", pc, addr, i, p, data[i:i+len(p)]) } if a != -1 { val := uint64(int32(binary.LittleEndian.Uint32(data[i+a:]))) if e == -1 { addr = val } else { addr += uint64(i+e) + val } if op&opSub8 != 0 { addr -= 8 } } if op&^opFlags == opDone { if DebugMatch { fmt.Fprintf(os.Stderr, "done %x\n", addr) } return addr, true } if a != -1 { // changed addr, so reload data, err = f.ReadData(addr, 512) if err != nil { return 0, false } if DebugMatch { fmt.Fprintf(os.Stderr, "reload @%#x: %x\n", addr, data[:32]) } } continue Matchers } // not matched if DebugMatch { fmt.Fprintf(os.Stderr, "no match (%d) %#x %x %x\n", pc, addr, p, data[:32]) } if op&^opFlags == opMust { return 0, false } } // ran off end of matcher return 0, false } func readBuildVersionX86Asm(f exe) (isGo bool, buildVersion string) { entry := f.Entry() if entry == 0 { if DebugMatch { fmt.Fprintf(os.Stderr, "missing entry!\n") } return } addr, ok := amd64Matcher.match(f, entry) if !ok { return } v, err := readBuildVersion(f, addr, 16) if err != nil { return } return true, v }
goversion
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/goversion/exe.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package goversion import ( "bytes" "debug/elf" "debug/macho" "debug/pe" "encoding/binary" "fmt" "io" "os" ) type sym struct { Name string Addr uint64 Size uint64 } type exe interface { AddrSize() int // bytes ReadData(addr, size uint64) ([]byte, error) Symbols() ([]sym, error) SectionNames() []string Close() error ByteOrder() binary.ByteOrder Entry() uint64 TextRange() (uint64, uint64) RODataRange() (uint64, uint64) } func openExe(file string) (exe, error) { f, err := os.Open(file) if err != nil { return nil, err } data := make([]byte, 16) if _, err := io.ReadFull(f, data); err != nil { return nil, err } f.Seek(0, 0) if bytes.HasPrefix(data, []byte("\x7FELF")) { e, err := elf.NewFile(f) if err != nil { f.Close() return nil, err } return &elfExe{f, e}, nil } if bytes.HasPrefix(data, []byte("MZ")) { e, err := pe.NewFile(f) if err != nil { f.Close() return nil, err } return &peExe{f, e}, nil } if bytes.HasPrefix(data, []byte("\xFE\xED\xFA")) || bytes.HasPrefix(data[1:], []byte("\xFA\xED\xFE")) { e, err := macho.NewFile(f) if err != nil { f.Close() return nil, err } return &machoExe{f, e}, nil } return nil, fmt.Errorf("unrecognized executable format") } type elfExe struct { os *os.File f *elf.File } func (x *elfExe) AddrSize() int { return 0 } func (x *elfExe) ByteOrder() binary.ByteOrder { return x.f.ByteOrder } func (x *elfExe) Close() error { return x.os.Close() } func (x *elfExe) Entry() uint64 { return x.f.Entry } func (x *elfExe) ReadData(addr, size uint64) ([]byte, error) { for _, prog := range x.f.Progs { // The following line was commented from the original code. //fmt.Printf("%#x %#x %#x\n", addr, prog.Vaddr, prog.Vaddr+prog.Filesz) if prog.Vaddr <= addr && addr <= prog.Vaddr+prog.Filesz-1 { n := prog.Vaddr + prog.Filesz - addr if n > size { n = size } data := make([]byte, n) _, err := prog.ReadAt(data, int64(addr-prog.Vaddr)) if err != nil { return nil, err } return data, nil } } return nil, fmt.Errorf("address not mapped") } func (x *elfExe) Symbols() ([]sym, error) { syms, err := x.f.Symbols() if err != nil { return nil, err } var out []sym for _, s := range syms { out = append(out, sym{s.Name, s.Value, s.Size}) } return out, nil } func (x *elfExe) SectionNames() []string { var names []string for _, sect := range x.f.Sections { names = append(names, sect.Name) } return names } func (x *elfExe) TextRange() (uint64, uint64) { for _, p := range x.f.Progs { if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 { return p.Vaddr, p.Vaddr + p.Filesz } } return 0, 0 } func (x *elfExe) RODataRange() (uint64, uint64) { for _, p := range x.f.Progs { if p.Type == elf.PT_LOAD && p.Flags&(elf.PF_R|elf.PF_W|elf.PF_X) == elf.PF_R { return p.Vaddr, p.Vaddr + p.Filesz } } for _, p := range x.f.Progs { if p.Type == elf.PT_LOAD && p.Flags&(elf.PF_R|elf.PF_W|elf.PF_X) == (elf.PF_R|elf.PF_X) { return p.Vaddr, p.Vaddr + p.Filesz } } return 0, 0 } type peExe struct { os *os.File f *pe.File } func (x *peExe) imageBase() uint64 { switch oh := x.f.OptionalHeader.(type) { case *pe.OptionalHeader32: return uint64(oh.ImageBase) case *pe.OptionalHeader64: return oh.ImageBase } return 0 } func (x *peExe) AddrSize() int { if x.f.Machine == pe.IMAGE_FILE_MACHINE_AMD64 { return 8 } return 4 } func (x *peExe) ByteOrder() binary.ByteOrder { return binary.LittleEndian } func (x *peExe) Close() error { return x.os.Close() } func (x *peExe) Entry() uint64 { switch oh := x.f.OptionalHeader.(type) { case *pe.OptionalHeader32: return uint64(oh.ImageBase + oh.AddressOfEntryPoint) case *pe.OptionalHeader64: return oh.ImageBase + uint64(oh.AddressOfEntryPoint) } return 0 } func (x *peExe) ReadData(addr, size uint64) ([]byte, error) { addr -= x.imageBase() data := make([]byte, size) for _, sect := range x.f.Sections { if uint64(sect.VirtualAddress) <= addr && addr+size-1 <= uint64(sect.VirtualAddress+sect.Size-1) { _, err := sect.ReadAt(data, int64(addr-uint64(sect.VirtualAddress))) if err != nil { return nil, err } return data, nil } } return nil, fmt.Errorf("address not mapped") } func (x *peExe) Symbols() ([]sym, error) { base := x.imageBase() var out []sym for _, s := range x.f.Symbols { if s.SectionNumber <= 0 || int(s.SectionNumber) > len(x.f.Sections) { continue } sect := x.f.Sections[s.SectionNumber-1] out = append(out, sym{s.Name, uint64(s.Value) + base + uint64(sect.VirtualAddress), 0}) } return out, nil } func (x *peExe) SectionNames() []string { var names []string for _, sect := range x.f.Sections { names = append(names, sect.Name) } return names } func (x *peExe) TextRange() (uint64, uint64) { // Assume text is first non-empty section. for _, sect := range x.f.Sections { if sect.VirtualAddress != 0 && sect.Size != 0 { return uint64(sect.VirtualAddress) + x.imageBase(), uint64(sect.VirtualAddress+sect.Size) + x.imageBase() } } return 0, 0 } func (x *peExe) RODataRange() (uint64, uint64) { return x.TextRange() } type machoExe struct { os *os.File f *macho.File } func (x *machoExe) AddrSize() int { if x.f.Cpu&0x01000000 != 0 { return 8 } return 4 } func (x *machoExe) ByteOrder() binary.ByteOrder { return x.f.ByteOrder } func (x *machoExe) Close() error { return x.os.Close() } func (x *machoExe) Entry() uint64 { for _, load := range x.f.Loads { b, ok := load.(macho.LoadBytes) if !ok { continue } // TODO: Other thread states. bo := x.f.ByteOrder const x86_THREAD_STATE64 = 4 cmd, siz := macho.LoadCmd(bo.Uint32(b[0:4])), bo.Uint32(b[4:8]) if cmd == macho.LoadCmdUnixThread && siz == 184 && bo.Uint32(b[8:12]) == x86_THREAD_STATE64 { return bo.Uint64(b[144:]) } } return 0 } func (x *machoExe) ReadData(addr, size uint64) ([]byte, error) { data := make([]byte, size) for _, load := range x.f.Loads { seg, ok := load.(*macho.Segment) if !ok { continue } if seg.Addr <= addr && addr+size-1 <= seg.Addr+seg.Filesz-1 { if seg.Name == "__PAGEZERO" { continue } _, err := seg.ReadAt(data, int64(addr-seg.Addr)) if err != nil { return nil, err } return data, nil } } return nil, fmt.Errorf("address not mapped") } func (x *machoExe) Symbols() ([]sym, error) { var out []sym for _, s := range x.f.Symtab.Syms { out = append(out, sym{s.Name, s.Value, 0}) } return out, nil } func (x *machoExe) SectionNames() []string { var names []string for _, sect := range x.f.Sections { names = append(names, sect.Name) } return names } func (x *machoExe) TextRange() (uint64, uint64) { // Assume text is first non-empty segment. for _, load := range x.f.Loads { seg, ok := load.(*macho.Segment) if ok && seg.Name != "__PAGEZERO" && seg.Addr != 0 && seg.Filesz != 0 { return seg.Addr, seg.Addr + seg.Filesz } } return 0, 0 } func (x *machoExe) RODataRange() (uint64, uint64) { return x.TextRange() }
goversion
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/goversion/read.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package goversion reports the Go version used to build program executables. // // This is a copy of rsc.io/goversion/version. We renamed the package to goversion // to differentiate between version package in standard library that we also use. package goversion import ( "bytes" "encoding/hex" "errors" "fmt" "regexp" "strings" ) // Version is the information reported by ReadExe. type Version struct { Release string // Go version (runtime.Version in the program) ModuleInfo string // program's module information BoringCrypto bool // program uses BoringCrypto StandardCrypto bool // program uses standard crypto (replaced by BoringCrypto) FIPSOnly bool // program imports "crypto/tls/fipsonly" } // ReadExe reports information about the Go version used to build // the program executable named by file. func ReadExe(file string) (Version, error) { var v Version f, err := openExe(file) if err != nil { return v, err } defer f.Close() isGo := false for _, name := range f.SectionNames() { if name == ".note.go.buildid" { isGo = true } } syms, symsErr := f.Symbols() isGccgo := false for _, sym := range syms { name := sym.Name if name == "runtime.main" || name == "main.main" { isGo = true } if strings.HasPrefix(name, "runtime.") && strings.HasSuffix(name, "$descriptor") { isGccgo = true } if name == "runtime.buildVersion" { isGo = true release, err := readBuildVersion(f, sym.Addr, sym.Size) if err != nil { return v, err } v.Release = release } // Note: Using strings.HasPrefix because Go 1.17+ adds ".abi0" to many of these symbols. if strings.Contains(name, "_Cfunc__goboringcrypto_") || strings.HasPrefix(name, "crypto/internal/boring/sig.BoringCrypto") { v.BoringCrypto = true } if strings.HasPrefix(name, "crypto/internal/boring/sig.FIPSOnly") { v.FIPSOnly = true } for _, re := range standardCryptoNames { if re.MatchString(name) { v.StandardCrypto = true } } if strings.HasPrefix(name, "crypto/internal/boring/sig.StandardCrypto") { v.StandardCrypto = true } } if DebugMatch { v.Release = "" } if err := findModuleInfo(&v, f); err != nil { return v, err } if v.Release == "" { g, release := readBuildVersionX86Asm(f) if g { isGo = true v.Release = release if err := findCryptoSigs(&v, f); err != nil { return v, err } } } if isGccgo && v.Release == "" { isGo = true v.Release = "gccgo (version unknown)" } if !isGo && symsErr != nil { return v, symsErr } if !isGo { return v, errors.New("not a Go executable") } if v.Release == "" { v.Release = "unknown Go version" } return v, nil } var re = regexp.MustCompile var standardCryptoNames = []*regexp.Regexp{ re(`^crypto/sha1\.\(\*digest\)`), re(`^crypto/sha256\.\(\*digest\)`), re(`^crypto/rand\.\(\*devReader\)`), re(`^crypto/rsa\.encrypt(\.abi.)?$`), re(`^crypto/rsa\.decrypt(\.abi.)?$`), } func readBuildVersion(f exe, addr, size uint64) (string, error) { if size == 0 { size = uint64(f.AddrSize() * 2) } if size != 8 && size != 16 { return "", fmt.Errorf("invalid size for runtime.buildVersion") } data, err := f.ReadData(addr, size) if err != nil { return "", fmt.Errorf("reading runtime.buildVersion: %v", err) } if size == 8 { addr = uint64(f.ByteOrder().Uint32(data)) size = uint64(f.ByteOrder().Uint32(data[4:])) } else { addr = f.ByteOrder().Uint64(data) size = f.ByteOrder().Uint64(data[8:]) } if size > 1000 { return "", fmt.Errorf("implausible string size %d for runtime.buildVersion", size) } data, err = f.ReadData(addr, size) if err != nil { return "", fmt.Errorf("reading runtime.buildVersion string data: %v", err) } return string(data), nil } // Code signatures that indicate BoringCrypto or crypto/internal/fipsonly. // These are not byte literals in order to avoid the actual // byte signatures appearing in the goversion binary, // because on some systems you can't tell rodata from text. var ( sigBoringCrypto, _ = hex.DecodeString("EB1DF448F44BF4B332F52813A3B450D441CC2485F001454E92101B1D2F1950C3") sigStandardCrypto, _ = hex.DecodeString("EB1DF448F44BF4BAEE4DFA9851CA56A91145E83E99C59CF911CB8E80DAF12FC3") sigFIPSOnly, _ = hex.DecodeString("EB1DF448F44BF4363CB9CE9D68047D31F28D325D5CA5873F5D80CAF6D6151BC3") ) func findCryptoSigs(v *Version, f exe) error { const maxSigLen = 1 << 10 start, end := f.TextRange() for addr := start; addr < end; { size := uint64(1 << 20) if end-addr < size { size = end - addr } data, err := f.ReadData(addr, size) if err != nil { return fmt.Errorf("reading text: %v", err) } if haveSig(data, sigBoringCrypto) { v.BoringCrypto = true } if haveSig(data, sigFIPSOnly) { v.FIPSOnly = true } if haveSig(data, sigStandardCrypto) { v.StandardCrypto = true } if addr+size < end { size -= maxSigLen } addr += size } return nil } func haveSig(data, sig []byte) bool { const align = 16 for { i := bytes.Index(data, sig) if i < 0 { return false } if i&(align-1) == 0 { return true } // Found unaligned match; unexpected but // skip to next aligned boundary and keep searching. data = data[(i+align-1)&^(align-1):] } } func findModuleInfo(v *Version, f exe) error { const maxModInfo = 128 << 10 start, end := f.RODataRange() for addr := start; addr < end; { size := uint64(4 << 20) if end-addr < size { size = end - addr } data, err := f.ReadData(addr, size) if err != nil { return fmt.Errorf("reading text: %v", err) } if haveModuleInfo(data, v) { return nil } if addr+size < end { size -= maxModInfo } addr += size } return nil } var ( infoStart, _ = hex.DecodeString("3077af0c9274080241e1c107e6d618e6") infoEnd, _ = hex.DecodeString("f932433186182072008242104116d8f2") ) func haveModuleInfo(data []byte, v *Version) bool { i := bytes.Index(data, infoStart) if i < 0 { return false } j := bytes.Index(data[i:], infoEnd) if j < 0 { return false } v.ModuleInfo = string(data[i+len(infoStart) : i+j]) return true }
derrors
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/derrors/derrors.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package derrors defines internal error values to categorize the different // types error semantics supported by x/vuln. package derrors import ( "fmt" ) // Wrap adds context to the error and allows // unwrapping the result to recover the original error. // // Example: // // defer derrors.Wrap(&err, "copy(%s, %s)", dst, src) func Wrap(errp *error, format string, args ...interface{}) { if *errp != nil { *errp = fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), *errp) } }
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/pclntab_test.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gosym import ( "bytes" "compress/gzip" "debug/elf" "io" "os" "runtime" "strings" "testing" "golang.org/x/vuln/internal/test" "golang.org/x/vuln/internal/testenv" ) func dotest(t *testing.T) (binaryName string, cleanup func()) { testenv.NeedsGoBuild(t) // For now, only works on amd64 platforms. if runtime.GOARCH != "amd64" { t.Skipf("skipping on non-AMD64 system %s", runtime.GOARCH) } // This test builds a Linux/AMD64 binary. Skipping in short mode if cross compiling. if runtime.GOOS != "linux" && testing.Short() { t.Skipf("skipping in short mode on non-Linux system %s", runtime.GOARCH) } return test.GoBuild(t, "testdata", "", false, "GOOS", "linux") } // skipIfNotELF skips the test if we are not running on an ELF system. // These tests open and examine the test binary, and use elf.Open to do so. func skipIfNotELF(t *testing.T) { switch runtime.GOOS { case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris", "illumos": // OK. default: t.Skipf("skipping on non-ELF system %s", runtime.GOOS) } } func getTable(t *testing.T) *Table { f, tab := crack(os.Args[0], t) f.Close() return tab } func crack(file string, t *testing.T) (*elf.File, *Table) { // Open self f, err := elf.Open(file) if err != nil { t.Fatal(err) } return parse(file, f, t) } func parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) { s := f.Section(".gosymtab") if s == nil { t.Skip("no .gosymtab section") } symdat, err := s.Data() if err != nil { f.Close() t.Fatalf("reading %s gosymtab: %v", file, err) } pclndat, err := f.Section(".gopclntab").Data() if err != nil { f.Close() t.Fatalf("reading %s gopclntab: %v", file, err) } pcln := NewLineTable(pclndat, f.Section(".text").Addr) tab, err := NewTable(symdat, pcln) if err != nil { f.Close() t.Fatalf("parsing %s gosymtab: %v", file, err) } return f, tab } func TestLineFromAline(t *testing.T) { skipIfNotELF(t) tab := getTable(t) if tab.go12line != nil { // aline's don't exist in the Go 1.2 table. t.Skip("not relevant to Go 1.2 symbol table") } // Find the sym package pkg := tab.LookupFunc("debug/gosym.TestLineFromAline").Obj if pkg == nil { t.Fatalf("nil pkg") } // Walk every absolute line and ensure that we hit every // source line monotonically lastline := make(map[string]int) final := -1 for i := 0; i < 10000; i++ { path, line := pkg.lineFromAline(i) // Check for end of object if path == "" { if final == -1 { final = i - 1 } continue } else if final != -1 { t.Fatalf("reached end of package at absolute line %d, but absolute line %d mapped to %s:%d", final, i, path, line) } // It's okay to see files multiple times (e.g., sys.a) if line == 1 { lastline[path] = 1 continue } // Check that the is the next line in path ll, ok := lastline[path] if !ok { t.Errorf("file %s starts on line %d", path, line) } else if line != ll+1 { t.Fatalf("expected next line of file %s to be %d, got %d", path, ll+1, line) } lastline[path] = line } if final == -1 { t.Errorf("never reached end of object") } } func TestLineAline(t *testing.T) { skipIfNotELF(t) tab := getTable(t) if tab.go12line != nil { // aline's don't exist in the Go 1.2 table. t.Skip("not relevant to Go 1.2 symbol table") } for _, o := range tab.Files { // A source file can appear multiple times in a // object. alineFromLine will always return alines in // the first file, so track which lines we've seen. found := make(map[string]int) for i := 0; i < 1000; i++ { path, line := o.lineFromAline(i) if path == "" { break } // cgo files are full of 'Z' symbols, which we don't handle if len(path) > 4 && path[len(path)-4:] == ".cgo" { continue } if minline, ok := found[path]; path != "" && ok { if minline >= line { // We've already covered this file continue } } found[path] = line a, err := o.alineFromLine(path, line) if err != nil { t.Errorf("absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s", i, o.Paths[0].Name, path, line, err) } else if a != i { t.Errorf("absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\n", i, o.Paths[0].Name, path, line, a) } } } } func TestPCLine(t *testing.T) { pclinetestBinary, cleanup := dotest(t) defer cleanup() f, tab := crack(pclinetestBinary, t) defer f.Close() text := f.Section(".text") textdat, err := text.Data() if err != nil { t.Fatalf("reading .text: %v", err) } // Test PCToLine sym := tab.LookupFunc("main.linefrompc") wantLine := 0 for pc := sym.Entry; pc < sym.End; pc++ { off := pc - text.Addr // TODO(rsc): should not need off; bug in 8g if textdat[off] == 255 { break } wantLine += int(textdat[off]) t.Logf("off is %d %#x (max %d)", off, textdat[off], sym.End-pc) file, line, fn := tab.PCToLine(pc) if fn == nil { t.Errorf("failed to get line of PC %#x", pc) } else if !strings.HasSuffix(file, "pclinetest.s") || line != wantLine || fn != sym { t.Errorf("PCToLine(%#x) = %s:%d (%s), want %s:%d (%s)", pc, file, line, fn.Name, "pclinetest.s", wantLine, sym.Name) } } // Test LineToPC sym = tab.LookupFunc("main.pcfromline") lookupline := -1 wantLine = 0 off := uint64(0) // TODO(rsc): should not need off; bug in 8g for pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) { file, line, fn := tab.PCToLine(pc) off = pc - text.Addr if textdat[off] == 255 { break } wantLine += int(textdat[off]) if line != wantLine { t.Errorf("expected line %d at PC %#x in pcfromline, got %d", wantLine, pc, line) off = pc + 1 - text.Addr continue } if lookupline == -1 { lookupline = line } for ; lookupline <= line; lookupline++ { pc2, fn2, err := tab.LineToPC(file, lookupline) if lookupline != line { // Should be nothing on this line if err == nil { t.Errorf("expected no PC at line %d, got %#x (%s)", lookupline, pc2, fn2.Name) } } else if err != nil { t.Errorf("failed to get PC of line %d: %s", lookupline, err) } else if pc != pc2 { t.Errorf("expected PC %#x (%s) at line %d, got PC %#x (%s)", pc, fn.Name, line, pc2, fn2.Name) } } off = pc + 1 - text.Addr } } func TestSymVersion(t *testing.T) { skipIfNotELF(t) table := getTable(t) if table.go12line == nil { t.Skip("not relevant to Go 1.2+ symbol table") } for _, fn := range table.Funcs { if fn.goVersion == verUnknown { t.Fatalf("unexpected symbol version: %v", fn) } } } // read115Executable returns a hello world executable compiled by Go 1.15. // // The file was compiled in /tmp/hello.go: // // package main // // func main() { // println("hello") // } func read115Executable(tb testing.TB) []byte { zippedDat, err := os.ReadFile("testdata/pcln115.gz") if err != nil { tb.Fatal(err) } var gzReader *gzip.Reader gzReader, err = gzip.NewReader(bytes.NewBuffer(zippedDat)) if err != nil { tb.Fatal(err) } var dat []byte dat, err = io.ReadAll(gzReader) if err != nil { tb.Fatal(err) } return dat } // Test that we can parse a pclntab from 1.15. func Test115PclnParsing(t *testing.T) { dat := read115Executable(t) const textStart = 0x1001000 pcln := NewLineTable(dat, textStart) tab, err := NewTable(nil, pcln) if err != nil { t.Fatal(err) } var f *Func var pc uint64 pc, f, err = tab.LineToPC("/tmp/hello.go", 3) if err != nil { t.Fatal(err) } if pcln.version != ver12 { t.Fatal("Expected pcln to parse as an older version") } if pc != 0x105c280 { t.Fatalf("expect pc = 0x105c280, got 0x%x", pc) } if f.Name != "main.main" { t.Fatalf("expected to parse name as main.main, got %v", f.Name) } } var ( sinkLineTable *LineTable sinkTable *Table ) func Benchmark115(b *testing.B) { dat := read115Executable(b) const textStart = 0x1001000 b.Run("NewLineTable", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { sinkLineTable = NewLineTable(dat, textStart) } }) pcln := NewLineTable(dat, textStart) b.Run("NewTable", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { var err error sinkTable, err = NewTable(nil, pcln) if err != nil { b.Fatal(err) } } }) tab, err := NewTable(nil, pcln) if err != nil { b.Fatal(err) } b.Run("LineToPC", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { var f *Func var pc uint64 pc, f, err = tab.LineToPC("/tmp/hello.go", 3) if err != nil { b.Fatal(err) } if pcln.version != ver12 { b.Fatalf("want version=%d, got %d", ver12, pcln.version) } if pc != 0x105c280 { b.Fatalf("want pc=0x105c280, got 0x%x", pc) } if f.Name != "main.main" { b.Fatalf("want name=main.main, got %q", f.Name) } } }) b.Run("PCToLine", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { file, line, fn := tab.PCToLine(0x105c280) if file != "/tmp/hello.go" { b.Fatalf("want name=/tmp/hello.go, got %q", file) } if line != 3 { b.Fatalf("want line=3, got %d", line) } if fn.Name != "main.main" { b.Fatalf("want name=main.main, got %q", fn.Name) } } }) }
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/symtab.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package gosym implements access to the Go symbol // and line number tables embedded in Go binaries generated // by the gc compilers. package gosym import ( "bytes" "encoding/binary" "fmt" "strconv" "strings" ) /* * Symbols */ // A Sym represents a single symbol table entry. type Sym struct { Value uint64 Type byte Name string GoType uint64 // If this symbol is a function symbol, the corresponding Func Func *Func goVersion version } // Static reports whether this symbol is static (not visible outside its file). func (s *Sym) Static() bool { return s.Type >= 'a' } // nameWithoutInst returns s.Name if s.Name has no brackets (does not reference an // instantiated type, function, or method). If s.Name contains brackets, then it // returns s.Name with all the contents between (and including) the outermost left // and right bracket removed. This is useful to ignore any extra slashes or dots // inside the brackets from the string searches below, where needed. func (s *Sym) nameWithoutInst() string { start := strings.Index(s.Name, "[") if start < 0 { return s.Name } end := strings.LastIndex(s.Name, "]") if end < 0 { // Malformed name, should contain closing bracket too. return s.Name } return s.Name[0:start] + s.Name[end+1:] } // PackageName returns the package part of the symbol name, // or the empty string if there is none. func (s *Sym) PackageName() string { name := s.nameWithoutInst() // Since go1.20, a prefix of "type:" and "go:" is a compiler-generated symbol, // they do not belong to any package. // // See cmd/compile/internal/base/link.go:ReservedImports variable. if s.goVersion >= ver120 && (strings.HasPrefix(name, "go:") || strings.HasPrefix(name, "type:")) { return "" } // For go1.18 and below, the prefix are "type." and "go." instead. if s.goVersion <= ver118 && (strings.HasPrefix(name, "go.") || strings.HasPrefix(name, "type.")) { return "" } pathend := strings.LastIndex(name, "/") if pathend < 0 { pathend = 0 } if i := strings.Index(name[pathend:], "."); i != -1 { return name[:pathend+i] } return "" } // ReceiverName returns the receiver type name of this symbol, // or the empty string if there is none. A receiver name is only detected in // the case that s.Name is fully-specified with a package name. func (s *Sym) ReceiverName() string { name := s.nameWithoutInst() // If we find a slash in name, it should precede any bracketed expression // that was removed, so pathend will apply correctly to name and s.Name. pathend := strings.LastIndex(name, "/") if pathend < 0 { pathend = 0 } // Find the first dot after pathend (or from the beginning, if there was // no slash in name). l := strings.Index(name[pathend:], ".") // Find the last dot after pathend (or the beginning). r := strings.LastIndex(name[pathend:], ".") if l == -1 || r == -1 || l == r { // There is no receiver if we didn't find two distinct dots after pathend. return "" } // Given there is a trailing '.' that is in name, find it now in s.Name. // pathend+l should apply to s.Name, because it should be the dot in the // package name. r = strings.LastIndex(s.Name[pathend:], ".") return s.Name[pathend+l+1 : pathend+r] } // BaseName returns the symbol name without the package or receiver name. func (s *Sym) BaseName() string { name := s.nameWithoutInst() if i := strings.LastIndex(name, "."); i != -1 { if s.Name != name { brack := strings.Index(s.Name, "[") if i > brack { // BaseName is a method name after the brackets, so // recalculate for s.Name. Otherwise, i applies // correctly to s.Name, since it is before the // brackets. i = strings.LastIndex(s.Name, ".") } } return s.Name[i+1:] } return s.Name } // A Func collects information about a single function. type Func struct { Entry uint64 *Sym End uint64 Params []*Sym // nil for Go 1.3 and later binaries Locals []*Sym // nil for Go 1.3 and later binaries FrameSize int LineTable *LineTable Obj *Obj // Addition: extra data to support inlining. inlTree } // An Obj represents a collection of functions in a symbol table. // // The exact method of division of a binary into separate Objs is an internal detail // of the symbol table format. // // In early versions of Go each source file became a different Obj. // // In Go 1 and Go 1.1, each package produced one Obj for all Go sources // and one Obj per C source file. // // In Go 1.2, there is a single Obj for the entire program. type Obj struct { // Funcs is a list of functions in the Obj. Funcs []Func // In Go 1.1 and earlier, Paths is a list of symbols corresponding // to the source file names that produced the Obj. // In Go 1.2, Paths is nil. // Use the keys of Table.Files to obtain a list of source files. Paths []Sym // meta } /* * Symbol tables */ // Table represents a Go symbol table. It stores all of the // symbols decoded from the program and provides methods to translate // between symbols, names, and addresses. type Table struct { Syms []Sym // nil for Go 1.3 and later binaries Funcs []Func Files map[string]*Obj // for Go 1.2 and later all files map to one Obj Objs []Obj // for Go 1.2 and later only one Obj in slice go12line *LineTable // Go 1.2 line number table } type sym struct { value uint64 gotype uint64 typ byte name []byte } var ( littleEndianSymtab = []byte{0xFD, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00} bigEndianSymtab = []byte{0xFF, 0xFF, 0xFF, 0xFD, 0x00, 0x00, 0x00} oldLittleEndianSymtab = []byte{0xFE, 0xFF, 0xFF, 0xFF, 0x00, 0x00} ) func walksymtab(data []byte, fn func(sym) error) error { if len(data) == 0 { // missing symtab is okay return nil } var order binary.ByteOrder = binary.BigEndian newTable := false switch { case bytes.HasPrefix(data, oldLittleEndianSymtab): // Same as Go 1.0, but little endian. // Format was used during interim development between Go 1.0 and Go 1.1. // Should not be widespread, but easy to support. data = data[6:] order = binary.LittleEndian case bytes.HasPrefix(data, bigEndianSymtab): newTable = true case bytes.HasPrefix(data, littleEndianSymtab): newTable = true order = binary.LittleEndian } var ptrsz int if newTable { if len(data) < 8 { return &DecodingError{len(data), "unexpected EOF", nil} } ptrsz = int(data[7]) if ptrsz != 4 && ptrsz != 8 { return &DecodingError{7, "invalid pointer size", ptrsz} } data = data[8:] } var s sym p := data for len(p) >= 4 { var typ byte if newTable { // Symbol type, value, Go type. typ = p[0] & 0x3F wideValue := p[0]&0x40 != 0 goType := p[0]&0x80 != 0 if typ < 26 { typ += 'A' } else { typ += 'a' - 26 } s.typ = typ p = p[1:] if wideValue { if len(p) < ptrsz { return &DecodingError{len(data), "unexpected EOF", nil} } // fixed-width value if ptrsz == 8 { s.value = order.Uint64(p[0:8]) p = p[8:] } else { s.value = uint64(order.Uint32(p[0:4])) p = p[4:] } } else { // varint value s.value = 0 shift := uint(0) for len(p) > 0 && p[0]&0x80 != 0 { s.value |= uint64(p[0]&0x7F) << shift shift += 7 p = p[1:] } if len(p) == 0 { return &DecodingError{len(data), "unexpected EOF", nil} } s.value |= uint64(p[0]) << shift p = p[1:] } if goType { if len(p) < ptrsz { return &DecodingError{len(data), "unexpected EOF", nil} } // fixed-width go type if ptrsz == 8 { s.gotype = order.Uint64(p[0:8]) p = p[8:] } else { s.gotype = uint64(order.Uint32(p[0:4])) p = p[4:] } } } else { // Value, symbol type. s.value = uint64(order.Uint32(p[0:4])) if len(p) < 5 { return &DecodingError{len(data), "unexpected EOF", nil} } typ = p[4] if typ&0x80 == 0 { return &DecodingError{len(data) - len(p) + 4, "bad symbol type", typ} } typ &^= 0x80 s.typ = typ p = p[5:] } // Name. var i int var nnul int for i = 0; i < len(p); i++ { if p[i] == 0 { nnul = 1 break } } switch typ { case 'z', 'Z': p = p[i+nnul:] for i = 0; i+2 <= len(p); i += 2 { if p[i] == 0 && p[i+1] == 0 { nnul = 2 break } } } if len(p) < i+nnul { return &DecodingError{len(data), "unexpected EOF", nil} } s.name = p[0:i] i += nnul p = p[i:] if !newTable { if len(p) < 4 { return &DecodingError{len(data), "unexpected EOF", nil} } // Go type. s.gotype = uint64(order.Uint32(p[:4])) p = p[4:] } _ = fn(s) } return nil } // NewTable decodes the Go symbol table (the ".gosymtab" section in ELF), // returning an in-memory representation. // Starting with Go 1.3, the Go symbol table no longer includes symbol data. func NewTable(symtab []byte, pcln *LineTable) (*Table, error) { var n int err := walksymtab(symtab, func(s sym) error { n++ return nil }) if err != nil { return nil, err } var t Table if pcln.isGo12() { t.go12line = pcln } fname := make(map[uint16]string) t.Syms = make([]Sym, 0, n) nf := 0 nz := 0 lasttyp := uint8(0) err = walksymtab(symtab, func(s sym) error { n := len(t.Syms) t.Syms = t.Syms[0 : n+1] ts := &t.Syms[n] ts.Type = s.typ ts.Value = s.value ts.GoType = s.gotype ts.goVersion = pcln.version switch s.typ { default: // rewrite name to use . instead of · (c2 b7) w := 0 b := s.name for i := 0; i < len(b); i++ { if b[i] == 0xc2 && i+1 < len(b) && b[i+1] == 0xb7 { i++ b[i] = '.' } b[w] = b[i] w++ } ts.Name = string(s.name[0:w]) case 'z', 'Z': if lasttyp != 'z' && lasttyp != 'Z' { nz++ } for i := 0; i < len(s.name); i += 2 { eltIdx := binary.BigEndian.Uint16(s.name[i : i+2]) elt, ok := fname[eltIdx] if !ok { return &DecodingError{-1, "bad filename code", eltIdx} } if n := len(ts.Name); n > 0 && ts.Name[n-1] != '/' { ts.Name += "/" } ts.Name += elt } } switch s.typ { case 'T', 't', 'L', 'l': nf++ case 'f': fname[uint16(s.value)] = ts.Name } lasttyp = s.typ return nil }) if err != nil { return nil, err } t.Funcs = make([]Func, 0, nf) t.Files = make(map[string]*Obj) var obj *Obj if t.go12line != nil { // Put all functions into one Obj. t.Objs = make([]Obj, 1) obj = &t.Objs[0] t.go12line.go12MapFiles(t.Files, obj) } else { t.Objs = make([]Obj, 0, nz) } // Count text symbols and attach frame sizes, parameters, and // locals to them. Also, find object file boundaries. lastf := 0 for i := 0; i < len(t.Syms); i++ { sym := &t.Syms[i] switch sym.Type { case 'Z', 'z': // path symbol if t.go12line != nil { // Go 1.2 binaries have the file information elsewhere. Ignore. break } // Finish the current object if obj != nil { obj.Funcs = t.Funcs[lastf:] } lastf = len(t.Funcs) // Start new object n := len(t.Objs) t.Objs = t.Objs[0 : n+1] obj = &t.Objs[n] // Count & copy path symbols var end int for end = i + 1; end < len(t.Syms); end++ { if c := t.Syms[end].Type; c != 'Z' && c != 'z' { break } } obj.Paths = t.Syms[i:end] i = end - 1 // loop will i++ // Record file names depth := 0 for j := range obj.Paths { s := &obj.Paths[j] if s.Name == "" { depth-- } else { if depth == 0 { t.Files[s.Name] = obj } depth++ } } case 'T', 't', 'L', 'l': // text symbol if n := len(t.Funcs); n > 0 { t.Funcs[n-1].End = sym.Value } if sym.Name == "runtime.etext" || sym.Name == "etext" { continue } // Count parameter and local (auto) syms var np, na int var end int countloop: for end = i + 1; end < len(t.Syms); end++ { switch t.Syms[end].Type { case 'T', 't', 'L', 'l', 'Z', 'z': break countloop case 'p': np++ case 'a': na++ } } // Fill in the function symbol n := len(t.Funcs) t.Funcs = t.Funcs[0 : n+1] fn := &t.Funcs[n] sym.Func = fn fn.Params = make([]*Sym, 0, np) fn.Locals = make([]*Sym, 0, na) fn.Sym = sym fn.Entry = sym.Value fn.Obj = obj if t.go12line != nil { // All functions share the same line table. // It knows how to narrow down to a specific // function quickly. fn.LineTable = t.go12line } else if pcln != nil { fn.LineTable = pcln.slice(fn.Entry) pcln = fn.LineTable } for j := i; j < end; j++ { s := &t.Syms[j] switch s.Type { case 'm': fn.FrameSize = int(s.Value) case 'p': n := len(fn.Params) fn.Params = fn.Params[0 : n+1] fn.Params[n] = s case 'a': n := len(fn.Locals) fn.Locals = fn.Locals[0 : n+1] fn.Locals[n] = s } } i = end - 1 // loop will i++ } } if t.go12line != nil && nf == 0 { t.Funcs = t.go12line.go12Funcs() } if obj != nil { obj.Funcs = t.Funcs[lastf:] } return &t, nil } // PCToFunc returns the function containing the program counter pc, // or nil if there is no such function. func (t *Table) PCToFunc(pc uint64) *Func { funcs := t.Funcs for len(funcs) > 0 { m := len(funcs) / 2 fn := &funcs[m] switch { case pc < fn.Entry: funcs = funcs[0:m] case fn.Entry <= pc && pc < fn.End: return fn default: funcs = funcs[m+1:] } } return nil } // PCToLine looks up line number information for a program counter. // If there is no information, it returns fn == nil. func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func) { if fn = t.PCToFunc(pc); fn == nil { return } if t.go12line != nil { file = t.go12line.go12PCToFile(pc) line = t.go12line.go12PCToLine(pc) } else { file, line = fn.Obj.lineFromAline(fn.LineTable.PCToLine(pc)) } return } // LineToPC looks up the first program counter on the given line in // the named file. It returns UnknownPathError or UnknownLineError if // there is an error looking up this line. func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error) { obj, ok := t.Files[file] if !ok { return 0, nil, UnknownFileError(file) } if t.go12line != nil { pc := t.go12line.go12LineToPC(file, line) if pc == 0 { return 0, nil, &UnknownLineError{file, line} } return pc, t.PCToFunc(pc), nil } abs, err := obj.alineFromLine(file, line) if err != nil { return } for i := range obj.Funcs { f := &obj.Funcs[i] pc := f.LineTable.LineToPC(abs, f.End) if pc != 0 { return pc, f, nil } } return 0, nil, &UnknownLineError{file, line} } // LookupSym returns the text, data, or bss symbol with the given name, // or nil if no such symbol is found. func (t *Table) LookupSym(name string) *Sym { // TODO(austin) Maybe make a map for i := range t.Syms { s := &t.Syms[i] switch s.Type { case 'T', 't', 'L', 'l', 'D', 'd', 'B', 'b': if s.Name == name { return s } } } return nil } // LookupFunc returns the text, data, or bss symbol with the given name, // or nil if no such symbol is found. func (t *Table) LookupFunc(name string) *Func { for i := range t.Funcs { f := &t.Funcs[i] if f.Sym.Name == name { return f } } return nil } // SymByAddr returns the text, data, or bss symbol starting at the given address. func (t *Table) SymByAddr(addr uint64) *Sym { for i := range t.Syms { s := &t.Syms[i] switch s.Type { case 'T', 't', 'L', 'l', 'D', 'd', 'B', 'b': if s.Value == addr { return s } } } return nil } /* * Object files */ // This is legacy code for Go 1.1 and earlier, which used the // Plan 9 format for pc-line tables. This code was never quite // correct. It's probably very close, and it's usually correct, but // we never quite found all the corner cases. // // Go 1.2 and later use a simpler format, documented at golang.org/s/go12symtab. func (o *Obj) lineFromAline(aline int) (string, int) { type stackEnt struct { path string start int offset int prev *stackEnt } noPath := &stackEnt{"", 0, 0, nil} tos := noPath pathloop: for _, s := range o.Paths { val := int(s.Value) switch { case val > aline: break pathloop case val == 1: // Start a new stack tos = &stackEnt{s.Name, val, 0, noPath} case s.Name == "": // Pop if tos == noPath { return "<malformed symbol table>", 0 } tos.prev.offset += val - tos.start tos = tos.prev default: // Push tos = &stackEnt{s.Name, val, 0, tos} } } if tos == noPath { return "", 0 } return tos.path, aline - tos.start - tos.offset + 1 } func (o *Obj) alineFromLine(path string, line int) (int, error) { if line < 1 { return 0, &UnknownLineError{path, line} } for i, s := range o.Paths { // Find this path if s.Name != path { continue } // Find this line at this stack level depth := 0 var incstart int line += int(s.Value) pathloop: for _, s := range o.Paths[i:] { val := int(s.Value) switch { case depth == 1 && val >= line: return line - 1, nil case s.Name == "": depth-- if depth == 0 { break pathloop } else if depth == 1 { line += val - incstart } default: if depth == 1 { incstart = val } depth++ } } return 0, &UnknownLineError{path, line} } return 0, UnknownFileError(path) } /* * Errors */ // UnknownFileError represents a failure to find the specific file in // the symbol table. type UnknownFileError string func (e UnknownFileError) Error() string { return "unknown file: " + string(e) } // UnknownLineError represents a failure to map a line to a program // counter, either because the line is beyond the bounds of the file // or because there is no code on the given line. type UnknownLineError struct { File string Line int } func (e *UnknownLineError) Error() string { return "no code at " + e.File + ":" + strconv.Itoa(e.Line) } // DecodingError represents an error during the decoding of // the symbol table. type DecodingError struct { off int msg string val any } func (e *DecodingError) Error() string { msg := e.msg if e.val != nil { msg += fmt.Sprintf(" '%v'", e.val) } msg += fmt.Sprintf(" at byte %#x", e.off) return msg }
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/symtab_test.go
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gosym import ( "fmt" "testing" ) func assertString(t *testing.T, dsc, out, tgt string) { if out != tgt { t.Fatalf("Expected: %q Actual: %q for %s", tgt, out, dsc) } } func TestStandardLibPackage(t *testing.T) { s1 := Sym{Name: "io.(*LimitedReader).Read"} s2 := Sym{Name: "io.NewSectionReader"} assertString(t, fmt.Sprintf("package of %q", s1.Name), s1.PackageName(), "io") assertString(t, fmt.Sprintf("package of %q", s2.Name), s2.PackageName(), "io") assertString(t, fmt.Sprintf("receiver of %q", s1.Name), s1.ReceiverName(), "(*LimitedReader)") assertString(t, fmt.Sprintf("receiver of %q", s2.Name), s2.ReceiverName(), "") } func TestStandardLibPathPackage(t *testing.T) { s1 := Sym{Name: "debug/gosym.(*LineTable).PCToLine"} s2 := Sym{Name: "debug/gosym.NewTable"} assertString(t, fmt.Sprintf("package of %q", s1.Name), s1.PackageName(), "debug/gosym") assertString(t, fmt.Sprintf("package of %q", s2.Name), s2.PackageName(), "debug/gosym") assertString(t, fmt.Sprintf("receiver of %q", s1.Name), s1.ReceiverName(), "(*LineTable)") assertString(t, fmt.Sprintf("receiver of %q", s2.Name), s2.ReceiverName(), "") } func TestGenericNames(t *testing.T) { s1 := Sym{Name: "main.set[int]"} s2 := Sym{Name: "main.(*value[int]).get"} s3 := Sym{Name: "a/b.absDifference[c/d.orderedAbs[float64]]"} s4 := Sym{Name: "main.testfunction[.shape.int]"} assertString(t, fmt.Sprintf("package of %q", s1.Name), s1.PackageName(), "main") assertString(t, fmt.Sprintf("package of %q", s2.Name), s2.PackageName(), "main") assertString(t, fmt.Sprintf("package of %q", s3.Name), s3.PackageName(), "a/b") assertString(t, fmt.Sprintf("package of %q", s4.Name), s4.PackageName(), "main") assertString(t, fmt.Sprintf("receiver of %q", s1.Name), s1.ReceiverName(), "") assertString(t, fmt.Sprintf("receiver of %q", s2.Name), s2.ReceiverName(), "(*value[int])") assertString(t, fmt.Sprintf("receiver of %q", s3.Name), s3.ReceiverName(), "") assertString(t, fmt.Sprintf("receiver of %q", s4.Name), s4.ReceiverName(), "") assertString(t, fmt.Sprintf("base of %q", s1.Name), s1.BaseName(), "set[int]") assertString(t, fmt.Sprintf("base of %q", s2.Name), s2.BaseName(), "get") assertString(t, fmt.Sprintf("base of %q", s3.Name), s3.BaseName(), "absDifference[c/d.orderedAbs[float64]]") assertString(t, fmt.Sprintf("base of %q", s4.Name), s4.BaseName(), "testfunction[.shape.int]") } func TestRemotePackage(t *testing.T) { s1 := Sym{Name: "github.com/docker/doc.ker/pkg/mflag.(*FlagSet).PrintDefaults"} s2 := Sym{Name: "github.com/docker/doc.ker/pkg/mflag.PrintDefaults"} assertString(t, fmt.Sprintf("package of %q", s1.Name), s1.PackageName(), "github.com/docker/doc.ker/pkg/mflag") assertString(t, fmt.Sprintf("package of %q", s2.Name), s2.PackageName(), "github.com/docker/doc.ker/pkg/mflag") assertString(t, fmt.Sprintf("receiver of %q", s1.Name), s1.ReceiverName(), "(*FlagSet)") assertString(t, fmt.Sprintf("receiver of %q", s2.Name), s2.ReceiverName(), "") } func TestIssue29551(t *testing.T) { tests := []struct { sym Sym pkgName string }{ {Sym{goVersion: ver120, Name: "type:.eq.[9]debug/elf.intName"}, ""}, {Sym{goVersion: ver120, Name: "type:.hash.debug/elf.ProgHeader"}, ""}, {Sym{goVersion: ver120, Name: "type:.eq.runtime._panic"}, ""}, {Sym{goVersion: ver120, Name: "type:.hash.struct { runtime.gList; runtime.n int32 }"}, ""}, {Sym{goVersion: ver120, Name: "go:(*struct { sync.Mutex; math/big.table [64]math/big"}, ""}, {Sym{goVersion: ver120, Name: "go.uber.org/zap/buffer.(*Buffer).AppendString"}, "go.uber.org/zap/buffer"}, {Sym{goVersion: ver118, Name: "type..eq.[9]debug/elf.intName"}, ""}, {Sym{goVersion: ver118, Name: "type..hash.debug/elf.ProgHeader"}, ""}, {Sym{goVersion: ver118, Name: "type..eq.runtime._panic"}, ""}, {Sym{goVersion: ver118, Name: "type..hash.struct { runtime.gList; runtime.n int32 }"}, ""}, {Sym{goVersion: ver118, Name: "go.(*struct { sync.Mutex; math/big.table [64]math/big"}, ""}, // unfortunate {Sym{goVersion: ver118, Name: "go.uber.org/zap/buffer.(*Buffer).AppendString"}, ""}, } for _, tc := range tests { assertString(t, fmt.Sprintf("package of %q", tc.sym.Name), tc.sym.PackageName(), tc.pkgName) } }
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/pclntab.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* * Line tables */ package gosym import ( "bytes" "encoding/binary" "sort" "sync" ) // version of the pclntab type version int const ( verUnknown version = iota ver11 ver12 ver116 ver118 ver120 ) // A LineTable is a data structure mapping program counters to line numbers. // // In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, // and the line number corresponded to a numbering of all source lines in the // program, across all files. That absolute line number would then have to be // converted separately to a file name and line number within the file. // // In Go 1.2, the format of the data changed so that there is a single LineTable // for the entire program, shared by all Funcs, and there are no absolute line // numbers, just line numbers within specific files. // // For the most part, LineTable's methods should be treated as an internal // detail of the package; callers should use the methods on Table instead. type LineTable struct { Data []byte PC uint64 Line int // This mutex is used to keep parsing of pclntab synchronous. mu sync.Mutex // Contains the version of the pclntab section. version version // Go 1.2/1.16/1.18 state binary binary.ByteOrder quantum uint32 ptrsize uint32 textStart uint64 // address of runtime.text symbol (1.18+) funcnametab []byte cutab []byte funcdata []byte functab []byte nfunctab uint32 filetab []byte pctab []byte // points to the pctables. nfiletab uint32 funcNames map[uint32]string // cache the function names strings map[uint32]string // interned substrings of Data, keyed by offset // fileMap varies depending on the version of the object file. // For ver12, it maps the name to the index in the file table. // For ver116, it maps the name to the offset in filetab. fileMap map[string]uint32 } // NOTE(rsc): This is wrong for GOARCH=arm, which uses a quantum of 4, // but we have no idea whether we're using arm or not. This only // matters in the old (pre-Go 1.2) symbol table format, so it's not worth // fixing. const oldQuantum = 1 func (t *LineTable) parse(targetPC uint64, targetLine int) (b []byte, pc uint64, line int) { // The PC/line table can be thought of as a sequence of // <pc update>* <line update> // batches. Each update batch results in a (pc, line) pair, // where line applies to every PC from pc up to but not // including the pc of the next pair. // // Here we process each update individually, which simplifies // the code, but makes the corner cases more confusing. b, pc, line = t.Data, t.PC, t.Line for pc <= targetPC && line != targetLine && len(b) > 0 { code := b[0] b = b[1:] switch { case code == 0: if len(b) < 4 { b = b[0:0] break } val := binary.BigEndian.Uint32(b) b = b[4:] line += int(val) case code <= 64: line += int(code) case code <= 128: line -= int(code - 64) default: pc += oldQuantum * uint64(code-128) continue } pc += oldQuantum } return b, pc, line } func (t *LineTable) slice(pc uint64) *LineTable { data, pc, line := t.parse(pc, -1) return &LineTable{Data: data, PC: pc, Line: line} } // PCToLine returns the line number for the given program counter. // // Deprecated: Use Table's PCToLine method instead. func (t *LineTable) PCToLine(pc uint64) int { if t.isGo12() { return t.go12PCToLine(pc) } _, _, line := t.parse(pc, -1) return line } // LineToPC returns the program counter for the given line number, // considering only program counters before maxpc. // // Deprecated: Use Table's LineToPC method instead. func (t *LineTable) LineToPC(line int, maxpc uint64) uint64 { if t.isGo12() { return 0 } _, pc, line1 := t.parse(maxpc, line) if line1 != line { return 0 } // Subtract quantum from PC to account for post-line increment return pc - oldQuantum } // NewLineTable returns a new PC/line table // corresponding to the encoded data. // Text must be the start address of the // corresponding text segment. func NewLineTable(data []byte, text uint64) *LineTable { return &LineTable{Data: data, PC: text, Line: 0, funcNames: make(map[uint32]string), strings: make(map[uint32]string)} } // Go 1.2 symbol table format. // See golang.org/s/go12symtab. // // A general note about the methods here: rather than try to avoid // index out of bounds errors, we trust Go to detect them, and then // we recover from the panics and treat them as indicative of a malformed // or incomplete table. // // The methods called by symtab.go, which begin with "go12" prefixes, // are expected to have that recovery logic. // isGo12 reports whether this is a Go 1.2 (or later) symbol table. func (t *LineTable) isGo12() bool { t.parsePclnTab() return t.version >= ver12 } const ( go12magic = 0xfffffffb go116magic = 0xfffffffa go118magic = 0xfffffff0 go120magic = 0xfffffff1 ) // uintptr returns the pointer-sized value encoded at b. // The pointer size is dictated by the table being read. func (t *LineTable) uintptr(b []byte) uint64 { if t.ptrsize == 4 { return uint64(t.binary.Uint32(b)) } return t.binary.Uint64(b) } // parsePclnTab parses the pclntab, setting the version. func (t *LineTable) parsePclnTab() { t.mu.Lock() defer t.mu.Unlock() if t.version != verUnknown { return } // Note that during this function, setting the version is the last thing we do. // If we set the version too early, and parsing failed (likely as a panic on // slice lookups), we'd have a mistaken version. // // Error paths through this code will default the version to 1.1. t.version = ver11 if !disableRecover { defer func() { // If we panic parsing, assume it's a Go 1.1 pclntab. _ = recover() }() } // Check header: 4-byte magic, two zeros, pc quantum, pointer size. if len(t.Data) < 16 || t.Data[4] != 0 || t.Data[5] != 0 || (t.Data[6] != 1 && t.Data[6] != 2 && t.Data[6] != 4) || // pc quantum (t.Data[7] != 4 && t.Data[7] != 8) { // pointer size return } var possibleVersion version leMagic := binary.LittleEndian.Uint32(t.Data) beMagic := binary.BigEndian.Uint32(t.Data) switch { case leMagic == go12magic: t.binary, possibleVersion = binary.LittleEndian, ver12 case beMagic == go12magic: t.binary, possibleVersion = binary.BigEndian, ver12 case leMagic == go116magic: t.binary, possibleVersion = binary.LittleEndian, ver116 case beMagic == go116magic: t.binary, possibleVersion = binary.BigEndian, ver116 case leMagic == go118magic: t.binary, possibleVersion = binary.LittleEndian, ver118 case beMagic == go118magic: t.binary, possibleVersion = binary.BigEndian, ver118 case leMagic == go120magic: t.binary, possibleVersion = binary.LittleEndian, ver120 case beMagic == go120magic: t.binary, possibleVersion = binary.BigEndian, ver120 default: return } t.version = possibleVersion // quantum and ptrSize are the same between 1.2, 1.16, and 1.18 t.quantum = uint32(t.Data[6]) t.ptrsize = uint32(t.Data[7]) offset := func(word uint32) uint64 { return t.uintptr(t.Data[8+word*t.ptrsize:]) } data := func(word uint32) []byte { return t.Data[offset(word):] } switch possibleVersion { case ver118, ver120: t.nfunctab = uint32(offset(0)) t.nfiletab = uint32(offset(1)) t.textStart = t.PC // use the start PC instead of reading from the table, which may be unrelocated t.funcnametab = data(3) t.cutab = data(4) t.filetab = data(5) t.pctab = data(6) t.funcdata = data(7) t.functab = data(7) functabsize := (int(t.nfunctab)*2 + 1) * t.functabFieldSize() t.functab = t.functab[:functabsize] case ver116: t.nfunctab = uint32(offset(0)) t.nfiletab = uint32(offset(1)) t.funcnametab = data(2) t.cutab = data(3) t.filetab = data(4) t.pctab = data(5) t.funcdata = data(6) t.functab = data(6) functabsize := (int(t.nfunctab)*2 + 1) * t.functabFieldSize() t.functab = t.functab[:functabsize] case ver12: t.nfunctab = uint32(t.uintptr(t.Data[8:])) t.funcdata = t.Data t.funcnametab = t.Data t.functab = t.Data[8+t.ptrsize:] t.pctab = t.Data functabsize := (int(t.nfunctab)*2 + 1) * t.functabFieldSize() fileoff := t.binary.Uint32(t.functab[functabsize:]) t.functab = t.functab[:functabsize] t.filetab = t.Data[fileoff:] t.nfiletab = t.binary.Uint32(t.filetab) t.filetab = t.filetab[:t.nfiletab*4] default: panic("unreachable") } } // go12Funcs returns a slice of Funcs derived from the Go 1.2+ pcln table. func (t *LineTable) go12Funcs() []Func { // Assume it is malformed and return nil on error. if !disableRecover { defer func() { _ = recover() }() } ft := t.funcTab() funcs := make([]Func, ft.Count()) syms := make([]Sym, len(funcs)) for i := range funcs { f := &funcs[i] f.Entry = ft.pc(i) f.End = ft.pc(i + 1) info := t.funcData(uint32(i)) f.LineTable = t f.FrameSize = int(info.deferreturn()) // Additions: // numFuncField is the number of (32 bit) fields in _func (src/runtime/runtime2.go) // Note that the last 4 fields are 32 bits combined. This number is 11 for go1.20, // 10 for earlier versions down to go1.16, and 9 before that. var numFuncFields uint32 = 11 if t.version < ver116 { numFuncFields = 9 } else if t.version < ver120 { numFuncFields = 10 } f.inlineTreeOffset = info.funcdataOffset(funcdata_InlTree, numFuncFields) f.inlineTreeCount = 1 + t.maxInlineTreeIndexValue(info, numFuncFields) syms[i] = Sym{ Value: f.Entry, Type: 'T', Name: t.funcName(info.nameOff()), GoType: 0, Func: f, goVersion: t.version, } f.Sym = &syms[i] } return funcs } // findFunc returns the funcData corresponding to the given program counter. func (t *LineTable) findFunc(pc uint64) funcData { ft := t.funcTab() if pc < ft.pc(0) || pc >= ft.pc(ft.Count()) { return funcData{} } idx := sort.Search(int(t.nfunctab), func(i int) bool { return ft.pc(i) > pc }) idx-- return t.funcData(uint32(idx)) } // readvarint reads, removes, and returns a varint from *pp. func (t *LineTable) readvarint(pp *[]byte) uint32 { var v, shift uint32 p := *pp for shift = 0; ; shift += 7 { b := p[0] p = p[1:] v |= (uint32(b) & 0x7F) << shift if b&0x80 == 0 { break } } *pp = p return v } // funcName returns the name of the function found at off. func (t *LineTable) funcName(off uint32) string { if s, ok := t.funcNames[off]; ok { return s } i := bytes.IndexByte(t.funcnametab[off:], 0) s := string(t.funcnametab[off : off+uint32(i)]) t.funcNames[off] = s return s } // stringFrom returns a Go string found at off from a position. func (t *LineTable) stringFrom(arr []byte, off uint32) string { if s, ok := t.strings[off]; ok { return s } i := bytes.IndexByte(arr[off:], 0) s := string(arr[off : off+uint32(i)]) t.strings[off] = s return s } // string returns a Go string found at off. func (t *LineTable) string(off uint32) string { return t.stringFrom(t.funcdata, off) } // functabFieldSize returns the size in bytes of a single functab field. func (t *LineTable) functabFieldSize() int { if t.version >= ver118 { return 4 } return int(t.ptrsize) } // funcTab returns t's funcTab. func (t *LineTable) funcTab() funcTab { return funcTab{LineTable: t, sz: t.functabFieldSize()} } // funcTab is memory corresponding to a slice of functab structs, followed by an invalid PC. // A functab struct is a PC and a func offset. type funcTab struct { *LineTable sz int // cached result of t.functabFieldSize } // Count returns the number of func entries in f. func (f funcTab) Count() int { return int(f.nfunctab) } // pc returns the PC of the i'th func in f. func (f funcTab) pc(i int) uint64 { u := f.uint(f.functab[2*i*f.sz:]) if f.version >= ver118 { u += f.textStart } return u } // funcOff returns the funcdata offset of the i'th func in f. func (f funcTab) funcOff(i int) uint64 { return f.uint(f.functab[(2*i+1)*f.sz:]) } // uint returns the uint stored at b. func (f funcTab) uint(b []byte) uint64 { if f.sz == 4 { return uint64(f.binary.Uint32(b)) } return f.binary.Uint64(b) } // funcData is memory corresponding to an _func struct. type funcData struct { t *LineTable // LineTable this data is a part of data []byte // raw memory for the function } // funcData returns the ith funcData in t.functab. func (t *LineTable) funcData(i uint32) funcData { data := t.funcdata[t.funcTab().funcOff(int(i)):] return funcData{t: t, data: data} } // IsZero reports whether f is the zero value. func (f funcData) IsZero() bool { return f.t == nil && f.data == nil } // entryPC returns the func's entry PC. func (f *funcData) entryPC() uint64 { // In Go 1.18, the first field of _func changed // from a uintptr entry PC to a uint32 entry offset. if f.t.version >= ver118 { // TODO: support multiple text sections. // See runtime/symtab.go:(*moduledata).textAddr. return uint64(f.t.binary.Uint32(f.data)) + f.t.textStart } return f.t.uintptr(f.data) } func (f funcData) nameOff() uint32 { return f.field(1) } func (f funcData) deferreturn() uint32 { return f.field(3) } func (f funcData) pcfile() uint32 { return f.field(5) } func (f funcData) pcln() uint32 { return f.field(6) } func (f funcData) cuOffset() uint32 { return f.field(8) } // field returns the nth field of the _func struct. // It panics if n == 0 or n > 9; for n == 0, call f.entryPC. // Most callers should use a named field accessor (just above). func (f funcData) field(n uint32) uint32 { if n == 0 || n > 9 { panic("bad funcdata field") } // Addition: some code deleted here to support inlining. off := f.fieldOffset(n) data := f.data[off:] return f.t.binary.Uint32(data) } // step advances to the next pc, value pair in the encoded table. func (t *LineTable) step(p *[]byte, pc *uint64, val *int32, first bool) bool { uvdelta := t.readvarint(p) if uvdelta == 0 && !first { return false } if uvdelta&1 != 0 { uvdelta = ^(uvdelta >> 1) } else { uvdelta >>= 1 } vdelta := int32(uvdelta) pcdelta := t.readvarint(p) * t.quantum *pc += uint64(pcdelta) *val += vdelta return true } // pcvalue reports the value associated with the target pc. // off is the offset to the beginning of the pc-value table, // and entry is the start PC for the corresponding function. func (t *LineTable) pcvalue(off uint32, entry, targetpc uint64) int32 { p := t.pctab[off:] val := int32(-1) pc := entry for t.step(&p, &pc, &val, pc == entry) { if targetpc < pc { return val } } return -1 } // findFileLine scans one function in the binary looking for a // program counter in the given file on the given line. // It does so by running the pc-value tables mapping program counter // to file number. Since most functions come from a single file, these // are usually short and quick to scan. If a file match is found, then the // code goes to the expense of looking for a simultaneous line number match. func (t *LineTable) findFileLine(entry uint64, filetab, linetab uint32, filenum, line int32, cutab []byte) uint64 { if filetab == 0 || linetab == 0 { return 0 } fp := t.pctab[filetab:] fl := t.pctab[linetab:] fileVal := int32(-1) filePC := entry lineVal := int32(-1) linePC := entry fileStartPC := filePC for t.step(&fp, &filePC, &fileVal, filePC == entry) { fileIndex := fileVal if t.version == ver116 || t.version == ver118 || t.version == ver120 { fileIndex = int32(t.binary.Uint32(cutab[fileVal*4:])) } if fileIndex == filenum && fileStartPC < filePC { // fileIndex is in effect starting at fileStartPC up to // but not including filePC, and it's the file we want. // Run the PC table looking for a matching line number // or until we reach filePC. lineStartPC := linePC for linePC < filePC && t.step(&fl, &linePC, &lineVal, linePC == entry) { // lineVal is in effect until linePC, and lineStartPC < filePC. if lineVal == line { if fileStartPC <= lineStartPC { return lineStartPC } if fileStartPC < linePC { return fileStartPC } } lineStartPC = linePC } } fileStartPC = filePC } return 0 } // go12PCToLine maps program counter to line number for the Go 1.2+ pcln table. func (t *LineTable) go12PCToLine(pc uint64) (line int) { defer func() { if !disableRecover && recover() != nil { line = -1 } }() f := t.findFunc(pc) if f.IsZero() { return -1 } entry := f.entryPC() linetab := f.pcln() return int(t.pcvalue(linetab, entry, pc)) } // go12PCToFile maps program counter to file name for the Go 1.2+ pcln table. func (t *LineTable) go12PCToFile(pc uint64) (file string) { defer func() { if !disableRecover && recover() != nil { file = "" } }() f := t.findFunc(pc) if f.IsZero() { return "" } entry := f.entryPC() filetab := f.pcfile() fno := t.pcvalue(filetab, entry, pc) if t.version == ver12 { if fno <= 0 { return "" } return t.string(t.binary.Uint32(t.filetab[4*fno:])) } // Go ≥ 1.16 if fno < 0 { // 0 is valid for ≥ 1.16 return "" } cuoff := f.cuOffset() if fnoff := t.binary.Uint32(t.cutab[(cuoff+uint32(fno))*4:]); fnoff != ^uint32(0) { return t.stringFrom(t.filetab, fnoff) } return "" } // go12LineToPC maps a (file, line) pair to a program counter for the Go 1.2+ pcln table. func (t *LineTable) go12LineToPC(file string, line int) (pc uint64) { defer func() { if !disableRecover && recover() != nil { pc = 0 } }() t.initFileMap() filenum, ok := t.fileMap[file] if !ok { return 0 } // Scan all functions. // If this turns out to be a bottleneck, we could build a map[int32][]int32 // mapping file number to a list of functions with code from that file. var cutab []byte for i := uint32(0); i < t.nfunctab; i++ { f := t.funcData(i) entry := f.entryPC() filetab := f.pcfile() linetab := f.pcln() if t.version == ver116 || t.version == ver118 || t.version == ver120 { if f.cuOffset() == ^uint32(0) { // skip functions without compilation unit (not real function, or linker generated) continue } cutab = t.cutab[f.cuOffset()*4:] } pc := t.findFileLine(entry, filetab, linetab, int32(filenum), int32(line), cutab) if pc != 0 { return pc } } return 0 } // initFileMap initializes the map from file name to file number. func (t *LineTable) initFileMap() { t.mu.Lock() defer t.mu.Unlock() if t.fileMap != nil { return } m := make(map[string]uint32) if t.version == ver12 { for i := uint32(1); i < t.nfiletab; i++ { s := t.string(t.binary.Uint32(t.filetab[4*i:])) m[s] = i } } else { var pos uint32 for i := uint32(0); i < t.nfiletab; i++ { s := t.stringFrom(t.filetab, pos) m[s] = pos pos += uint32(len(s) + 1) } } t.fileMap = m } // go12MapFiles adds to m a key for every file in the Go 1.2 LineTable. // Every key maps to obj. That's not a very interesting map, but it provides // a way for callers to obtain the list of files in the program. func (t *LineTable) go12MapFiles(m map[string]*Obj, obj *Obj) { if !disableRecover { defer func() { _ = recover() }() } t.initFileMap() for file := range t.fileMap { m[file] = obj } } // disableRecover causes this package not to swallow panics. // This is useful when making changes. const disableRecover = true
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/additions.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gosym import ( "encoding/binary" "io" "strings" sv "golang.org/x/mod/semver" "golang.org/x/vuln/internal/semver" ) const ( funcSymNameGo119Lower string = "go.func.*" funcSymNameGo120 string = "go:func.*" ) // FuncSymName returns symbol name for Go functions used in binaries // based on Go version. Supported Go versions are 1.18 and greater. // If the go version is unreadable it assumes that it is a newer version // and returns the symbol name for go version 1.20 or greater. func FuncSymName(goVersion string) string { // Support devel goX.Y... v := strings.TrimPrefix(goVersion, "devel ") v = semver.GoTagToSemver(v) mm := sv.MajorMinor(v) if sv.Compare(mm, "v1.20") >= 0 || mm == "" { return funcSymNameGo120 } else if sv.Compare(mm, "v1.18") >= 0 { return funcSymNameGo119Lower } return "" } // Additions to the original package from cmd/internal/objabi/funcdata.go const ( pcdata_InlTreeIndex = 2 funcdata_InlTree = 3 ) // InlineTree returns the inline tree for Func f as a sequence of InlinedCalls. // goFuncValue is the value of the gosym.FuncSymName symbol. // baseAddr is the address of the memory region (ELF Prog) containing goFuncValue. // progReader is a ReaderAt positioned at the start of that region. func (t *LineTable) InlineTree(f *Func, goFuncValue, baseAddr uint64, progReader io.ReaderAt) ([]InlinedCall, error) { if f.inlineTreeCount == 0 { return nil, nil } if f.inlineTreeOffset == ^uint32(0) { return nil, nil } var offset int64 if t.version >= ver118 { offset = int64(goFuncValue - baseAddr + uint64(f.inlineTreeOffset)) } else { offset = int64(uint64(f.inlineTreeOffset) - baseAddr) } r := io.NewSectionReader(progReader, offset, 1<<32) // pick a size larger than we need ics := make([]InlinedCall, 0, f.inlineTreeCount) for i := 0; i < f.inlineTreeCount; i++ { if t.version >= ver120 { var ric rawInlinedCall120 if err := binary.Read(r, t.binary, &ric); err != nil { return nil, err } ics = append(ics, InlinedCall{ FuncID: ric.FuncID, Name: t.funcName(uint32(ric.NameOff)), ParentPC: ric.ParentPC, }) } else { var ric rawInlinedCall112 if err := binary.Read(r, t.binary, &ric); err != nil { return nil, err } ics = append(ics, InlinedCall{ FuncID: ric.FuncID, Name: t.funcName(uint32(ric.Func_)), ParentPC: ric.ParentPC, }) } } return ics, nil } // InlinedCall describes a call to an inlined function. type InlinedCall struct { FuncID uint8 // type of the called function Name string // name of called function ParentPC int32 // position of an instruction whose source position is the call site (offset from entry) } // rawInlinedCall112 is the encoding of entries in the FUNCDATA_InlTree table // from Go 1.12 through 1.19. It is equivalent to runtime.inlinedCall. type rawInlinedCall112 struct { Parent int16 // index of parent in the inltree, or < 0 FuncID uint8 // type of the called function _ byte File int32 // perCU file index for inlined call. See cmd/link:pcln.go Line int32 // line number of the call site Func_ int32 // offset into pclntab for name of called function ParentPC int32 // position of an instruction whose source position is the call site (offset from entry) } // rawInlinedCall120 is the encoding of entries in the FUNCDATA_InlTree table // from Go 1.20. It is equivalent to runtime.inlinedCall. type rawInlinedCall120 struct { FuncID uint8 // type of the called function _ [3]byte NameOff int32 // offset into pclntab for name of called function ParentPC int32 // position of an instruction whose source position is the call site (offset from entry) StartLine int32 // line number of start of function (func keyword/TEXT directive) } func (f funcData) npcdata() uint32 { return f.field(7) } func (f funcData) nfuncdata(numFuncFields uint32) uint32 { return uint32(f.data[f.fieldOffset(numFuncFields-1)+3]) } func (f funcData) funcdataOffset(i uint8, numFuncFields uint32) uint32 { if uint32(i) >= f.nfuncdata(numFuncFields) { return ^uint32(0) } var off uint32 if f.t.version >= ver118 { off = f.fieldOffset(numFuncFields) + // skip fixed part of _func f.npcdata()*4 + // skip pcdata uint32(i)*4 // index of i'th FUNCDATA } else { off = f.fieldOffset(numFuncFields) + // skip fixed part of _func f.npcdata()*4 off += uint32(i) * f.t.ptrsize } return f.t.binary.Uint32(f.data[off:]) } func (f funcData) fieldOffset(n uint32) uint32 { // In Go 1.18, the first field of _func changed // from a uintptr entry PC to a uint32 entry offset. sz0 := f.t.ptrsize if f.t.version >= ver118 { sz0 = 4 } return sz0 + (n-1)*4 // subsequent fields are 4 bytes each } func (f funcData) pcdataOffset(i uint8, numFuncFields uint32) uint32 { if uint32(i) >= f.npcdata() { return ^uint32(0) } off := f.fieldOffset(numFuncFields) + // skip fixed part of _func uint32(i)*4 // index of i'th PCDATA return f.t.binary.Uint32(f.data[off:]) } // maxInlineTreeIndexValue returns the maximum value of the inline tree index // pc-value table in info. This is the only way to determine how many // IndexedCalls are in an inline tree, since the data of the tree itself is not // delimited in any way. func (t *LineTable) maxInlineTreeIndexValue(info funcData, numFuncFields uint32) int { if info.npcdata() <= pcdata_InlTreeIndex { return -1 } off := info.pcdataOffset(pcdata_InlTreeIndex, numFuncFields) p := t.pctab[off:] val := int32(-1) max := int32(-1) var pc uint64 for t.step(&p, &pc, &val, pc == 0) { if val > max { max = val } } return int(max) } type inlTree struct { inlineTreeOffset uint32 // offset from go.func.* symbol inlineTreeCount int // number of entries in inline tree }
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/README.md
This code is a copied and slightly modified version of go/src/debug/gosym. The original code contains logic for accessing symbol tables and line numbers in Go binaries. The only reason why this is copied is to support inlining. Code added by vulncheck is located in files with "additions_" prefix and it contains logic for accessing inlining information. Within the originally named files, deleted or added logic is annotated with a comment starting with "Addition:". The modified logic allows the inlining code in "additions_*" files to access the necessary information.
gosym
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/additions_test.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gosym import ( "debug/elf" "runtime" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" ) func TestFuncSymName(t *testing.T) { for _, test := range []struct { v string want string }{ {"go1.15", ""}, {"go1.18", funcSymNameGo119Lower}, {"go1.19", funcSymNameGo119Lower}, {"devel go1.19", funcSymNameGo119Lower}, {"go1.19-pre4", funcSymNameGo119Lower}, {"go1.20", funcSymNameGo120}, {"devel bd56cb90a72e6725e", funcSymNameGo120}, {"go1.21", funcSymNameGo120}, {"unknown version", funcSymNameGo120}, } { if got := FuncSymName(test.v); got != test.want { t.Errorf("got %s; want %s", got, test.want) } } } func TestInlineTree(t *testing.T) { t.Skip("to temporarily resolve #61511") pclinetestBinary, cleanup := dotest(t) defer cleanup() f, err := elf.Open(pclinetestBinary) if err != nil { t.Fatal(err) } defer f.Close() pclndat, err := f.Section(".gopclntab").Data() if err != nil { t.Fatalf("reading %s gopclntab: %v", pclinetestBinary, err) } // The test binaries will be compiled with the same Go version // used to run the tests. goFunc := lookupSymbol(f, FuncSymName(runtime.Version())) if goFunc == nil { t.Fatal("couldn't find go.func.*") } prog := progContaining(f, goFunc.Value) if prog == nil { t.Fatal("couldn't find go.func.* Prog") } pcln := NewLineTable(pclndat, f.Section(".text").Addr) s := f.Section(".gosymtab") if s == nil { t.Fatal("no .gosymtab section") } d, err := s.Data() if err != nil { t.Fatal(err) } tab, err := NewTable(d, pcln) if err != nil { t.Fatal(err) } fun := tab.LookupFunc("main.main") got, err := pcln.InlineTree(fun, goFunc.Value, prog.Vaddr, prog.ReaderAt) if err != nil { t.Fatal(err) } want := []InlinedCall{ {FuncID: 0, Name: "main.inline1"}, {FuncID: 0, Name: "main.inline2"}, } if !cmp.Equal(got, want, cmpopts.IgnoreFields(InlinedCall{}, "ParentPC")) { t.Errorf("got\n%+v\nwant\n%+v", got, want) } } func progContaining(f *elf.File, addr uint64) *elf.Prog { for _, p := range f.Progs { if addr >= p.Vaddr && addr < p.Vaddr+p.Filesz { return p } } return nil } func lookupSymbol(f *elf.File, name string) *elf.Symbol { syms, err := f.Symbols() if err != nil { return nil } for _, s := range syms { if s.Name == name { return &s } } return nil }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/testdata/pclinetest.s
TEXT ·linefrompc(SB),4,$0 // Each byte stores its line delta BYTE $2; BYTE $1; BYTE $1; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $1; BYTE $1; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; #include "pclinetest.h" BYTE $2; #include "pclinetest.h" BYTE $2; BYTE $255; TEXT ·pcfromline(SB),4,$0 // Each record stores its line delta, then n, then n more bytes BYTE $32; BYTE $0; BYTE $1; BYTE $1; BYTE $0; BYTE $1; BYTE $0; BYTE $2; BYTE $4; BYTE $0; BYTE $0; BYTE $0; BYTE $0; #include "pclinetest.h" BYTE $4; BYTE $0; BYTE $3; BYTE $3; BYTE $0; BYTE $0; BYTE $0; #include "pclinetest.h" BYTE $4; BYTE $3; BYTE $0; BYTE $0; BYTE $0; BYTE $255;
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/testdata/pclinetest.h
// +build ignore // Empty include file to generate z symbols // EOF
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/gosym/testdata/main.go
package main func linefrompc() func pcfromline() func main() { // Prevent GC of our test symbols linefrompc() pcfromline() inline1() } func inline1() { inline2() } func inline2() { println(1) }
test
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/test/buildtest.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package test import ( "errors" "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "golang.org/x/vuln/internal/testenv" ) var unsupportedGoosGoarch = map[string]bool{ "darwin/386": true, "darwin/arm": true, } // GoBuild runs "go build" on dir using the additional environment variables in // envVarVals, which should be an alternating list of variables and values. // It returns the path to the resulting binary, and a function // to call when finished with the binary. func GoBuild(t *testing.T, dir, tags string, strip bool, envVarVals ...string) (binaryPath string, cleanup func()) { testenv.NeedsGoBuild(t) if len(envVarVals)%2 != 0 { t.Fatal("last args should be alternating variables and values") } var env []string if len(envVarVals) > 0 { env = os.Environ() for i := 0; i < len(envVarVals); i += 2 { env = append(env, fmt.Sprintf("%s=%s", envVarVals[i], envVarVals[i+1])) } } gg := lookupEnv("GOOS", env, runtime.GOOS) + "/" + lookupEnv("GOARCH", env, runtime.GOARCH) if unsupportedGoosGoarch[gg] { t.Skipf("skipping unsupported GOOS/GOARCH pair %s", gg) } tmpDir, err := os.MkdirTemp("", "buildtest") if err != nil { t.Fatal(err) } abs, err := filepath.Abs(dir) if err != nil { t.Fatal(err) } binaryPath = filepath.Join(tmpDir, filepath.Base(abs)) var exeSuffix string if runtime.GOOS == "windows" { exeSuffix = ".exe" } // Make sure we use the same version of go that is running this test. goCommandPath := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix) if _, err := os.Stat(goCommandPath); err != nil { t.Fatal(err) } args := []string{"build", "-o", binaryPath + exeSuffix} if tags != "" { args = append(args, "-tags", tags) } if strip { args = append(args, "-ldflags", "-s -w") } cmd := exec.Command(goCommandPath, args...) cmd.Dir = dir cmd.Env = env cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { if ee := (*exec.ExitError)(nil); errors.As(err, &ee) && len(ee.Stderr) > 0 { t.Fatalf("%v: %v\n%s", cmd, err, ee.Stderr) } t.Fatalf("%v: %v", cmd, err) } return binaryPath + exeSuffix, func() { os.RemoveAll(tmpDir) } } // lookEnv looks for name in env, a list of "VAR=VALUE" strings. It returns // the value if name is found, and defaultValue if it is not. func lookupEnv(name string, env []string, defaultValue string) string { for _, vv := range env { i := strings.IndexByte(vv, '=') if i < 0 { // malformed env entry; just ignore it continue } if name == vv[:i] { return vv[i+1:] } } return defaultValue }
test
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vuln/internal/test/testenv.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package test import ( "os/exec" "testing" ) // NeedsGoEnv skips t if the current system can't get the environment with // “go env” in a subprocess. func NeedsGoEnv(t testing.TB) { t.Helper() if _, err := exec.LookPath("go"); err != nil { t.Skip("skipping test: can't run go env") } }