diff --git a/cache/bolt.go b/cache/bolt.go index 8bc8cffc3b..825e5642fb 100644 --- a/cache/bolt.go +++ b/cache/bolt.go @@ -2,10 +2,10 @@ package cache import ( "encoding/json" + "fmt" "time" bolt "go.etcd.io/bbolt" - "golang.org/x/xerrors" "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/util" @@ -53,7 +53,7 @@ func (b *Bolt) createBucketIfNotExists(name string) error { return b.db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte(name)) if err != nil { - return xerrors.Errorf("Failed to create bucket: %w", err) + return fmt.Errorf("Failed to create bucket: %w", err) } return nil }) @@ -82,7 +82,7 @@ func (b Bolt) RefreshMeta(meta Meta) error { meta.CreatedAt = time.Now() jsonBytes, err := json.Marshal(meta) if err != nil { - return xerrors.Errorf("Failed to marshal to JSON: %w", err) + return fmt.Errorf("Failed to marshal to JSON: %w", err) } return b.db.Update(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(metabucket)) @@ -98,7 +98,7 @@ func (b Bolt) RefreshMeta(meta Meta) error { func (b Bolt) EnsureBuckets(meta Meta) error { jsonBytes, err := json.Marshal(meta) if err != nil { - return xerrors.Errorf("Failed to marshal to JSON: %w", err) + return fmt.Errorf("Failed to marshal to JSON: %w", err) } return b.db.Update(func(tx *bolt.Tx) error { b.Log.Debugf("Put to meta: %s", meta.Name) @@ -147,7 +147,7 @@ func (b Bolt) GetChangelog(servername, packName string) (changelog string, err e err = b.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(servername)) if bkt == nil { - return xerrors.Errorf("Failed to get Bucket: %s", servername) + return fmt.Errorf("Failed to get Bucket: %s", servername) } v := bkt.Get([]byte(packName)) if v == nil { @@ -165,7 +165,7 @@ func (b Bolt) PutChangelog(servername, packName, changelog string) error { return b.db.Update(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(servername)) if bkt == nil { - return xerrors.Errorf("Failed to get Bucket: %s", servername) + return fmt.Errorf("Failed to get Bucket: %s", servername) } return bkt.Put([]byte(packName), []byte(changelog)) }) diff --git a/config/azureconf.go b/config/azureconf.go index 714769222d..7dfa12245f 100644 --- a/config/azureconf.go +++ b/config/azureconf.go @@ -3,8 +3,6 @@ package config import ( "fmt" "os" - - "golang.org/x/xerrors" ) // AzureConf is azure config @@ -40,13 +38,13 @@ func (c *AzureConf) Validate() (errs []error) { c.AccountName = os.Getenv(azureAccount) } if c.AccountName == "" { - errs = append(errs, xerrors.Errorf("Azure account name is required")) + errs = append(errs, fmt.Errorf("Azure account name is required")) } if os.Getenv(azureKey) != "" { c.AccountKey = os.Getenv(azureKey) } if c.AccountKey == "" { - errs = append(errs, xerrors.Errorf("Azure account key is required")) + errs = append(errs, fmt.Errorf("Azure account key is required")) } if c.Endpoint == "" { @@ -54,7 +52,7 @@ func (c *AzureConf) Validate() (errs []error) { } if c.ContainerName == "" { - errs = append(errs, xerrors.Errorf("Azure storage container name is required")) + errs = append(errs, fmt.Errorf("Azure storage container name is required")) } return } diff --git a/config/chatworkconf.go b/config/chatworkconf.go index 8c0fc5eb40..7bb6fabb8d 100644 --- a/config/chatworkconf.go +++ b/config/chatworkconf.go @@ -1,8 +1,9 @@ package config import ( + "errors" + "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // ChatWorkConf is ChatWork config @@ -18,11 +19,11 @@ func (c *ChatWorkConf) Validate() (errs []error) { return } if len(c.Room) == 0 { - errs = append(errs, xerrors.New("chatWorkConf.room must not be empty")) + errs = append(errs, errors.New("chatWorkConf.room must not be empty")) } if len(c.APIToken) == 0 { - errs = append(errs, xerrors.New("chatWorkConf.ApiToken must not be empty")) + errs = append(errs, errors.New("chatWorkConf.ApiToken must not be empty")) } _, err := govalidator.ValidateStruct(c) diff --git a/config/config.go b/config/config.go index 0aef9c7337..f7926a8b62 100644 --- a/config/config.go +++ b/config/config.go @@ -1,13 +1,13 @@ package config import ( + "errors" "fmt" "os" "strconv" "strings" "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config/syslog" "github.com/future-architect/vuls/constant" @@ -113,7 +113,7 @@ func (c Config) ValidateOnScan() bool { errs := c.checkSSHKeyExist() if len(c.ResultsDir) != 0 { if ok, _ := govalidator.IsFilePath(c.ResultsDir); !ok { - errs = append(errs, xerrors.Errorf( + errs = append(errs, fmt.Errorf( "JSON base directory must be a *Absolute* file path. -results-dir: %s", c.ResultsDir)) } } @@ -147,7 +147,7 @@ func (c Config) checkSSHKeyExist() (errs []error) { } if v.KeyPath != "" { if _, err := os.Stat(v.KeyPath); err != nil { - errs = append(errs, xerrors.Errorf( + errs = append(errs, fmt.Errorf( "%s is invalid. keypath: %s not exists", serverName, v.KeyPath)) } } @@ -161,7 +161,7 @@ func (c *Config) ValidateOnReport() bool { if len(c.ResultsDir) != 0 { if ok, _ := govalidator.IsFilePath(c.ResultsDir); !ok { - errs = append(errs, xerrors.Errorf( + errs = append(errs, fmt.Errorf( "JSON base directory must be a *Absolute* file path. -results-dir: %s", c.ResultsDir)) } } @@ -196,10 +196,10 @@ func (c *Config) ValidateOnReport() bool { &Conf.Cti, } { if err := cnf.Validate(); err != nil { - errs = append(errs, xerrors.Errorf("Failed to validate %s: %+v", cnf.GetName(), err)) + errs = append(errs, fmt.Errorf("Failed to validate %s: %+v", cnf.GetName(), err)) } if err := cnf.CheckHTTPHealth(); err != nil { - errs = append(errs, xerrors.Errorf("Run %s as server mode before reporting: %+v", cnf.GetName(), err)) + errs = append(errs, fmt.Errorf("Run %s as server mode before reporting: %+v", cnf.GetName(), err)) } } @@ -340,7 +340,7 @@ func (l Distro) MajorVersion() (int, error) { return strconv.Atoi(strings.Split(l.Release, ".")[0]) } } - return 0, xerrors.New("Release is empty") + return 0, errors.New("Release is empty") } // IsContainer returns whether this ServerInfo is about container diff --git a/config/config_v1.go b/config/config_v1.go index 671b8edc6d..4d8fb6f599 100644 --- a/config/config_v1.go +++ b/config/config_v1.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/BurntSushi/toml" - "golang.org/x/xerrors" ) // ConfV1 has old version Configuration for windows @@ -68,10 +67,10 @@ func convertToLatestConfig(pathToToml string) error { case "3": server.WinUpdateSrcInt = LocalCab if server.CabPath == "" { - return xerrors.Errorf("Failed to load CabPath. err: CabPath is empty") + return fmt.Errorf("Failed to load CabPath. err: CabPath is empty") } default: - return xerrors.Errorf(`Specify WindUpdateSrc in "0"|"1"|"2"|"3"`) + return fmt.Errorf(`Specify WindUpdateSrc in "0"|"1"|"2"|"3"`) } convertedServerConfig := ServerInfo{ @@ -90,11 +89,11 @@ func convertToLatestConfig(pathToToml string) error { raw, err := os.ReadFile(pathToSaasJSON) if err != nil { - return xerrors.Errorf("Failed to read saas-credential.json. err: %w", err) + return fmt.Errorf("Failed to read saas-credential.json. err: %w", err) } saasJSON := SaasConf{} if err := json.Unmarshal(raw, &saasJSON); err != nil { - return xerrors.Errorf("Failed to unmarshal saas-credential.json. err: %w", err) + return fmt.Errorf("Failed to unmarshal saas-credential.json. err: %w", err) } Conf.Saas = SaasConf{ GroupID: saasJSON.GroupID, @@ -117,21 +116,21 @@ func convertToLatestConfig(pathToToml string) error { // rename the current config.toml to config.toml.bak info, err := os.Lstat(pathToToml) if err != nil { - return xerrors.Errorf("Failed to lstat %s: %w", pathToToml, err) + return fmt.Errorf("Failed to lstat %s: %w", pathToToml, err) } realPath := pathToToml if info.Mode()&os.ModeSymlink == os.ModeSymlink { if realPath, err = os.Readlink(pathToToml); err != nil { - return xerrors.Errorf("Failed to Read link %s: %w", pathToToml, err) + return fmt.Errorf("Failed to Read link %s: %w", pathToToml, err) } } if err := os.Rename(realPath, realPath+".bak"); err != nil { - return xerrors.Errorf("Failed to rename %s: %w", pathToToml, err) + return fmt.Errorf("Failed to rename %s: %w", pathToToml, err) } var buf bytes.Buffer if err := toml.NewEncoder(&buf).Encode(c); err != nil { - return xerrors.Errorf("Failed to encode to toml: %w", err) + return fmt.Errorf("Failed to encode to toml: %w", err) } str := strings.ReplaceAll(buf.String(), "\n [", "\n\n [") str = fmt.Sprintf("%s\n\n%s", diff --git a/config/googlechatconf.go b/config/googlechatconf.go index 5c5bad505e..71e94d3d5d 100644 --- a/config/googlechatconf.go +++ b/config/googlechatconf.go @@ -1,8 +1,9 @@ package config import ( + "errors" + "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // GoogleChatConf is GoogleChat config @@ -19,10 +20,10 @@ func (c *GoogleChatConf) Validate() (errs []error) { return } if len(c.WebHookURL) == 0 { - errs = append(errs, xerrors.New("googleChatConf.webHookURL must not be empty")) + errs = append(errs, errors.New("googleChatConf.webHookURL must not be empty")) } if !govalidator.IsRegex(c.ServerNameRegexp) { - errs = append(errs, xerrors.New("googleChatConf.serverNameRegexp must be regex")) + errs = append(errs, errors.New("googleChatConf.serverNameRegexp must be regex")) } _, err := govalidator.ValidateStruct(c) if err != nil { diff --git a/config/jsonloader.go b/config/jsonloader.go index e53f6b70d9..33c7fdbdc1 100644 --- a/config/jsonloader.go +++ b/config/jsonloader.go @@ -1,6 +1,6 @@ package config -import "golang.org/x/xerrors" +import "errors" // JSONLoader loads configuration type JSONLoader struct { @@ -8,5 +8,5 @@ type JSONLoader struct { // Load load the configuration JSON file specified by path arg. func (c JSONLoader) Load(_, _, _ string) (err error) { - return xerrors.New("Not implement yet") + return errors.New("Not implement yet") } diff --git a/config/portscan.go b/config/portscan.go index 7c4e3a93ef..830d27895d 100644 --- a/config/portscan.go +++ b/config/portscan.go @@ -1,6 +1,8 @@ package config import ( + "errors" + "fmt" "os" "os/exec" "slices" @@ -8,7 +10,6 @@ import ( "strings" "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // PortScanConf is the setting for using an external port scanner @@ -120,36 +121,36 @@ func (c *PortScanConf) Validate() (errs []error) { if c.IsZero() { return } - errs = append(errs, xerrors.New("To enable the PortScan option, ScannerBinPath must be set.")) + errs = append(errs, errors.New("to enable the PortScan option, ScannerBinPath must be set")) } if _, err := os.Stat(c.ScannerBinPath); err != nil { - errs = append(errs, xerrors.Errorf( + errs = append(errs, fmt.Errorf( "scanner is not found. ScannerBinPath: %s not exists", c.ScannerBinPath)) } scanTechniques := c.GetScanTechniques() for _, scanTechnique := range scanTechniques { if scanTechnique == NotSupportTechnique { - errs = append(errs, xerrors.New("There is an unsupported option in ScanTechniques.")) + errs = append(errs, errors.New("there is an unsupported option in ScanTechniques")) } } // It does not currently support multiple ScanTechniques. // But if it supports UDP scanning, it will need to accept multiple ScanTechniques. if len(scanTechniques) > 1 { - errs = append(errs, xerrors.New("Currently multiple ScanTechniques are not supported.")) + errs = append(errs, errors.New("currently multiple ScanTechniques are not supported")) } if c.HasPrivileged { if os.Geteuid() != 0 { output, err := exec.Command("getcap", c.ScannerBinPath).Output() if err != nil { - errs = append(errs, xerrors.Errorf("Failed to check capability of %s. error message: %w", c.ScannerBinPath, err)) + errs = append(errs, fmt.Errorf("Failed to check capability of %s. error message: %w", c.ScannerBinPath, err)) } else { parseOutput := strings.SplitN(string(output), "=", 2) if len(parseOutput) != 2 { - errs = append(errs, xerrors.Errorf("Failed to parse getcap outputs. please execute this command: `$ getcap %s`. If the following string (`/usr/bin/nmap = ... `) is not displayed, you need to set the capability with the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", c.ScannerBinPath, c.ScannerBinPath)) + errs = append(errs, fmt.Errorf("Failed to parse getcap outputs. please execute this command: `$ getcap %s`. If the following string (`/usr/bin/nmap = ... `) is not displayed, you need to set the capability with the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", c.ScannerBinPath, c.ScannerBinPath)) } else { parseCapability := strings.Split(strings.TrimSpace(parseOutput[1]), "+") capabilities := strings.Split(parseCapability[0], ",") @@ -160,12 +161,12 @@ func (c *PortScanConf) Validate() (errs []error) { continue } - errs = append(errs, xerrors.Errorf("Not enough capability to execute. needs: ['cap_net_bind_service', 'cap_net_admin', 'cap_net_raw'], actual: %s. To fix this, run the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", capabilities, c.ScannerBinPath)) + errs = append(errs, fmt.Errorf("Not enough capability to execute. needs: ['cap_net_bind_service', 'cap_net_admin', 'cap_net_raw'], actual: %s. To fix this, run the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", capabilities, c.ScannerBinPath)) break } if parseCapability[1] != "eip" { - errs = append(errs, xerrors.Errorf("Capability(`cap_net_bind_service,cap_net_admin,cap_net_raw`) must belong to the following capability set(need: eip, actual: %s). To fix this, run the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", parseCapability[1], c.ScannerBinPath)) + errs = append(errs, fmt.Errorf("Capability(`cap_net_bind_service,cap_net_admin,cap_net_raw`) must belong to the following capability set(need: eip, actual: %s). To fix this, run the following command. `$ setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip %s`", parseCapability[1], c.ScannerBinPath)) } } } @@ -175,7 +176,7 @@ func (c *PortScanConf) Validate() (errs []error) { if !c.HasPrivileged { for _, scanTechnique := range scanTechniques { if scanTechnique != TCPConnect && scanTechnique != NotSupportTechnique { - errs = append(errs, xerrors.New("If not privileged, only TCPConnect Scan(-sT) can be used.")) + errs = append(errs, errors.New("if not privileged, only TCPConnect Scan(-sT) can be used")) break } } @@ -183,19 +184,19 @@ func (c *PortScanConf) Validate() (errs []error) { if c.SourcePort != "" { if slices.Contains(scanTechniques, TCPConnect) { - errs = append(errs, xerrors.New("SourcePort Option(-g/--source-port) is incompatible with the default TCPConnect Scan(-sT).")) + errs = append(errs, errors.New("sourcePort option(-g/--source-port) is incompatible with the default TCPConnect Scan(-sT)")) } portNumber, err := strconv.Atoi(c.SourcePort) if err != nil { - errs = append(errs, xerrors.Errorf("SourcePort conversion failed. %w", err)) + errs = append(errs, fmt.Errorf("SourcePort conversion failed. %w", err)) } else { if portNumber < 0 || 65535 < portNumber { - errs = append(errs, xerrors.Errorf("SourcePort(%s) must be between 0 and 65535.", c.SourcePort)) + errs = append(errs, fmt.Errorf("sourcePort(%s) must be between 0 and 65535", c.SourcePort)) } if portNumber == 0 { - errs = append(errs, xerrors.New("SourcePort(0) may not work on all systems.")) + errs = append(errs, errors.New("sourcePort(0) may not work on all systems")) } } } diff --git a/config/saasconf.go b/config/saasconf.go index 8d219a504a..d7cf100703 100644 --- a/config/saasconf.go +++ b/config/saasconf.go @@ -1,8 +1,9 @@ package config import ( + "errors" + "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // SaasConf is FutureVuls config @@ -15,15 +16,15 @@ type SaasConf struct { // Validate validates configuration func (c *SaasConf) Validate() (errs []error) { if c.GroupID == 0 { - errs = append(errs, xerrors.New("GroupID must not be empty")) + errs = append(errs, errors.New("GroupID must not be empty")) } if len(c.Token) == 0 { - errs = append(errs, xerrors.New("Token must not be empty")) + errs = append(errs, errors.New("Token must not be empty")) } if len(c.URL) == 0 { - errs = append(errs, xerrors.New("URL must not be empty")) + errs = append(errs, errors.New("URL must not be empty")) } _, err := govalidator.ValidateStruct(c) diff --git a/config/scanmode.go b/config/scanmode.go index 86d2efbef7..79b701f537 100644 --- a/config/scanmode.go +++ b/config/scanmode.go @@ -1,9 +1,9 @@ package config import ( + "errors" + "fmt" "strings" - - "golang.org/x/xerrors" ) // ScanMode has a type of scan mode. fast, fast-root, deep and offline @@ -62,9 +62,9 @@ func (s *ScanMode) ensure() error { if numTrue == 0 { s.Set(Fast) } else if s.IsDeep() && s.IsOffline() { - return xerrors.New("Don't specify both of deep and offline") + return errors.New("Don't specify both of deep and offline") } else if numTrue != 1 { - return xerrors.New("Specify only one of offline, fast, fast-root or deep") + return errors.New("Specify only one of offline, fast, fast-root or deep") } return nil } @@ -99,12 +99,12 @@ func setScanMode(server *ServerInfo) error { case offlineStr: server.Mode.Set(Offline) default: - return xerrors.Errorf("scanMode: %s of %s is invalid. Specify -fast, -fast-root, -deep or offline", + return fmt.Errorf("scanMode: %s of %s is invalid. Specify -fast, -fast-root, -deep or offline", m, server.ServerName) } } if err := server.Mode.ensure(); err != nil { - return xerrors.Errorf("%s in %s", err, server.ServerName) + return fmt.Errorf("%s in %s", err, server.ServerName) } return nil } diff --git a/config/scanmodule.go b/config/scanmodule.go index d0fd7f8868..eade7e69e4 100644 --- a/config/scanmodule.go +++ b/config/scanmodule.go @@ -1,9 +1,9 @@ package config import ( + "errors" + "fmt" "strings" - - "golang.org/x/xerrors" ) // ScanModule has a type of scan module @@ -66,7 +66,7 @@ func (s *ScanModule) ensure() error { s.Set(Lockfile) s.Set(Port) } else if !s.IsScanOSPkg() && s.IsScanPort() { - return xerrors.New("When specifying the Port, Specify OSPkg as well") + return errors.New("When specifying the Port, Specify OSPkg as well") } return nil } @@ -86,12 +86,12 @@ func setScanModules(server *ServerInfo, d ServerInfo) error { case portStr: server.Module.Set(Port) default: - return xerrors.Errorf("scanMode: %s of %s is invalid. Specify %s", + return fmt.Errorf("scanMode: %s of %s is invalid. Specify %s", m, server.ServerName, allModules) } } if err := server.Module.ensure(); err != nil { - return xerrors.Errorf("%s in %s", err, server.ServerName) + return fmt.Errorf("%s in %s", err, server.ServerName) } return nil } diff --git a/config/slackconf.go b/config/slackconf.go index 797ed32bdc..c83d125af8 100644 --- a/config/slackconf.go +++ b/config/slackconf.go @@ -1,10 +1,11 @@ package config import ( + "errors" + "fmt" "strings" "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // SlackConf is slack config @@ -26,19 +27,19 @@ func (c *SlackConf) Validate() (errs []error) { } if len(c.HookURL) == 0 && len(c.LegacyToken) == 0 { - errs = append(errs, xerrors.New("slack.hookURL or slack.LegacyToken must not be empty")) + errs = append(errs, errors.New("slack.hookURL or slack.LegacyToken must not be empty")) } if len(c.Channel) == 0 { - errs = append(errs, xerrors.New("slack.channel must not be empty")) + errs = append(errs, errors.New("slack.channel must not be empty")) } else { if !strings.HasPrefix(c.Channel, "#") && c.Channel != "${servername}" { - errs = append(errs, xerrors.Errorf("channel's prefix must be '#', channel: %s", c.Channel)) + errs = append(errs, fmt.Errorf("channel's prefix must be '#', channel: %s", c.Channel)) } } if len(c.AuthUser) == 0 { - errs = append(errs, xerrors.New("slack.authUser must not be empty")) + errs = append(errs, errors.New("slack.authUser must not be empty")) } _, err := govalidator.ValidateStruct(c) diff --git a/config/smtpconf.go b/config/smtpconf.go index 8dd462fb62..9d7773beca 100644 --- a/config/smtpconf.go +++ b/config/smtpconf.go @@ -1,8 +1,10 @@ package config import ( + "errors" + "fmt" + "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // SMTPConf is smtp config @@ -26,7 +28,7 @@ func checkEmails(emails []string) (errs []error) { return } if ok := govalidator.IsEmail(addr); !ok { - errs = append(errs, xerrors.Errorf("Invalid email address. email: %s", addr)) + errs = append(errs, fmt.Errorf("Invalid email address. email: %s", addr)) } } return @@ -47,21 +49,21 @@ func (c *SMTPConf) Validate() (errs []error) { } if c.SMTPAddr == "" { - errs = append(errs, xerrors.New("email.smtpAddr must not be empty")) + errs = append(errs, errors.New("email.smtpAddr must not be empty")) } if c.SMTPPort == "" { - errs = append(errs, xerrors.New("email.smtpPort must not be empty")) + errs = append(errs, errors.New("email.smtpPort must not be empty")) } switch c.TLSMode { case "", "None", "STARTTLS", "SMTPS": default: - errs = append(errs, xerrors.New(`email.tlsMode accepts ["", "None", "STARTTLS", "SMTPS"]`)) + errs = append(errs, errors.New(`email.tlsMode accepts ["", "None", "STARTTLS", "SMTPS"]`)) } if len(c.To) == 0 { - errs = append(errs, xerrors.New("email.To required at least one address")) + errs = append(errs, errors.New("email.To required at least one address")) } if len(c.From) == 0 { - errs = append(errs, xerrors.New("email.From required at least one address")) + errs = append(errs, errors.New("email.From required at least one address")) } _, err := govalidator.ValidateStruct(c) diff --git a/config/syslog/syslogconf.go b/config/syslog/syslogconf.go index de26d0f840..7bbb864b10 100644 --- a/config/syslog/syslogconf.go +++ b/config/syslog/syslogconf.go @@ -4,10 +4,10 @@ package syslog import ( "errors" + "fmt" "log/syslog" "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // Validate validates configuration @@ -63,7 +63,7 @@ func (c *Conf) GetSeverity() (syslog.Priority, error) { case "debug": return syslog.LOG_DEBUG, nil default: - return -1, xerrors.Errorf("Invalid severity: %s", c.Severity) + return -1, fmt.Errorf("Invalid severity: %s", c.Severity) } } @@ -115,6 +115,6 @@ func (c *Conf) GetFacility() (syslog.Priority, error) { case "local7": return syslog.LOG_LOCAL7, nil default: - return -1, xerrors.Errorf("Invalid facility: %s", c.Facility) + return -1, fmt.Errorf("Invalid facility: %s", c.Facility) } } diff --git a/config/syslog/syslogconf_windows.go b/config/syslog/syslogconf_windows.go index 6ce1bd755b..ba6e7cc30d 100644 --- a/config/syslog/syslogconf_windows.go +++ b/config/syslog/syslogconf_windows.go @@ -2,12 +2,12 @@ package syslog -import "golang.org/x/xerrors" +import "errors" // Validate validates configuration func (c *Conf) Validate() (errs []error) { if !c.Enabled { return nil } - return []error{xerrors.New("windows not support syslog")} + return []error{errors.New("windows not support syslog")} } diff --git a/config/telegramconf.go b/config/telegramconf.go index 349a7067df..c3ac3e11f7 100644 --- a/config/telegramconf.go +++ b/config/telegramconf.go @@ -1,8 +1,9 @@ package config import ( + "errors" + "github.com/asaskevich/govalidator" - "golang.org/x/xerrors" ) // TelegramConf is Telegram config @@ -18,11 +19,11 @@ func (c *TelegramConf) Validate() (errs []error) { return } if len(c.ChatID) == 0 { - errs = append(errs, xerrors.New("TelegramConf.ChatID must not be empty")) + errs = append(errs, errors.New("TelegramConf.ChatID must not be empty")) } if len(c.Token) == 0 { - errs = append(errs, xerrors.New("TelegramConf.Token must not be empty")) + errs = append(errs, errors.New("TelegramConf.Token must not be empty")) } _, err := govalidator.ValidateStruct(c) diff --git a/config/tomlloader.go b/config/tomlloader.go index a2503e9a5f..1026c52f41 100644 --- a/config/tomlloader.go +++ b/config/tomlloader.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "maps" "net" @@ -12,7 +13,6 @@ import ( "github.com/BurntSushi/toml" "github.com/c-robinson/iplib" "github.com/knqyf263/go-cpe/naming" - "golang.org/x/xerrors" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/logging" @@ -31,7 +31,7 @@ func (c TOMLLoader) Load(pathToToml string) error { if ConfV1.Version != "v2" && runtime.GOOS == "windows" { logging.Log.Infof("An outdated version of config.toml was detected. Converting to newer version...") if err := convertToLatestConfig(pathToToml); err != nil { - return xerrors.Errorf("Failed to convert to latest config. err: %w", err) + return fmt.Errorf("Failed to convert to latest config. err: %w", err) } } else if _, err := toml.DecodeFile(pathToToml, &Conf); err != nil { return err @@ -54,26 +54,26 @@ func (c TOMLLoader) Load(pathToToml string) error { server.BaseName = name if server.Type != constant.ServerTypePseudo && server.Host == "" { - return xerrors.New("Failed to find hosts. err: server.host is empty") + return errors.New("Failed to find hosts. err: server.host is empty") } serverHosts, err := hosts(server.Host, server.IgnoreIPAddresses) if err != nil { - return xerrors.Errorf("Failed to find hosts. err: %w", err) + return fmt.Errorf("Failed to find hosts. err: %w", err) } if len(serverHosts) == 0 { - return xerrors.New("Failed to find hosts. err: zero enumerated hosts") + return errors.New("Failed to find hosts. err: zero enumerated hosts") } if err := setDefaultIfEmpty(&server); err != nil { - return xerrors.Errorf("Failed to set default value to config. server: %s, err: %w", name, err) + return fmt.Errorf("Failed to set default value to config. server: %s, err: %w", name, err) } if err := setScanMode(&server); err != nil { - return xerrors.Errorf("Failed to set ScanMode: %w", err) + return fmt.Errorf("Failed to set ScanMode: %w", err) } if err := setScanModules(&server, Conf.Default); err != nil { - return xerrors.Errorf("Failed to set ScanModule: %w", err) + return fmt.Errorf("Failed to set ScanModule: %w", err) } if len(server.CpeNames) == 0 { @@ -82,7 +82,7 @@ func (c TOMLLoader) Load(pathToToml string) error { for i, n := range server.CpeNames { uri, err := toCpeURI(n) if err != nil { - return xerrors.Errorf("Failed to parse CPENames %s in %s, err: %w", n, name, err) + return fmt.Errorf("Failed to parse CPENames %s in %s, err: %w", n, name, err) } server.CpeNames[i] = uri } @@ -103,24 +103,24 @@ func (c TOMLLoader) Load(pathToToml string) error { for _, reg := range server.IgnorePkgsRegexp { _, err := regexp.Compile(reg) if err != nil { - return xerrors.Errorf("Failed to parse %s in %s. err: %w", reg, name, err) + return fmt.Errorf("Failed to parse %s in %s. err: %w", reg, name, err) } } for contName, cont := range server.Containers { for _, reg := range cont.IgnorePkgsRegexp { _, err := regexp.Compile(reg) if err != nil { - return xerrors.Errorf("Failed to parse %s in %s@%s. err: %w", reg, contName, name, err) + return fmt.Errorf("Failed to parse %s in %s@%s. err: %w", reg, contName, name, err) } } } for ownerRepo, githubSetting := range server.GitHubRepos { if ss := strings.Split(ownerRepo, "/"); len(ss) != 2 { - return xerrors.Errorf("Failed to parse GitHub owner/repo: %s in %s", ownerRepo, name) + return fmt.Errorf("Failed to parse GitHub owner/repo: %s in %s", ownerRepo, name) } if githubSetting.Token == "" { - return xerrors.Errorf("GitHub owner/repo: %s in %s token is empty", ownerRepo, name) + return fmt.Errorf("GitHub owner/repo: %s in %s token is empty", ownerRepo, name) } } @@ -132,7 +132,7 @@ func (c TOMLLoader) Load(pathToToml string) error { case "base", "updates": // nop default: - return xerrors.Errorf("For now, enablerepo have to be base or updates: %s", server.Enablerepo) + return fmt.Errorf("For now, enablerepo have to be base or updates: %s", server.Enablerepo) } } @@ -162,7 +162,7 @@ func hosts(host string, ignores []string) ([]string, error) { hostMap := map[string]struct{}{} hosts, err := enumerateHosts(host) if err != nil { - return nil, xerrors.Errorf("Failed to enumarate hosts. err: %w", err) + return nil, fmt.Errorf("Failed to enumarate hosts. err: %w", err) } for _, host := range hosts { hostMap[host] = struct{}{} @@ -171,10 +171,10 @@ func hosts(host string, ignores []string) ([]string, error) { for _, ignore := range ignores { hosts, err := enumerateHosts(ignore) if err != nil { - return nil, xerrors.Errorf("Failed to enumarate hosts. err: %w", err) + return nil, fmt.Errorf("Failed to enumarate hosts. err: %w", err) } if len(hosts) == 1 && net.ParseIP(hosts[0]) == nil { - return nil, xerrors.Errorf("Failed to ignore hosts. err: a non-IP address has been entered in ignoreIPAddress") + return nil, fmt.Errorf("Failed to ignore hosts. err: a non-IP address has been entered in ignoreIPAddress") } for _, host := range hosts { delete(hostMap, host) @@ -195,7 +195,7 @@ func enumerateHosts(host string) ([]string, error) { ipAddr, ipNet, err := net.ParseCIDR(host) if err != nil { - return nil, xerrors.Errorf("Failed to parse CIDR. err: %w", err) + return nil, fmt.Errorf("Failed to parse CIDR. err: %w", err) } maskLen, _ := ipNet.Mask.Size() @@ -208,7 +208,7 @@ func enumerateHosts(host string) ([]string, error) { } else if net.ParseIP(ipAddr.String()).To16() != nil { n := iplib.NewNet6(ipAddr, int(maskLen), 0) if !n.Count().IsInt64() { - return nil, xerrors.Errorf("Failed to enumerate IP address. err: mask bitsize too big") + return nil, fmt.Errorf("Failed to enumerate IP address. err: mask bitsize too big") } for _, addr := range n.Enumerate(int(n.Count().Int64()), 0) { addrs = append(addrs, addr.String()) @@ -324,5 +324,5 @@ func toCpeURI(cpename string) (string, error) { } return naming.BindToURI(wfn), nil } - return "", xerrors.Errorf("Unknown CPE format: %s", cpename) + return "", fmt.Errorf("Unknown CPE format: %s", cpename) } diff --git a/config/vulnDictConf.go b/config/vulnDictConf.go index ea17044dd9..a095d3e52a 100644 --- a/config/vulnDictConf.go +++ b/config/vulnDictConf.go @@ -9,7 +9,6 @@ import ( "github.com/asaskevich/govalidator" "github.com/future-architect/vuls/logging" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" ) // VulnDictInterface is an interface of vulnsrc @@ -80,11 +79,11 @@ func (cnf VulnDict) Validate() error { switch cnf.Type { case "sqlite3": if cnf.URL != "" { - return xerrors.Errorf("To use SQLite3, specify %s.type=sqlite3 and %s.SQLite3Path. To use as HTTP server mode, specify %s.type=http and %s.url", + return fmt.Errorf("To use SQLite3, specify %s.type=sqlite3 and %s.SQLite3Path. To use as HTTP server mode, specify %s.type=http and %s.url", cnf.Name, cnf.Name, cnf.Name, cnf.Name) } if ok, _ := govalidator.IsFilePath(cnf.SQLite3Path); !ok { - return xerrors.Errorf("SQLite3 path must be a *Absolute* file path. %s.SQLite3Path: %s", + return fmt.Errorf("SQLite3 path must be a *Absolute* file path. %s.SQLite3Path: %s", cnf.Name, cnf.SQLite3Path) } if _, err := os.Stat(cnf.SQLite3Path); os.IsNotExist(err) { @@ -92,22 +91,22 @@ func (cnf VulnDict) Validate() error { } case "mysql": if cnf.URL == "" { - return xerrors.Errorf(`MySQL connection string is needed. %s.url="user:pass@tcp(localhost:3306)/dbname"`, cnf.Name) + return fmt.Errorf(`MySQL connection string is needed. %s.url="user:pass@tcp(localhost:3306)/dbname"`, cnf.Name) } case "postgres": if cnf.URL == "" { - return xerrors.Errorf(`PostgreSQL connection string is needed. %s.url="host=myhost user=user dbname=dbname sslmode=disable password=password"`, cnf.Name) + return fmt.Errorf(`PostgreSQL connection string is needed. %s.url="host=myhost user=user dbname=dbname sslmode=disable password=password"`, cnf.Name) } case "redis": if cnf.URL == "" { - return xerrors.Errorf(`Redis connection string is needed. %s.url="redis://localhost/0"`, cnf.Name) + return fmt.Errorf(`Redis connection string is needed. %s.url="redis://localhost/0"`, cnf.Name) } case "http": if cnf.URL == "" { - return xerrors.Errorf(`URL is needed. -%s-url="http://localhost:1323"`, cnf.Name) + return fmt.Errorf(`URL is needed. -%s-url="http://localhost:1323"`, cnf.Name) } default: - return xerrors.Errorf("%s.type must be either 'sqlite3', 'mysql', 'postgres', 'redis' or 'http'. %s.type: %s", cnf.Name, cnf.Name, cnf.Type) + return fmt.Errorf("%s.type must be either 'sqlite3', 'mysql', 'postgres', 'redis' or 'http'. %s.type: %s", cnf.Name, cnf.Name, cnf.Type) } return nil } @@ -140,7 +139,7 @@ func (cnf VulnDict) CheckHTTPHealth() error { resp, _, errs := gorequest.New().Timeout(10 * time.Second).SetDebug(Conf.Debug).Get(url).End() // resp, _, errs = gorequest.New().Proxy(api.httpProxy).Get(url).End() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("Failed to request to CVE server. url: %s, errs: %s", + return fmt.Errorf("Failed to request to CVE server. url: %s, errs: %s", url, errs) } return nil diff --git a/config/windows.go b/config/windows.go index d15417dd79..60993bc83c 100644 --- a/config/windows.go +++ b/config/windows.go @@ -1,8 +1,6 @@ package config -import ( - "golang.org/x/xerrors" -) +import "fmt" // WindowsConf used for Windows Update Setting type WindowsConf struct { @@ -15,7 +13,7 @@ func (c *WindowsConf) Validate() []error { switch c.ServerSelection { case 0, 1, 2, 3: default: - return []error{xerrors.Errorf("ServerSelection: %d does not support . Reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-uamg/07e2bfa4-6795-4189-b007-cc50b476181a", c.ServerSelection)} + return []error{fmt.Errorf("ServerSelection: %d does not support . Reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-uamg/07e2bfa4-6795-4189-b007-cc50b476181a", c.ServerSelection)} } return nil } diff --git a/contrib/owasp-dependency-check/parser/parser.go b/contrib/owasp-dependency-check/parser/parser.go index 2efbc4615b..f58f804637 100644 --- a/contrib/owasp-dependency-check/parser/parser.go +++ b/contrib/owasp-dependency-check/parser/parser.go @@ -2,6 +2,7 @@ package parser import ( "encoding/xml" + "fmt" "io" "os" "slices" @@ -9,7 +10,6 @@ import ( "github.com/knqyf263/go-cpe/naming" log "github.com/sirupsen/logrus" - "golang.org/x/xerrors" ) type analysis struct { @@ -48,7 +48,7 @@ func Parse(path string) ([]string, error) { var anal analysis if err := xml.Unmarshal(b, &anal); err != nil { - return nil, xerrors.Errorf("Failed to unmarshal: %s", err) + return nil, fmt.Errorf("Failed to unmarshal: %s", err) } cpes := []string{} diff --git a/contrib/trivy/parser/parser.go b/contrib/trivy/parser/parser.go index 2fd37d03f9..28657a7a6f 100644 --- a/contrib/trivy/parser/parser.go +++ b/contrib/trivy/parser/parser.go @@ -3,10 +3,10 @@ package parser import ( "encoding/json" + "fmt" v2 "github.com/future-architect/vuls/contrib/trivy/parser/v2" "github.com/future-architect/vuls/models" - "golang.org/x/xerrors" ) // Parser is a parser interface @@ -23,12 +23,12 @@ type Report struct { func NewParser(vulnJSON []byte) (Parser, error) { r := Report{} if err := json.Unmarshal(vulnJSON, &r); err != nil { - return nil, xerrors.Errorf("Failed to parse JSON. Please use the latest version of trivy, trivy-to-vuls and future-vuls") + return nil, fmt.Errorf("Failed to parse JSON. Please use the latest version of trivy, trivy-to-vuls and future-vuls") } switch r.SchemaVersion { case 2: return v2.ParserV2{}, nil default: - return nil, xerrors.Errorf("Failed to parse trivy json. SchemeVersion %d is not supported yet. Please contact support", r.SchemaVersion) + return nil, fmt.Errorf("Failed to parse trivy json. SchemeVersion %d is not supported yet. Please contact support", r.SchemaVersion) } } diff --git a/contrib/trivy/parser/v2/parser.go b/contrib/trivy/parser/v2/parser.go index 085e730653..e436849514 100644 --- a/contrib/trivy/parser/v2/parser.go +++ b/contrib/trivy/parser/v2/parser.go @@ -2,11 +2,11 @@ package v2 import ( "encoding/json" + "fmt" "regexp" "time" "github.com/aquasecurity/trivy/pkg/types" - "golang.org/x/xerrors" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/contrib/trivy/pkg" @@ -39,7 +39,7 @@ var dockerTagPattern = regexp.MustCompile(`^(.*):(.*)$`) func setScanResultMeta(scanResult *models.ScanResult, report *types.Report) error { if len(report.Results) == 0 { - return xerrors.Errorf("scanned images or libraries are not supported by Trivy. see https://aquasecurity.github.io/trivy/dev/docs/coverage/os/, https://aquasecurity.github.io/trivy/dev/docs/coverage/language/") + return fmt.Errorf("scanned images or libraries are not supported by Trivy. see https://aquasecurity.github.io/trivy/dev/docs/coverage/os/, https://aquasecurity.github.io/trivy/dev/docs/coverage/language/") } scanResult.ServerName = report.ArtifactName diff --git a/contrib/trivy/parser/v2/parser_test.go b/contrib/trivy/parser/v2/parser_test.go index 2756badce3..45c639da6f 100644 --- a/contrib/trivy/parser/v2/parser_test.go +++ b/contrib/trivy/parser/v2/parser_test.go @@ -1,11 +1,11 @@ package v2 import ( + "fmt" "testing" "time" "github.com/d4l3k/messagediff" - "golang.org/x/xerrors" "github.com/future-architect/vuls/models" ) @@ -3126,7 +3126,7 @@ func TestParseError(t *testing.T) { }{ "image hello-world": { vulnJSON: helloWorldTrivy, - expected: xerrors.Errorf("scanned images or libraries are not supported by Trivy. see https://aquasecurity.github.io/trivy/dev/docs/coverage/os/, https://aquasecurity.github.io/trivy/dev/docs/coverage/language/"), + expected: fmt.Errorf("scanned images or libraries are not supported by Trivy. see https://aquasecurity.github.io/trivy/dev/docs/coverage/os/, https://aquasecurity.github.io/trivy/dev/docs/coverage/language/"), }, } diff --git a/detector/cti.go b/detector/cti.go index 4684e40f3f..9f1d49adbf 100644 --- a/detector/cti.go +++ b/detector/cti.go @@ -5,12 +5,12 @@ package detector import ( "encoding/json" "errors" + "fmt" "net/http" "time" "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -36,12 +36,12 @@ func (client goCTIDBClient) closeDB() error { func newGoCTIDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goCTIDBClient, error) { if err := ctilog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set go-cti logger. err: %w", err) + return nil, fmt.Errorf("Failed to set go-cti logger. err: %w", err) } db, err := newCTIDB(cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newCTIDB. err: %w", err) + return nil, fmt.Errorf("Failed to newCTIDB. err: %w", err) } return &goCTIDBClient{driver: db, baseURL: cnf.GetURL()}, nil } @@ -91,7 +91,7 @@ func FillWithCTI(r *models.ScanResult, cnf config.CtiConf, logOpts logging.LogOp } techniqueIDs, err := client.driver.GetTechniqueIDsByCveID(cveID) if err != nil { - return xerrors.Errorf("Failed to get CTIs by CVE-ID. err: %w", err) + return fmt.Errorf("Failed to get CTIs by CVE-ID. err: %w", err) } if len(techniqueIDs) == 0 { continue @@ -158,11 +158,11 @@ func getCTIsViaHTTP(cveIDs []string, urlPrefix string) (responses []ctiResponse, case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching CTI") + return nil, errors.New("Timeout Fetching CTI") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch CTI. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch CTI. err: %w", errors.Join(errs...)) } return } @@ -187,7 +187,7 @@ func httpGetCTI(url string, req ctiRequest, resChan chan<- ctiResponse, errChan if count == retryMax { return nil } - return xerrors.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -195,11 +195,11 @@ func httpGetCTI(url string, req ctiRequest, resChan chan<- ctiResponse, errChan logging.Log.Warnf("Failed to HTTP GET. retrying in %f seconds. err: %+v", t.Seconds(), err) } if err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify); err != nil { - errChan <- xerrors.Errorf("HTTP Error %w", err) + errChan <- fmt.Errorf("HTTP Error %w", err) return } if count == retryMax { - errChan <- xerrors.New("Retry count exceeded") + errChan <- errors.New("Retry count exceeded") return } @@ -220,9 +220,9 @@ func newCTIDB(cnf config.VulnDictInterface) (ctidb.DB, error) { driver, err := ctidb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), ctidb.Option{}) if err != nil { if errors.Is(err, ctidb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init cti DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init cti DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init cti DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init cti DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/detector/cve_client.go b/detector/cve_client.go index 8f475b4528..9fe79cf6e3 100644 --- a/detector/cve_client.go +++ b/detector/cve_client.go @@ -11,7 +11,6 @@ import ( "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -28,12 +27,12 @@ type goCveDictClient struct { func newGoCveDictClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goCveDictClient, error) { if err := cvelog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set go-cve-dictionary logger. err: %w", err) + return nil, fmt.Errorf("Failed to set go-cve-dictionary logger. err: %w", err) } driver, err := newCveDB(cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newCveDB. err: %w", err) + return nil, fmt.Errorf("Failed to newCveDB. err: %w", err) } return &goCveDictClient{driver: driver, baseURL: cnf.GetURL()}, nil } @@ -92,17 +91,17 @@ func (client goCveDictClient) fetchCveDetails(cveIDs []string) (cveDetails []cve case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching CVE") + return nil, errors.New("Timeout Fetching CVE") } } if len(errs) != 0 { return nil, - xerrors.Errorf("Failed to fetch CVE. err: %w", errs) + fmt.Errorf("Failed to fetch CVE. err: %w", errors.Join(errs...)) } } else { m, err := client.driver.GetMulti(cveIDs) if err != nil { - return nil, xerrors.Errorf("Failed to GetMulti. err: %w", err) + return nil, fmt.Errorf("Failed to GetMulti. err: %w", err) } for _, v := range m { cveDetails = append(cveDetails, v) @@ -122,7 +121,7 @@ func httpGet(key, url string, resChan chan<- response, errChan chan<- error) { } resp, body, errs = req.End() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("HTTP GET Error, url: %s, resp: %v, err: %+v", + return fmt.Errorf("HTTP GET Error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil @@ -132,12 +131,12 @@ func httpGet(key, url string, resChan chan<- response, errChan chan<- error) { } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - errChan <- xerrors.Errorf("HTTP Error: %w", err) + errChan <- fmt.Errorf("HTTP Error: %w", err) return } cveDetail := cvemodels.CveDetail{} if err := json.Unmarshal([]byte(body), &cveDetail); err != nil { - errChan <- xerrors.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) + errChan <- fmt.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) return } resChan <- response{ @@ -150,17 +149,17 @@ func (client goCveDictClient) detectCveByCpeURI(cpeURI string, useJVN bool) (cve if client.driver == nil { url, err := util.URLPathJoin(client.baseURL, "cpes") if err != nil { - return nil, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return nil, fmt.Errorf("Failed to join URLPath. err: %w", err) } query := map[string]string{"name": cpeURI} logging.Log.Debugf("HTTP Request to %s, query: %#v", url, query) if cves, err = httpPost(url, query); err != nil { - return nil, xerrors.Errorf("Failed to post HTTP Request. err: %w", err) + return nil, fmt.Errorf("Failed to post HTTP Request. err: %w", err) } } else { if cves, err = client.driver.GetByCpeURI(cpeURI); err != nil { - return nil, xerrors.Errorf("Failed to get CVEs by CPEURI. err: %w", err) + return nil, fmt.Errorf("Failed to get CVEs by CPEURI. err: %w", err) } } @@ -193,7 +192,7 @@ func httpPost(url string, query map[string]string) ([]cvemodels.CveDetail, error } resp, body, errs = req.End() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -202,13 +201,13 @@ func httpPost(url string, query map[string]string) ([]cvemodels.CveDetail, error } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - return nil, xerrors.Errorf("HTTP Error: %w", err) + return nil, fmt.Errorf("HTTP Error: %w", err) } cveDetails := []cvemodels.CveDetail{} if err := json.Unmarshal([]byte(body), &cveDetails); err != nil { return nil, - xerrors.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) + fmt.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) } return cveDetails, nil } @@ -224,9 +223,9 @@ func newCveDB(cnf config.VulnDictInterface) (cvedb.DB, error) { driver, err := cvedb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), cvedb.Option{}) if err != nil { if errors.Is(err, cvedb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init CVE DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init CVE DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init CVE DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init CVE DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/detector/detector.go b/detector/detector.go index f4302dfbf2..999f02d9cf 100644 --- a/detector/detector.go +++ b/detector/detector.go @@ -10,8 +10,6 @@ import ( "strings" "time" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/contrib/owasp-dependency-check/parser" @@ -47,11 +45,11 @@ func Detect(rs []models.ScanResult, dir string) ([]models.ScanResult, error) { } if err := DetectLibsCves(&r, config.Conf.TrivyOpts, config.Conf.LogOpts, config.Conf.NoProgress); err != nil { - return nil, xerrors.Errorf("Failed to fill with Library dependency: %w", err) + return nil, fmt.Errorf("Failed to fill with Library dependency: %w", err) } if err := DetectPkgCves(&r, config.Conf.Gost, config.Conf.Vuls2, config.Conf.LogOpts, config.Conf.NoProgress); err != nil { - return nil, xerrors.Errorf("Failed to detect Pkg CVE: %w", err) + return nil, fmt.Errorf("Failed to detect Pkg CVE: %w", err) } cpeURIs, owaspDCXMLPath := []string{}, "" @@ -70,7 +68,7 @@ func Detect(rs []models.ScanResult, dir string) ([]models.ScanResult, error) { if owaspDCXMLPath != "" { cpes, err := parser.Parse(owaspDCXMLPath) if err != nil { - return nil, xerrors.Errorf("Failed to read OWASP Dependency Check XML on %s, `%s`, err: %w", + return nil, fmt.Errorf("Failed to read OWASP Dependency Check XML on %s, `%s`, err: %w", r.ServerInfo(), owaspDCXMLPath, err) } cpeURIs = append(cpeURIs, cpes...) @@ -188,44 +186,44 @@ func Detect(rs []models.ScanResult, dir string) ([]models.ScanResult, error) { } if err := DetectCpeURIsCves(&r, cpes, config.Conf.CveDict, config.Conf.LogOpts); err != nil { - return nil, xerrors.Errorf("Failed to detect CVE of `%s`: %w", cpeURIs, err) + return nil, fmt.Errorf("Failed to detect CVE of `%s`: %w", cpeURIs, err) } repos := config.Conf.Servers[r.ServerName].GitHubRepos if err := DetectGitHubCves(&r, repos); err != nil { - return nil, xerrors.Errorf("Failed to detect GitHub Cves: %w", err) + return nil, fmt.Errorf("Failed to detect GitHub Cves: %w", err) } if err := DetectWordPressCves(&r, config.Conf.WpScan); err != nil { - return nil, xerrors.Errorf("Failed to detect WordPress Cves: %w", err) + return nil, fmt.Errorf("Failed to detect WordPress Cves: %w", err) } if err := gost.FillCVEsWithRedHat(&r, config.Conf.Gost, config.Conf.LogOpts); err != nil { - return nil, xerrors.Errorf("Failed to fill with gost: %w", err) + return nil, fmt.Errorf("Failed to fill with gost: %w", err) } if err := FillCvesWithGoCVEDictionary(&r, config.Conf.CveDict, config.Conf.LogOpts); err != nil { - return nil, xerrors.Errorf("Failed to fill with CVE: %w", err) + return nil, fmt.Errorf("Failed to fill with CVE: %w", err) } nExploitCve, err := FillWithExploit(&r, config.Conf.Exploit, config.Conf.LogOpts) if err != nil { - return nil, xerrors.Errorf("Failed to fill with exploit: %w", err) + return nil, fmt.Errorf("Failed to fill with exploit: %w", err) } logging.Log.Infof("%s: %d PoC are detected", r.FormatServerName(), nExploitCve) nMetasploitCve, err := FillWithMetasploit(&r, config.Conf.Metasploit, config.Conf.LogOpts) if err != nil { - return nil, xerrors.Errorf("Failed to fill with metasploit: %w", err) + return nil, fmt.Errorf("Failed to fill with metasploit: %w", err) } logging.Log.Infof("%s: %d exploits are detected", r.FormatServerName(), nMetasploitCve) if err := FillWithKEVuln(&r, config.Conf.KEVuln, config.Conf.LogOpts); err != nil { - return nil, xerrors.Errorf("Failed to fill with Known Exploited Vulnerabilities: %w", err) + return nil, fmt.Errorf("Failed to fill with Known Exploited Vulnerabilities: %w", err) } if err := FillWithCTI(&r, config.Conf.Cti, config.Conf.LogOpts); err != nil { - return nil, xerrors.Errorf("Failed to fill with Cyber Threat Intelligences: %w", err) + return nil, fmt.Errorf("Failed to fill with Cyber Threat Intelligences: %w", err) } FillCweDict(&r) @@ -249,14 +247,14 @@ func Detect(rs []models.ScanResult, dir string) ([]models.ScanResult, error) { } //TODO don't call here if err := reporter.OverwriteJSONFile(dir, r); err != nil { - return nil, xerrors.Errorf("Failed to write JSON: %w", err) + return nil, fmt.Errorf("Failed to write JSON: %w", err) } } if config.Conf.DiffPlus || config.Conf.DiffMinus { prevs, err := loadPrevious(rs, config.Conf.ResultsDir) if err != nil { - return nil, xerrors.Errorf("Failed to load previous results. err: %w", err) + return nil, fmt.Errorf("Failed to load previous results. err: %w", err) } rs = diff(rs, prevs, config.Conf.DiffPlus, config.Conf.DiffMinus) } @@ -324,14 +322,14 @@ func DetectPkgCves(r *models.ScanResult, gostCnf config.GostConf, vuls2Conf conf constant.OpenSUSE, constant.OpenSUSELeap, constant.SUSEEnterpriseServer, constant.SUSEEnterpriseDesktop, constant.Debian, constant.Raspbian, constant.Ubuntu, constant.Alpine: if err := vuls2.Detect(r, vuls2Conf, noProgress); err != nil { - return xerrors.Errorf("Failed to detect CVE with Vuls2: %w", err) + return fmt.Errorf("Failed to detect CVE with Vuls2: %w", err) } case constant.Windows: if err := detectPkgsCvesWithGost(gostCnf, r, logOpts); err != nil { - return xerrors.Errorf("Failed to detect CVE with gost: %w", err) + return fmt.Errorf("Failed to detect CVE with gost: %w", err) } default: - return xerrors.Errorf("Unsupported detection methods for %s", r.Family) + return fmt.Errorf("Unsupported detection methods for %s", r.Family) } } @@ -402,18 +400,18 @@ func DetectGitHubCves(r *models.ScanResult, githubConfs map[string]config.GitHub for ownerRepo, setting := range githubConfs { ss := strings.Split(ownerRepo, "/") if len(ss) != 2 { - return xerrors.Errorf("Failed to parse GitHub owner/repo: %s", ownerRepo) + return fmt.Errorf("Failed to parse GitHub owner/repo: %s", ownerRepo) } owner, repo := ss[0], ss[1] n, err := DetectGitHubSecurityAlerts(r, owner, repo, setting.Token, setting.IgnoreGitHubDismissed) if err != nil { - return xerrors.Errorf("Failed to access GitHub Security Alerts: %w", err) + return fmt.Errorf("Failed to access GitHub Security Alerts: %w", err) } logging.Log.Infof("%s: %d CVEs detected with GHSA %s/%s", r.FormatServerName(), n, owner, repo) if err = DetectGitHubDependencyGraph(r, owner, repo, setting.Token); err != nil { - return xerrors.Errorf("Failed to access GitHub Dependency graph: %w", err) + return fmt.Errorf("Failed to access GitHub Dependency graph: %w", err) } } return nil @@ -427,7 +425,7 @@ func DetectWordPressCves(r *models.ScanResult, wpCnf config.WpScanConf) error { logging.Log.Infof("%s: Detect WordPress CVE. Number of pkgs: %d ", r.ServerInfo(), len(r.WordPressPackages)) n, err := detectWordPressCves(r, wpCnf) if err != nil { - return xerrors.Errorf("Failed to detect WordPress CVE: %w", err) + return fmt.Errorf("Failed to detect WordPress CVE: %w", err) } logging.Log.Infof("%s: found %d WordPress CVEs", r.FormatServerName(), n) return nil @@ -442,7 +440,7 @@ func FillCvesWithGoCVEDictionary(r *models.ScanResult, cnf config.GoCveDictConf, client, err := newGoCveDictClient(&cnf, logOpts) if err != nil { - return xerrors.Errorf("Failed to newGoCveDictClient. err: %w", err) + return fmt.Errorf("Failed to newGoCveDictClient. err: %w", err) } defer func() { if err := client.closeDB(); err != nil { @@ -452,7 +450,7 @@ func FillCvesWithGoCVEDictionary(r *models.ScanResult, cnf config.GoCveDictConf, ds, err := client.fetchCveDetails(cveIDs) if err != nil { - return xerrors.Errorf("Failed to fetchCveDetails. err: %w", err) + return fmt.Errorf("Failed to fetchCveDetails. err: %w", err) } for _, d := range ds { @@ -531,7 +529,7 @@ func fillCertAlerts(cvedetail *cvemodels.CveDetail) (dict models.AlertDict) { func detectPkgsCvesWithGost(cnf config.GostConf, r *models.ScanResult, logOpts logging.LogOpts) error { client, err := gost.NewGostClient(cnf, r.Family, logOpts) if err != nil { - return xerrors.Errorf("Failed to new a gost client: %w", err) + return fmt.Errorf("Failed to new a gost client: %w", err) } defer func() { if err := client.CloseDB(); err != nil { @@ -541,7 +539,7 @@ func detectPkgsCvesWithGost(cnf config.GostConf, r *models.ScanResult, logOpts l nCVEs, err := client.DetectCVEs(r, true) if err != nil { - return xerrors.Errorf("Failed to detect CVEs with gost: %w", err) + return fmt.Errorf("Failed to detect CVEs with gost: %w", err) } logging.Log.Infof("%s: %d CVEs are detected with gost", r.FormatServerName(), nCVEs) @@ -553,7 +551,7 @@ func detectPkgsCvesWithGost(cnf config.GostConf, r *models.ScanResult, logOpts l func DetectCpeURIsCves(r *models.ScanResult, cpes []Cpe, cnf config.GoCveDictConf, logOpts logging.LogOpts) error { client, err := newGoCveDictClient(&cnf, logOpts) if err != nil { - return xerrors.Errorf("Failed to newGoCveDictClient. err: %w", err) + return fmt.Errorf("Failed to newGoCveDictClient. err: %w", err) } defer func() { if err := client.closeDB(); err != nil { @@ -565,7 +563,7 @@ func DetectCpeURIsCves(r *models.ScanResult, cpes []Cpe, cnf config.GoCveDictCon for _, cpe := range cpes { details, err := client.detectCveByCpeURI(cpe.CpeURI, cpe.UseJVN) if err != nil { - return xerrors.Errorf("Failed to detectCveByCpeURI. err: %w", err) + return fmt.Errorf("Failed to detectCveByCpeURI. err: %w", err) } for _, detail := range details { diff --git a/detector/exploitdb.go b/detector/exploitdb.go index 7b4b32a2b7..f88cba9b94 100644 --- a/detector/exploitdb.go +++ b/detector/exploitdb.go @@ -5,12 +5,12 @@ package detector import ( "encoding/json" "errors" + "fmt" "net/http" "time" "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -37,12 +37,12 @@ func (client goExploitDBClient) closeDB() error { func newGoExploitDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goExploitDBClient, error) { if err := exploitlog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set go-exploitdb logger. err: %w", err) + return nil, fmt.Errorf("Failed to set go-exploitdb logger. err: %w", err) } db, err := newExploitDB(cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newExploitDB. err: %w", err) + return nil, fmt.Errorf("Failed to newExploitDB. err: %w", err) } return &goExploitDBClient{driver: db, baseURL: cnf.GetURL()}, nil } @@ -51,7 +51,7 @@ func newGoExploitDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goE func FillWithExploit(r *models.ScanResult, cnf config.ExploitConf, logOpts logging.LogOpts) (nExploitCve int, err error) { client, err := newGoExploitDBClient(&cnf, logOpts) if err != nil { - return 0, xerrors.Errorf("Failed to newGoExploitDBClient. err: %w", err) + return 0, fmt.Errorf("Failed to newGoExploitDBClient. err: %w", err) } defer func() { if err := client.closeDB(); err != nil { @@ -66,16 +66,16 @@ func FillWithExploit(r *models.ScanResult, cnf config.ExploitConf, logOpts loggi } prefix, err := util.URLPathJoin(client.baseURL, "cves") if err != nil { - return 0, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return 0, fmt.Errorf("Failed to join URLPath. err: %w", err) } responses, err := getExploitsViaHTTP(cveIDs, prefix) if err != nil { - return 0, xerrors.Errorf("Failed to get Exploits via HTTP. err: %w", err) + return 0, fmt.Errorf("Failed to get Exploits via HTTP. err: %w", err) } for _, res := range responses { exps := []exploitmodels.Exploit{} if err := json.Unmarshal([]byte(res.json), &exps); err != nil { - return 0, xerrors.Errorf("Failed to unmarshal json. err: %w", err) + return 0, fmt.Errorf("Failed to unmarshal json. err: %w", err) } exploits := ConvertToModelsExploit(exps) v, ok := r.ScannedCves[res.request.cveID] @@ -92,7 +92,7 @@ func FillWithExploit(r *models.ScanResult, cnf config.ExploitConf, logOpts loggi } es, err := client.driver.GetExploitByCveID(cveID) if err != nil { - return 0, xerrors.Errorf("Failed to get Exploits by CVE-ID. err: %w", err) + return 0, fmt.Errorf("Failed to get Exploits by CVE-ID. err: %w", err) } if len(es) == 0 { continue @@ -188,11 +188,11 @@ func getExploitsViaHTTP(cveIDs []string, urlPrefix string) ( case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching Exploit") + return nil, errors.New("Timeout Fetching Exploit") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch Exploit. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch Exploit. err: %w", errors.Join(errs...)) } return } @@ -217,7 +217,7 @@ func httpGetExploit(url string, req exploitRequest, resChan chan<- exploitRespon if count == retryMax { return nil } - return xerrors.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -226,11 +226,11 @@ func httpGetExploit(url string, req exploitRequest, resChan chan<- exploitRespon } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - errChan <- xerrors.Errorf("HTTP Error %w", err) + errChan <- fmt.Errorf("HTTP Error %w", err) return } if count == retryMax { - errChan <- xerrors.New("Retry count exceeded") + errChan <- errors.New("Retry count exceeded") return } @@ -251,9 +251,9 @@ func newExploitDB(cnf config.VulnDictInterface) (exploitdb.DB, error) { driver, err := exploitdb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), exploitdb.Option{}) if err != nil { if errors.Is(err, exploitdb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init exploit DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init exploit DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init exploit DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init exploit DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/detector/javadb/javadb.go b/detector/javadb/javadb.go index 83aca05c57..67bde08fd3 100644 --- a/detector/javadb/javadb.go +++ b/detector/javadb/javadb.go @@ -18,7 +18,6 @@ import ( trivyjavadb "github.com/aquasecurity/trivy/pkg/javadb" "github.com/aquasecurity/trivy/pkg/oci" "github.com/google/go-containerregistry/pkg/name" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -35,11 +34,11 @@ func UpdateJavaDB(trivyOpts config.TrivyOpts, noProgress bool) error { meta, err := metac.Get() if err != nil { if !errors.Is(err, os.ErrNotExist) { - return xerrors.Errorf("Failed to get Java DB metadata. err: %w", err) + return fmt.Errorf("Failed to get Java DB metadata. err: %w", err) } if trivyOpts.TrivySkipJavaDBUpdate { logging.Log.Error("Could not skip, the first run cannot skip downloading Java DB") - return xerrors.New("'--trivy-skip-java-db-update' cannot be specified on the first run") + return errors.New("'--trivy-skip-java-db-update' cannot be specified on the first run") } } @@ -77,7 +76,7 @@ func UpdateJavaDB(trivyOpts config.TrivyOpts, noProgress bool) error { return ref, nil }() if err != nil { - return xerrors.Errorf("invalid javadb repository: %w", err) + return fmt.Errorf("invalid javadb repository: %w", err) } refs = append(refs, ref) } @@ -88,19 +87,19 @@ func UpdateJavaDB(trivyOpts config.TrivyOpts, noProgress bool) error { MediaType: "application/vnd.aquasec.trivy.javadb.layer.v1.tar+gzip", Quiet: noProgress, }); err != nil { - return xerrors.Errorf("Failed to download Trivy Java DB. err: %w", err) + return fmt.Errorf("Failed to download Trivy Java DB. err: %w", err) } // Parse the newly downloaded metadata.json meta, err = metac.Get() if err != nil { - return xerrors.Errorf("Failed to get Trivy Java DB metadata. err: %w", err) + return fmt.Errorf("Failed to get Trivy Java DB metadata. err: %w", err) } // Update DownloadedAt meta.DownloadedAt = time.Now().UTC() if err = metac.Update(meta); err != nil { - return xerrors.Errorf("Failed to update Trivy Java DB metadata. err: %w", err) + return fmt.Errorf("Failed to update Trivy Java DB metadata. err: %w", err) } return nil @@ -129,7 +128,7 @@ type DBClient struct { func NewClient(cacheDBDir string) (*DBClient, error) { driver, err := db.New(filepath.Join(cacheDBDir, "java-db")) if err != nil { - return nil, xerrors.Errorf("Failed to open Trivy Java DB. err: %w", err) + return nil, fmt.Errorf("Failed to open Trivy Java DB. err: %w", err) } return &DBClient{driver: driver}, nil } @@ -147,10 +146,10 @@ func (client *DBClient) Close() error { func (client *DBClient) SearchBySHA1(sha1 string) (jar.Properties, error) { index, err := client.driver.SelectIndexBySha1(sha1) if err != nil { - return jar.Properties{}, xerrors.Errorf("Failed to select from Trivy Java DB. err: %w", err) + return jar.Properties{}, fmt.Errorf("Failed to select from Trivy Java DB. err: %w", err) } if index.ArtifactID == "" { - return jar.Properties{}, xerrors.Errorf("Failed to search ArtifactID by digest %s. err: %w", sha1, jar.ArtifactNotFoundErr) + return jar.Properties{}, fmt.Errorf("Failed to search ArtifactID by digest %s. err: %w", sha1, jar.ArtifactNotFoundErr) } return jar.Properties{ GroupID: index.GroupID, diff --git a/detector/kevuln.go b/detector/kevuln.go index 603ffc0f30..e2d9fd8bf6 100644 --- a/detector/kevuln.go +++ b/detector/kevuln.go @@ -5,12 +5,12 @@ package detector import ( "encoding/json" "errors" + "fmt" "net/http" "time" "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -36,12 +36,12 @@ func (client goKEVulnDBClient) closeDB() error { func newGoKEVulnDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goKEVulnDBClient, error) { if err := kevulnlog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set go-kev logger. err: %w", err) + return nil, fmt.Errorf("Failed to set go-kev logger. err: %w", err) } db, err := newKEVulnDB(cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newKEVulnDB. err: %w", err) + return nil, fmt.Errorf("Failed to newKEVulnDB. err: %w", err) } return &goKEVulnDBClient{driver: db, baseURL: cnf.GetURL()}, nil } @@ -156,7 +156,7 @@ func FillWithKEVuln(r *models.ScanResult, cnf config.KEVulnConf, logOpts logging } kev, err := client.driver.GetKEVByCveID(cveID) if err != nil { - return xerrors.Errorf("Failed to get kev by %s", cveID) + return fmt.Errorf("Failed to get kev by %s", cveID) } if len(kev.CISA) == 0 && len(kev.VulnCheck) == 0 { continue @@ -288,11 +288,11 @@ func getKEVulnsViaHTTP(cveIDs []string, urlPrefix string) ( case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching KEVuln") + return nil, errors.New("Timeout Fetching KEVuln") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch KEVuln. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch KEVuln. err: %w", errors.Join(errs...)) } return } @@ -317,7 +317,7 @@ func httpGetKEVuln(url string, req kevulnRequest, resChan chan<- kevulnResponse, if count == retryMax { return nil } - return xerrors.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -326,11 +326,11 @@ func httpGetKEVuln(url string, req kevulnRequest, resChan chan<- kevulnResponse, } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - errChan <- xerrors.Errorf("HTTP Error %w", err) + errChan <- fmt.Errorf("HTTP Error %w", err) return } if count == retryMax { - errChan <- xerrors.New("Retry count exceeded") + errChan <- errors.New("Retry count exceeded") return } @@ -351,9 +351,9 @@ func newKEVulnDB(cnf config.VulnDictInterface) (kevulndb.DB, error) { driver, err := kevulndb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), kevulndb.Option{}) if err != nil { if errors.Is(err, kevulndb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init kevuln DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init kevuln DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init kevuln DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init kevuln DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/detector/library.go b/detector/library.go index 74f8390612..5057a4bc11 100644 --- a/detector/library.go +++ b/detector/library.go @@ -22,7 +22,6 @@ import ( "github.com/aquasecurity/trivy/pkg/types" "github.com/google/go-containerregistry/pkg/name" "github.com/samber/lo" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/detector/javadb" @@ -51,10 +50,10 @@ func DetectLibsCves(r *models.ScanResult, trivyOpts config.TrivyOpts, logOpts lo logging.Log.Info("Updating library db...") if err := downloadDB("", trivyOpts, noProgress, false); err != nil { - return xerrors.Errorf("Failed to download trivy DB. err: %w", err) + return fmt.Errorf("Failed to download trivy DB. err: %w", err) } if err := trivydb.Init(filepath.Join(trivyOpts.TrivyCacheDBDir, "db")); err != nil { - return xerrors.Errorf("Failed to init trivy DB. err: %w", err) + return fmt.Errorf("Failed to init trivy DB. err: %w", err) } defer trivydb.Close() @@ -68,12 +67,12 @@ func DetectLibsCves(r *models.ScanResult, trivyOpts config.TrivyOpts, logOpts lo if lib.Type == ftypes.Jar { if javaDBClient == nil { if err := javadb.UpdateJavaDB(trivyOpts, noProgress); err != nil { - return xerrors.Errorf("Failed to update Trivy Java DB. err: %w", err) + return fmt.Errorf("Failed to update Trivy Java DB. err: %w", err) } javaDBClient, err = javadb.NewClient(trivyOpts.TrivyCacheDBDir) if err != nil { - return xerrors.Errorf("Failed to open Trivy Java DB. err: %w", err) + return fmt.Errorf("Failed to open Trivy Java DB. err: %w", err) } } d.javaDBClient = javaDBClient @@ -81,7 +80,7 @@ func DetectLibsCves(r *models.ScanResult, trivyOpts config.TrivyOpts, logOpts lo vinfos, err := d.scan() if err != nil { - return xerrors.Errorf("Failed to scan library. err: %w", err) + return fmt.Errorf("Failed to scan library. err: %w", err) } r.LibraryScanners[i] = d.scanner for _, vinfo := range vinfos { @@ -126,7 +125,7 @@ func downloadDB(appVersion string, trivyOpts config.TrivyOpts, noProgress, skipU return ref, nil }() if err != nil { - return xerrors.Errorf("invalid db repository: %w", err) + return fmt.Errorf("invalid db repository: %w", err) } refs = append(refs, ref) } @@ -134,20 +133,20 @@ func downloadDB(appVersion string, trivyOpts config.TrivyOpts, noProgress, skipU ctx := context.Background() needsUpdate, err := client.NeedsUpdate(ctx, appVersion, skipUpdate) if err != nil { - return xerrors.Errorf("Failed to check NeedsUpdate. err: %w", err) + return fmt.Errorf("Failed to check NeedsUpdate. err: %w", err) } if needsUpdate { logging.Log.Info("Need to update DB") logging.Log.Infof("Downloading DB from %s...", strings.Join(trivyOpts.TrivyDBRepositories, ", ")) if err := client.Download(ctx, filepath.Join(trivyOpts.TrivyCacheDBDir, "db"), ftypes.RegistryOptions{}); err != nil { - return xerrors.Errorf("Failed to download vulnerability DB. err: %w", err) + return fmt.Errorf("Failed to download vulnerability DB. err: %w", err) } } // for debug if err := showDBInfo(trivyOpts.TrivyCacheDBDir); err != nil { - return xerrors.Errorf("Failed to show database info. err: %w", err) + return fmt.Errorf("Failed to show database info. err: %w", err) } return nil } @@ -156,7 +155,7 @@ func showDBInfo(cacheDir string) error { m := metadata.NewClient(filepath.Join(cacheDir, "db")) meta, err := m.Get() if err != nil { - return xerrors.Errorf("Failed to get DB metadata. err: %w", err) + return fmt.Errorf("Failed to get DB metadata. err: %w", err) } logging.Log.Debugf("DB Schema: %d, UpdatedAt: %s, NextUpdate: %s, DownloadedAt: %s", meta.Version, meta.UpdatedAt, meta.NextUpdate, meta.DownloadedAt) @@ -167,12 +166,12 @@ func showDBInfo(cacheDir string) error { func (d *libraryDetector) scan() ([]models.VulnInfo, error) { if d.scanner.Type == ftypes.Jar { if err := d.improveJARInfo(); err != nil { - return nil, xerrors.Errorf("Failed to improve JAR information by trivy Java DB. err: %w", err) + return nil, fmt.Errorf("Failed to improve JAR information by trivy Java DB. err: %w", err) } } scanner, ok := library.NewDriver(d.scanner.Type) if !ok { - return nil, xerrors.Errorf("Failed to new a library driver for %s", d.scanner.Type) + return nil, fmt.Errorf("Failed to new a library driver for %s", d.scanner.Type) } var vulnerabilities = []models.VulnInfo{} for _, pkg := range d.scanner.Libs { @@ -182,7 +181,7 @@ func (d *libraryDetector) scan() ([]models.VulnInfo, error) { tvulns, err := scanner.DetectVulnerabilities("", pkg.Name, pkg.Version) if err != nil { - return nil, xerrors.Errorf("Failed to detect %s vulnerabilities. err: %w", scanner.Type(), err) + return nil, fmt.Errorf("Failed to detect %s vulnerabilities. err: %w", scanner.Type(), err) } if len(tvulns) == 0 { continue @@ -214,7 +213,7 @@ func (d *libraryDetector) improveJARInfo() error { foundProps, err := d.javaDBClient.SearchBySHA1(sha1) if err != nil { if !errors.Is(err, jar.ArtifactNotFoundErr) { - return xerrors.Errorf("Failed to search trivy Java DB. err: %w", err) + return fmt.Errorf("Failed to search trivy Java DB. err: %w", err) } logging.Log.Debugf("No record in Java DB for %s by SHA1: %s", l.FilePath, sha1) diff --git a/detector/msf.go b/detector/msf.go index 9b081baaa8..02933570d9 100644 --- a/detector/msf.go +++ b/detector/msf.go @@ -5,12 +5,12 @@ package detector import ( "encoding/json" "errors" + "fmt" "net/http" "time" "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -37,12 +37,12 @@ func (client goMetasploitDBClient) closeDB() error { func newGoMetasploitDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (*goMetasploitDBClient, error) { if err := metasploitlog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set go-msfdb logger. err: %w", err) + return nil, fmt.Errorf("Failed to set go-msfdb logger. err: %w", err) } db, err := newMetasploitDB(cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newMetasploitDB. err: %w", err) + return nil, fmt.Errorf("Failed to newMetasploitDB. err: %w", err) } return &goMetasploitDBClient{driver: db, baseURL: cnf.GetURL()}, nil } @@ -51,7 +51,7 @@ func newGoMetasploitDBClient(cnf config.VulnDictInterface, o logging.LogOpts) (* func FillWithMetasploit(r *models.ScanResult, cnf config.MetasploitConf, logOpts logging.LogOpts) (nMetasploitCve int, err error) { client, err := newGoMetasploitDBClient(&cnf, logOpts) if err != nil { - return 0, xerrors.Errorf("Failed to newGoMetasploitDBClient. err: %w", err) + return 0, fmt.Errorf("Failed to newGoMetasploitDBClient. err: %w", err) } defer func() { if err := client.closeDB(); err != nil { @@ -66,16 +66,16 @@ func FillWithMetasploit(r *models.ScanResult, cnf config.MetasploitConf, logOpts } prefix, err := util.URLPathJoin(client.baseURL, "cves") if err != nil { - return 0, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return 0, fmt.Errorf("Failed to join URLPath. err: %w", err) } responses, err := getMetasploitsViaHTTP(cveIDs, prefix) if err != nil { - return 0, xerrors.Errorf("Failed to get Metasploits via HTTP. err: %w", err) + return 0, fmt.Errorf("Failed to get Metasploits via HTTP. err: %w", err) } for _, res := range responses { msfs := []metasploitmodels.Metasploit{} if err := json.Unmarshal([]byte(res.json), &msfs); err != nil { - return 0, xerrors.Errorf("Failed to unmarshal json. err: %w", err) + return 0, fmt.Errorf("Failed to unmarshal json. err: %w", err) } metasploits := ConvertToModelsMsf(msfs) v, ok := r.ScannedCves[res.request.cveID] @@ -92,7 +92,7 @@ func FillWithMetasploit(r *models.ScanResult, cnf config.MetasploitConf, logOpts } ms, err := client.driver.GetModuleByCveID(cveID) if err != nil { - return 0, xerrors.Errorf("Failed to get Metasploits by CVE-ID. err: %w", err) + return 0, fmt.Errorf("Failed to get Metasploits by CVE-ID. err: %w", err) } if len(ms) == 0 { continue @@ -159,11 +159,11 @@ func getMetasploitsViaHTTP(cveIDs []string, urlPrefix string) ( case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching Metasploit") + return nil, errors.New("Timeout Fetching Metasploit") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch Metasploit. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch Metasploit. err: %w", errors.Join(errs...)) } return } @@ -188,7 +188,7 @@ func httpGetMetasploit(url string, req metasploitRequest, resChan chan<- metaspl if count == retryMax { return nil } - return xerrors.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -197,11 +197,11 @@ func httpGetMetasploit(url string, req metasploitRequest, resChan chan<- metaspl } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - errChan <- xerrors.Errorf("HTTP Error %w", err) + errChan <- fmt.Errorf("HTTP Error %w", err) return } if count == retryMax { - errChan <- xerrors.New("Retry count exceeded") + errChan <- errors.New("Retry count exceeded") return } @@ -242,9 +242,9 @@ func newMetasploitDB(cnf config.VulnDictInterface) (metasploitdb.DB, error) { driver, err := metasploitdb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), metasploitdb.Option{}) if err != nil { if errors.Is(err, metasploitdb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init metasploit DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init metasploit DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init metasploit DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init metasploit DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/detector/util.go b/detector/util.go index fe94cc0814..1e72d8eb3f 100644 --- a/detector/util.go +++ b/detector/util.go @@ -17,7 +17,6 @@ import ( "github.com/future-architect/vuls/gost" "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" - "golang.org/x/xerrors" ) func reuseScannedCves(r *models.ScanResult) bool { @@ -221,7 +220,7 @@ func isCveInfoUpdated(cveID string, previous, current models.ScanResult) bool { func ListValidJSONDirs(resultsDir string) (dirs []string, err error) { dirInfo, err := os.ReadDir(resultsDir) if err != nil { - return nil, xerrors.Errorf("Failed to read %s: %w", config.Conf.ResultsDir, err) + return nil, fmt.Errorf("Failed to read %s: %w", config.Conf.ResultsDir, err) } for _, d := range dirInfo { if !d.IsDir() { @@ -246,11 +245,11 @@ func loadOneServerScanResult(jsonFile string) (*models.ScanResult, error) { err error ) if data, err = os.ReadFile(jsonFile); err != nil { - return nil, xerrors.Errorf("Failed to read %s: %w", jsonFile, err) + return nil, fmt.Errorf("Failed to read %s: %w", jsonFile, err) } result := &models.ScanResult{} if err := json.Unmarshal(data, result); err != nil { - return nil, xerrors.Errorf("Failed to parse %s: %w", jsonFile, err) + return nil, fmt.Errorf("Failed to parse %s: %w", jsonFile, err) } for k, v := range result.ScannedCves { @@ -266,50 +265,50 @@ func loadOneServerScanResult(jsonFile string) (*models.ScanResult, error) { func ValidateDBs(cveConf config.GoCveDictConf, gostConf config.GostConf, exploitConf config.ExploitConf, metasploitConf config.MetasploitConf, kevulnConf config.KEVulnConf, ctiConf config.CtiConf, logOpts logging.LogOpts) error { cvec, err := newGoCveDictClient(&cveConf, logOpts) if err != nil { - return xerrors.Errorf("Failed to new CVE client. err: %w", err) + return fmt.Errorf("Failed to new CVE client. err: %w", err) } if err := cvec.closeDB(); err != nil { - return xerrors.Errorf("Failed to close CVE DB. err: %w", err) + return fmt.Errorf("Failed to close CVE DB. err: %w", err) } gostc, err := gost.NewGostClient(gostConf, constant.ServerTypePseudo, logOpts) if err != nil { - return xerrors.Errorf("Failed to new gost client. err: %w", err) + return fmt.Errorf("Failed to new gost client. err: %w", err) } if err := gostc.CloseDB(); err != nil { - return xerrors.Errorf("Failed to close gost DB. err: %w", err) + return fmt.Errorf("Failed to close gost DB. err: %w", err) } exploitc, err := newGoExploitDBClient(&exploitConf, logOpts) if err != nil { - return xerrors.Errorf("Failed to new exploit client. err: %w", err) + return fmt.Errorf("Failed to new exploit client. err: %w", err) } if err := exploitc.closeDB(); err != nil { - return xerrors.Errorf("Failed to close exploit DB. err: %w", err) + return fmt.Errorf("Failed to close exploit DB. err: %w", err) } metasploitc, err := newGoMetasploitDBClient(&metasploitConf, logOpts) if err != nil { - return xerrors.Errorf("Failed to new metasploit client. err: %w", err) + return fmt.Errorf("Failed to new metasploit client. err: %w", err) } if err := metasploitc.closeDB(); err != nil { - return xerrors.Errorf("Failed to close metasploit DB. err: %w", err) + return fmt.Errorf("Failed to close metasploit DB. err: %w", err) } kevulnc, err := newGoKEVulnDBClient(&kevulnConf, logOpts) if err != nil { - return xerrors.Errorf("Failed to new KEVuln client. err: %w", err) + return fmt.Errorf("Failed to new KEVuln client. err: %w", err) } if err := kevulnc.closeDB(); err != nil { - return xerrors.Errorf("Failed to close KEVuln DB. err: %w", err) + return fmt.Errorf("Failed to close KEVuln DB. err: %w", err) } ctic, err := newGoCTIDBClient(&ctiConf, logOpts) if err != nil { - return xerrors.Errorf("Failed to new CTI client. err: %w", err) + return fmt.Errorf("Failed to new CTI client. err: %w", err) } if err := ctic.closeDB(); err != nil { - return xerrors.Errorf("Failed to close CTI DB. err: %w", err) + return fmt.Errorf("Failed to close CTI DB. err: %w", err) } return nil diff --git a/detector/vuls2/db.go b/detector/vuls2/db.go index 5db800993d..f6d749bd65 100644 --- a/detector/vuls2/db.go +++ b/detector/vuls2/db.go @@ -1,13 +1,13 @@ package vuls2 import ( + "fmt" "os" "path/filepath" "time" "github.com/pkg/errors" bolt "go.etcd.io/bbolt" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -27,13 +27,13 @@ var ( func newDBConfig(vuls2Conf config.Vuls2Conf, noProgress bool) (*session.Config, error) { willDownload, err := shouldDownload(vuls2Conf, time.Now()) if err != nil { - return nil, xerrors.Errorf("Failed to check whether to download vuls2 db. err: %w", err) + return nil, fmt.Errorf("Failed to check whether to download vuls2 db. err: %w", err) } if willDownload { logging.Log.Infof("Fetching vuls2 db. repository: %s", vuls2Conf.Repository) if err := fetch.Fetch(fetch.WithRepository(vuls2Conf.Repository), fetch.WithDBPath(vuls2Conf.Path), fetch.WithNoProgress(noProgress)); err != nil { - return nil, xerrors.Errorf("Failed to fetch vuls2 db. err: %w", err) + return nil, fmt.Errorf("Failed to fetch vuls2 db. err: %w", err) } } @@ -43,27 +43,27 @@ func newDBConfig(vuls2Conf config.Vuls2Conf, noProgress bool) (*session.Config, Options: session.StorageOptions{BoltDB: &bolt.Options{ReadOnly: true}}, }).New() if err != nil { - return nil, xerrors.Errorf("Failed to new vuls2 db connection. path: %s, err: %w", vuls2Conf.Path, err) + return nil, fmt.Errorf("Failed to new vuls2 db connection. path: %s, err: %w", vuls2Conf.Path, err) } if err := sesh.Storage().Open(); err != nil { - return nil, xerrors.Errorf("Failed to open vuls2 db. path: %s, err: %w", vuls2Conf.Path, err) + return nil, fmt.Errorf("Failed to open vuls2 db. path: %s, err: %w", vuls2Conf.Path, err) } defer sesh.Storage().Close() metadata, err := sesh.Storage().GetMetadata() if err != nil { - return nil, xerrors.Errorf("Failed to get vuls2 db metadata. path: %s, err: %w", vuls2Conf.Path, err) + return nil, fmt.Errorf("Failed to get vuls2 db metadata. path: %s, err: %w", vuls2Conf.Path, err) } if metadata == nil { - return nil, xerrors.Errorf("unexpected vuls2 db metadata. metadata: nil, path: %s", vuls2Conf.Path) + return nil, fmt.Errorf("unexpected vuls2 db metadata. metadata: nil, path: %s", vuls2Conf.Path) } sv, err := session.SchemaVersion("boltdb") if err != nil { - return nil, xerrors.Errorf("Failed to get schema version. err: %w", err) + return nil, fmt.Errorf("Failed to get schema version. err: %w", err) } if metadata.SchemaVersion != sv { - return nil, xerrors.Errorf("vuls2 db schema version mismatch. expected: %d, actual: %d", session.SchemaVersion, metadata.SchemaVersion) + return nil, fmt.Errorf("vuls2 db schema version mismatch. expected: %d, actual: %d", sv, metadata.SchemaVersion) } return &session.Config{ @@ -78,11 +78,11 @@ func shouldDownload(vuls2Conf config.Vuls2Conf, now time.Time) (bool, error) { if _, err := os.Stat(vuls2Conf.Path); err != nil { if errors.Is(err, os.ErrNotExist) { if vuls2Conf.SkipUpdate { - return false, xerrors.Errorf("%s not found, cannot skip update", vuls2Conf.Path) + return false, fmt.Errorf("%s not found, cannot skip update", vuls2Conf.Path) } return true, nil } - return false, xerrors.Errorf("Failed to stat vuls2 db file. err: %w", err) + return false, fmt.Errorf("Failed to stat vuls2 db file. err: %w", err) } sesh, err := (&session.Config{ @@ -91,30 +91,30 @@ func shouldDownload(vuls2Conf config.Vuls2Conf, now time.Time) (bool, error) { Options: session.StorageOptions{BoltDB: &bolt.Options{ReadOnly: true}}, }).New() if err != nil { - return false, xerrors.Errorf("Failed to new vuls2 db connection. path: %s, err: %w", vuls2Conf.Path, err) + return false, fmt.Errorf("Failed to new vuls2 db connection. path: %s, err: %w", vuls2Conf.Path, err) } if err := sesh.Storage().Open(); err != nil { - return false, xerrors.Errorf("Failed to open vuls2 db. path: %s, err: %w", vuls2Conf.Path, err) + return false, fmt.Errorf("Failed to open vuls2 db. path: %s, err: %w", vuls2Conf.Path, err) } defer sesh.Storage().Close() metadata, err := sesh.Storage().GetMetadata() if err != nil { - return false, xerrors.Errorf("Failed to get vuls2 db metadata. path: %s, err: %w", vuls2Conf.Path, err) + return false, fmt.Errorf("Failed to get vuls2 db metadata. path: %s, err: %w", vuls2Conf.Path, err) } if metadata == nil { - return false, xerrors.Errorf("unexpected vuls2 db metadata. metadata: nil, path: %s", vuls2Conf.Path) + return false, fmt.Errorf("unexpected vuls2 db metadata. metadata: nil, path: %s", vuls2Conf.Path) } sv, err := session.SchemaVersion("boltdb") if err != nil { - return false, xerrors.Errorf("Failed to get schema version. err: %w", err) + return false, fmt.Errorf("Failed to get schema version. err: %w", err) } if metadata.SchemaVersion != sv { if vuls2Conf.SkipUpdate { - return false, xerrors.Errorf("vuls2 db schema version mismatch. expected: %d, actual: %d", sv, metadata.SchemaVersion) + return false, fmt.Errorf("vuls2 db schema version mismatch. expected: %d, actual: %d", sv, metadata.SchemaVersion) } return true, nil } diff --git a/detector/vuls2/db_test.go b/detector/vuls2/db_test.go index 99e762fdd2..64a1485ae7 100644 --- a/detector/vuls2/db_test.go +++ b/detector/vuls2/db_test.go @@ -1,13 +1,12 @@ package vuls2_test import ( + "fmt" "path/filepath" "reflect" "testing" "time" - "golang.org/x/xerrors" - "github.com/MaineK00n/vuls2/pkg/db/session" "github.com/MaineK00n/vuls2/pkg/db/session/types" "github.com/future-architect/vuls/config" @@ -157,17 +156,17 @@ func putMetadata(metadata types.Metadata, path string) error { } sesh, err := c.New() if err != nil { - return xerrors.Errorf("c.New(). err: %w", err) + return fmt.Errorf("c.New(). err: %w", err) } if err := sesh.Storage().Open(); err != nil { - return xerrors.Errorf("sesh.Storage().Open(). err: %w", err) + return fmt.Errorf("sesh.Storage().Open(). err: %w", err) } defer sesh.Storage().Close() if err := sesh.Storage().Initialize(); err != nil { - return xerrors.Errorf("sesh.Storage().Initialize(). err: %w", err) + return fmt.Errorf("sesh.Storage().Initialize(). err: %w", err) } if err := sesh.Storage().PutMetadata(metadata); err != nil { - return xerrors.Errorf("sesh.Storage().PutMetadata(). err: %w", err) + return fmt.Errorf("sesh.Storage().PutMetadata(). err: %w", err) } return nil } diff --git a/detector/vuls2/vendor.go b/detector/vuls2/vendor.go index 00a29101ac..b38b4b1775 100644 --- a/detector/vuls2/vendor.go +++ b/detector/vuls2/vendor.go @@ -9,7 +9,6 @@ import ( apk "github.com/knqyf263/go-apk-version" deb "github.com/knqyf263/go-deb-version" rpm "github.com/knqyf263/go-rpm-version" - "golang.org/x/xerrors" criterionTypes "github.com/MaineK00n/vuls-data-update/pkg/extract/types/data/detection/condition/criteria/criterion" noneexistcriterionTypes "github.com/MaineK00n/vuls-data-update/pkg/extract/types/data/detection/condition/criteria/criterion/noneexistcriterion" @@ -245,7 +244,7 @@ func filterCriterion(e ecosystemTypes.Ecosystem, scanned scanTypes.ScanResult, c var accepts []int for _, index := range cn.Accepts.Version { if len(scanned.OSPackages) <= index { - return criterionTypes.FilteredCriterion{}, xerrors.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) + return criterionTypes.FilteredCriterion{}, fmt.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) } if slices.ContainsFunc(m[fmt.Sprintf("%s:%d:%s-%s", models.RenameKernelSourcePackageName(constant.Debian, scanned.OSPackages[index].SrcName), func() int { @@ -299,7 +298,7 @@ func filterCriterion(e ecosystemTypes.Ecosystem, scanned scanTypes.ScanResult, c var accepts []int for _, index := range cn.Accepts.Version { if len(scanned.OSPackages) <= index { - return criterionTypes.FilteredCriterion{}, xerrors.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) + return criterionTypes.FilteredCriterion{}, fmt.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) } if slices.ContainsFunc(m[fmt.Sprintf("%s:%d:%s-%s", models.RenameKernelSourcePackageName(constant.Ubuntu, scanned.OSPackages[index].SrcName), func() int { @@ -411,11 +410,11 @@ func selectFixedIn(rangeType vcAffectedRangeTypes.RangeType, fixed []string) str func comparePackStatus(a, b packStatus) (int, error) { if a.status.Name != b.status.Name { - return 0, xerrors.Errorf("Package names are different. a: %s, b: %s", a.status.Name, b.status.Name) + return 0, fmt.Errorf("Package names are different. a: %s, b: %s", a.status.Name, b.status.Name) } if a.rangeType != vcAffectedRangeTypes.RangeTypeUnknown && b.rangeType != vcAffectedRangeTypes.RangeTypeUnknown && a.rangeType != b.rangeType { - return 0, xerrors.Errorf("Range types are different. a: %s, b: %s", a.rangeType, b.rangeType) + return 0, fmt.Errorf("Range types are different. a: %s, b: %s", a.rangeType, b.rangeType) } return cmp.Or( @@ -479,7 +478,7 @@ func advisoryReference(e ecosystemTypes.Ecosystem, s sourceTypes.SourceID, da mo case sourceTypes.JVNFeedRSS, sourceTypes.JVNFeedDetail: ss := strings.Split(da.AdvisoryID, "-") if len(ss) != 3 { - return models.Reference{}, xerrors.Errorf("unexpected JVNDB ID: %s", da.AdvisoryID) + return models.Reference{}, fmt.Errorf("unexpected JVNDB ID: %s", da.AdvisoryID) } return models.Reference{ Link: fmt.Sprintf("https://jvndb.jvn.jp/ja/contents/%s/%s.html", ss[1], da.AdvisoryID), @@ -510,7 +509,7 @@ func advisoryReference(e ecosystemTypes.Ecosystem, s sourceTypes.SourceID, da mo RefID: da.AdvisoryID, }, nil default: - return models.Reference{}, xerrors.Errorf("unsupported source: %s", s) + return models.Reference{}, fmt.Errorf("unsupported source: %s", s) } case ecosystemTypes.EcosystemTypeEPEL, ecosystemTypes.EcosystemTypeFedora: return models.Reference{ @@ -578,7 +577,7 @@ func advisoryReference(e ecosystemTypes.Ecosystem, s sourceTypes.SourceID, da mo RefID: da.AdvisoryID, }, nil default: - return models.Reference{}, xerrors.Errorf("unsupported family: %s", et) + return models.Reference{}, fmt.Errorf("unsupported family: %s", et) } } diff --git a/detector/vuls2/vuls2.go b/detector/vuls2/vuls2.go index 847301a99a..0c3d084d74 100644 --- a/detector/vuls2/vuls2.go +++ b/detector/vuls2/vuls2.go @@ -13,8 +13,6 @@ import ( "strings" "time" - "golang.org/x/xerrors" - dataTypes "github.com/MaineK00n/vuls-data-update/pkg/extract/types/data" criteriaTypes "github.com/MaineK00n/vuls-data-update/pkg/extract/types/data/detection/condition/criteria" criterionTypes "github.com/MaineK00n/vuls-data-update/pkg/extract/types/data/detection/condition/criteria/criterion" @@ -48,7 +46,7 @@ func Detect(r *models.ScanResult, vuls2Conf config.Vuls2Conf, noProgress bool) e if vuls2Conf.Repository == "" { sv, err := session.SchemaVersion("boltdb") if err != nil { - return xerrors.Errorf("Failed to get schema version. err: %w", err) + return fmt.Errorf("Failed to get schema version. err: %w", err) } vuls2Conf.Repository = fmt.Sprintf("%s:%d", defaultRegistory, sv) @@ -59,24 +57,24 @@ func Detect(r *models.ScanResult, vuls2Conf config.Vuls2Conf, noProgress bool) e dbConfig, err := newDBConfig(vuls2Conf, noProgress) if err != nil { - return xerrors.Errorf("Failed to get new db connection. err: %w", err) + return fmt.Errorf("Failed to get new db connection. err: %w", err) } sesh, err := dbConfig.New() if err != nil { - return xerrors.Errorf("Failed to new db session. err: %w", err) + return fmt.Errorf("Failed to new db session. err: %w", err) } defer sesh.Cache().Close() if err := sesh.Storage().Open(); err != nil { - return xerrors.Errorf("Failed to open db. err: %w", err) + return fmt.Errorf("Failed to open db. err: %w", err) } defer sesh.Storage().Close() metadata, err := sesh.Storage().GetMetadata() if err != nil { - return xerrors.Errorf("Failed to get metadata. err: %w", err) + return fmt.Errorf("Failed to get metadata. err: %w", err) } config.Conf.Vuls2.Digest = metadata.Digest @@ -84,12 +82,12 @@ func Detect(r *models.ScanResult, vuls2Conf config.Vuls2Conf, noProgress bool) e vuls2Detected, err := detect(sesh, vuls2Scanned) if err != nil { - return xerrors.Errorf("Failed to detect. err: %w", err) + return fmt.Errorf("Failed to detect. err: %w", err) } vulnInfos, err := postConvert(vuls2Scanned, vuls2Detected) if err != nil { - return xerrors.Errorf("Failed to post convert. err: %w", err) + return fmt.Errorf("Failed to post convert. err: %w", err) } for cveID, vi := range vulnInfos { @@ -169,7 +167,7 @@ func detect(sesh *session.Session, sr scanTypes.ScanResult) (detectTypes.DetectR if len(sr.OSPackages) > 0 { m, err := ospkg.Detect(sesh.Storage(), sr, runtime.NumCPU()) if err != nil { - return detectTypes.DetectResult{}, xerrors.Errorf("Failed to detect os packages. err: %w", err) + return detectTypes.DetectResult{}, fmt.Errorf("Failed to detect os packages. err: %w", err) } for rootID, d := range m { base := detectTypes.VulnerabilityData{ @@ -187,7 +185,7 @@ func detect(sesh *session.Session, sr scanTypes.ScanResult) (detectTypes.DetectR DataSources: slices.Collect(maps.Keys(d.Contents)), }) if err != nil { - return detectTypes.DetectResult{}, xerrors.Errorf("Failed to get vulnerability data. RootID: %s, err: %w", rootID, err) + return detectTypes.DetectResult{}, fmt.Errorf("Failed to get vulnerability data. RootID: %s, err: %w", rootID, err) } base.Advisories = avs.Advisories @@ -225,7 +223,7 @@ func detect(sesh *session.Session, sr scanTypes.ScanResult) (detectTypes.DetectR for _, sourceID := range sourceIDs { s, err := sesh.Storage().GetDataSource(sourceID) if err != nil { - return detectTypes.DetectResult{}, xerrors.Errorf("Failed to get datasource. sourceID: %s, err: %w", sourceID, err) + return detectTypes.DetectResult{}, fmt.Errorf("Failed to get datasource. sourceID: %s, err: %w", sourceID, err) } datasources = append(datasources, s) } @@ -278,11 +276,11 @@ func postConvert(scanned scanTypes.ScanResult, detected detectTypes.DetectResult m := make(map[source]sourceData) if err := walkVulnerabilityDetections(m, scanned, detected.Detected); err != nil { - return nil, xerrors.Errorf("Failed to walk detections. err: %w", err) + return nil, fmt.Errorf("Failed to walk detections. err: %w", err) } if err := walkVulnerabilityDatas(m, detected.Detected); err != nil { - return nil, xerrors.Errorf("Failed to walk vulnerability data. err: %w", err) + return nil, fmt.Errorf("Failed to walk vulnerability data. err: %w", err) } type affected struct { @@ -315,7 +313,7 @@ func postConvert(scanned scanTypes.ScanResult, detected detectTypes.DetectResult }, }) if err != nil { - return nil, xerrors.Errorf("Failed to compare pack. err: %w", err) + return nil, fmt.Errorf("Failed to compare pack. err: %w", err) } switch result { case 0: @@ -403,7 +401,7 @@ func postConvert(scanned scanTypes.ScanResult, detected detectTypes.DetectResult if ok { merged, err := mergeVulnInfo(base, vi) if err != nil { - return nil, xerrors.Errorf("Failed to merge vuln info. err: %w", err) + return nil, fmt.Errorf("Failed to merge vuln info. err: %w", err) } base = merged } else { @@ -433,12 +431,12 @@ func walkVulnerabilityDetections(m map[source]sourceData, scanned scanTypes.Scan for _, fcond := range fconds { ca, err := pruneCriteria(fcond.Criteria) if err != nil { - return xerrors.Errorf("Failed to prune criteria. err: %w", err) + return fmt.Errorf("Failed to prune criteria. err: %w", err) } statuses, cpes, _, err := walkCriteria(d.Ecosystem, sourceID, ca, fcond.Tag, scanned) if err != nil { - return xerrors.Errorf("Failed to walk criteria. err: %w", err) + return fmt.Errorf("Failed to walk criteria. err: %w", err) } if len(statuses) == 0 && len(cpes) == 0 { continue @@ -483,7 +481,7 @@ func pruneCriteria(c criteriaTypes.FilteredCriteria) (criteriaTypes.FilteredCrit for _, child := range c.Criterias { child, err := pruneCriteria(child) if err != nil { - return criteriaTypes.FilteredCriteria{}, xerrors.Errorf("prune criteria: %w", err) + return criteriaTypes.FilteredCriteria{}, fmt.Errorf("prune criteria: %w", err) } if len(child.Criterias) == 0 && len(child.Criterions) == 0 { @@ -493,7 +491,7 @@ func pruneCriteria(c criteriaTypes.FilteredCriteria) (criteriaTypes.FilteredCrit case criteriaTypes.CriteriaOperatorTypeOR: continue default: - return criteriaTypes.FilteredCriteria{}, xerrors.Errorf("unexpected operator. expected: %q, actual: %q", []criteriaTypes.CriteriaOperatorType{criteriaTypes.CriteriaOperatorTypeAND, criteriaTypes.CriteriaOperatorTypeOR}, c.Operator) + return criteriaTypes.FilteredCriteria{}, fmt.Errorf("unexpected operator. expected: %q, actual: %q", []criteriaTypes.CriteriaOperatorType{criteriaTypes.CriteriaOperatorTypeAND, criteriaTypes.CriteriaOperatorTypeOR}, c.Operator) } } @@ -503,7 +501,7 @@ func pruneCriteria(c criteriaTypes.FilteredCriteria) (criteriaTypes.FilteredCrit for _, cn := range c.Criterions { isAffected, err := cn.Affected() if err != nil { - return criteriaTypes.FilteredCriteria{}, xerrors.Errorf("criterion affected: %w", err) + return criteriaTypes.FilteredCriteria{}, fmt.Errorf("criterion affected: %w", err) } if !isAffected { @@ -513,7 +511,7 @@ func pruneCriteria(c criteriaTypes.FilteredCriteria) (criteriaTypes.FilteredCrit case criteriaTypes.CriteriaOperatorTypeOR: continue default: - return criteriaTypes.FilteredCriteria{}, xerrors.Errorf("unexpected operator. expected: %q, actual: %q", []criteriaTypes.CriteriaOperatorType{criteriaTypes.CriteriaOperatorTypeAND, criteriaTypes.CriteriaOperatorTypeOR}, c.Operator) + return criteriaTypes.FilteredCriteria{}, fmt.Errorf("unexpected operator. expected: %q, actual: %q", []criteriaTypes.CriteriaOperatorType{criteriaTypes.CriteriaOperatorTypeAND, criteriaTypes.CriteriaOperatorTypeOR}, c.Operator) } } @@ -531,7 +529,7 @@ func walkCriteria(e ecosystemTypes.Ecosystem, sourceID sourceTypes.SourceID, ca for _, child := range ca.Criterias { ss, cs, ignore, err := walkCriteria(e, sourceID, child, tag, scanned) if err != nil { - return nil, nil, false, xerrors.Errorf("Failed to walk criteria. err: %w", err) + return nil, nil, false, fmt.Errorf("Failed to walk criteria. err: %w", err) } if ignore { switch ca.Operator { @@ -540,7 +538,7 @@ func walkCriteria(e ecosystemTypes.Ecosystem, sourceID sourceTypes.SourceID, ca case criteriaTypes.CriteriaOperatorTypeOR: continue default: - return nil, nil, false, xerrors.Errorf("unexpected operator: %s", ca.Operator) + return nil, nil, false, fmt.Errorf("unexpected operator: %s", ca.Operator) } } statuses = append(statuses, ss...) @@ -562,7 +560,7 @@ func walkCriteria(e ecosystemTypes.Ecosystem, sourceID sourceTypes.SourceID, ca fcn, err := filterCriterion(e, scanned, cn) if err != nil { - return nil, nil, false, xerrors.Errorf("Failed to filter criterion. err: %w", err) + return nil, nil, false, fmt.Errorf("Failed to filter criterion. err: %w", err) } switch fcn.Criterion.Version.Package.Type { @@ -580,7 +578,7 @@ func walkCriteria(e ecosystemTypes.Ecosystem, sourceID sourceTypes.SourceID, ca for _, index := range fcn.Accepts.Version { if len(scanned.OSPackages) <= index { - return nil, nil, false, xerrors.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) + return nil, nil, false, fmt.Errorf("Too large OSPackage index. len(OSPackage): %d, index: %d", len(scanned.OSPackages), index) } statuses = append(statuses, packStatus{ rangeType: rangeType, @@ -600,7 +598,7 @@ func walkCriteria(e ecosystemTypes.Ecosystem, sourceID sourceTypes.SourceID, ca case vcPackageTypes.PackageTypeCPE: for _, index := range fcn.Accepts.Version { if len(scanned.CPE) <= index { - return nil, nil, false, xerrors.Errorf("Too large CPE index. len(CPE): %d, index: %d", len(scanned.CPE), index) + return nil, nil, false, fmt.Errorf("Too large CPE index. len(CPE): %d, index: %d", len(scanned.CPE), index) } } cpes = append(cpes, string(*fcn.Criterion.Version.Package.CPE)) @@ -616,7 +614,7 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi for _, vda := range vd.Advisories { for sid, rm := range vda.Contents { if rm == nil { - return xerrors.Errorf("advisories map is nil, root id: %q -> advisories[source id: %q]", vd.ID, sid) + return fmt.Errorf("advisories map is nil, root id: %q -> advisories[source id: %q]", vd.ID, sid) } for _, a := range rm[vd.ID] { for _, segment := range a.Segments { @@ -662,7 +660,7 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi for _, vdv := range vd.Vulnerabilities { for sid, rm := range vdv.Contents { if rm == nil { - return xerrors.Errorf("vulnerabilities map is nil, root id: %q -> vulnerabilities[source id: %q]", vd.ID, sid) + return fmt.Errorf("vulnerabilities map is nil, root id: %q -> vulnerabilities[source id: %q]", vd.ID, sid) } for _, v := range rm[vd.ID] { for _, segment := range v.Segments { @@ -683,7 +681,7 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi vinfo, err := func() (models.VulnInfo, error) { bs, err := json.Marshal([]source{src}) if err != nil { - return models.VulnInfo{}, xerrors.Errorf("Failed to marshal sources. err: %w", err) + return models.VulnInfo{}, fmt.Errorf("Failed to marshal sources. err: %w", err) } fdas := filterDistroAdvisories(src.Segment.Ecosystem, am[src]) @@ -697,7 +695,7 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi for _, da := range fdas { ar, err := advisoryReference(src.Segment.Ecosystem, src.SourceID, da) if err != nil { - return models.VulnInfo{}, xerrors.Errorf("Failed to get advisory reference. err: %w", err) + return models.VulnInfo{}, fmt.Errorf("Failed to get advisory reference. err: %w", err) } if !slices.ContainsFunc(rs, func(r models.Reference) bool { return r.Link == ar.Link && r.Source == ar.Source && r.RefID == ar.RefID && slices.Equal(r.Tags, ar.Tags) @@ -750,7 +748,7 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi }, nil }() if err != nil { - return xerrors.Errorf("Failed to create vuln info. err: %w", err) + return fmt.Errorf("Failed to create vuln info. err: %w", err) } base := m[src] @@ -773,14 +771,14 @@ func walkVulnerabilityDatas(m map[source]sourceData, vds []detectTypes.Vulnerabi for _, da := range fdas { bs, err := json.Marshal([]source{src}) if err != nil { - return xerrors.Errorf("Failed to marshal sources. err: %w", err) + return fmt.Errorf("Failed to marshal sources. err: %w", err) } cctype := toCveContentType(src.Segment.Ecosystem, src.SourceID) ar, err := advisoryReference(src.Segment.Ecosystem, src.SourceID, da) if err != nil { - return xerrors.Errorf("Failed to get advisory reference. err: %w", err) + return fmt.Errorf("Failed to get advisory reference. err: %w", err) } vinfo := models.VulnInfo{ @@ -831,7 +829,7 @@ func comparePack(a, b pack) (int, error) { r, err := comparePackStatus(a.packStatus, b.packStatus) if err != nil { - return 0, xerrors.Errorf("Failed to compare pack status. err: %w", err) + return 0, fmt.Errorf("Failed to compare pack status. err: %w", err) } return r, nil @@ -839,7 +837,7 @@ func comparePack(a, b pack) (int, error) { func mergeVulnInfo(a, b models.VulnInfo) (models.VulnInfo, error) { if a.CveID != b.CveID { - return models.VulnInfo{}, xerrors.Errorf("CVE IDs are different. a: %s, b: %s", a.CveID, b.CveID) + return models.VulnInfo{}, fmt.Errorf("CVE IDs are different. a: %s, b: %s", a.CveID, b.CveID) } info := models.VulnInfo{ @@ -881,11 +879,11 @@ func mergeVulnInfo(a, b models.VulnInfo) (models.VulnInfo, error) { if ok { var src1 []source if err := json.Unmarshal([]byte(base.Optional["vuls2-sources"]), &src1); err != nil { - return models.VulnInfo{}, xerrors.Errorf("Failed to unmarshal sources. err: %w", err) + return models.VulnInfo{}, fmt.Errorf("Failed to unmarshal sources. err: %w", err) } var src2 []source if err := json.Unmarshal([]byte(c.Optional["vuls2-sources"]), &src2); err != nil { - return models.VulnInfo{}, xerrors.Errorf("Failed to unmarshal sources. err: %w", err) + return models.VulnInfo{}, fmt.Errorf("Failed to unmarshal sources. err: %w", err) } merged := models.CveContent{ @@ -980,7 +978,7 @@ func mergeVulnInfo(a, b models.VulnInfo) (models.VulnInfo, error) { slices.SortFunc(srcs, compareSource) bs, err := json.Marshal(srcs) if err != nil { - return models.VulnInfo{}, xerrors.Errorf("Failed to marshal sources. err: %w", err) + return models.VulnInfo{}, fmt.Errorf("Failed to marshal sources. err: %w", err) } merged.Optional["vuls2-sources"] = string(bs) diff --git a/detector/wordpress.go b/detector/wordpress.go index ac05542298..2ee9f159bb 100644 --- a/detector/wordpress.go +++ b/detector/wordpress.go @@ -18,7 +18,6 @@ import ( "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" version "github.com/hashicorp/go-version" - "golang.org/x/xerrors" ) // wpCveInfos is for wpscan json @@ -188,7 +187,7 @@ func convertToVinfos(pkgName, body string) (vinfos []models.VulnInfo, err error) // "pkgName" : CVE Detailed data pkgnameCves := map[string]wpCveInfos{} if err = json.Unmarshal([]byte(body), &pkgnameCves); err != nil { - return nil, xerrors.Errorf("Failed to unmarshal %s. err: %w", body, err) + return nil, fmt.Errorf("Failed to unmarshal %s. err: %w", body, err) } for _, v := range pkgnameCves { diff --git a/go.mod b/go.mod index c793fa3a72..8bb50002ee 100644 --- a/go.mod +++ b/go.mod @@ -62,7 +62,6 @@ require ( golang.org/x/sync v0.20.0 golang.org/x/term v0.40.0 golang.org/x/text v0.34.0 - golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da ) require ( @@ -359,6 +358,7 @@ require ( golang.org/x/sys v0.41.0 // indirect golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.42.0 // indirect + golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect google.golang.org/api v0.260.0 // indirect google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect diff --git a/gost/gost.go b/gost/gost.go index 665ca044e0..ca82128cbf 100644 --- a/gost/gost.go +++ b/gost/gost.go @@ -4,8 +4,7 @@ package gost import ( "errors" - - "golang.org/x/xerrors" + "fmt" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" @@ -43,7 +42,7 @@ func FillCVEsWithRedHat(r *models.ScanResult, cnf config.GostConf, o logging.Log db, err := newGostDB(&cnf) if err != nil { - return xerrors.Errorf("Failed to newGostDB. err: %w", err) + return fmt.Errorf("Failed to newGostDB. err: %w", err) } client := RedHat{Base{driver: db, baseURL: cnf.GetURL()}} @@ -58,12 +57,12 @@ func FillCVEsWithRedHat(r *models.ScanResult, cnf config.GostConf, o logging.Log // NewGostClient make Client by family func NewGostClient(cnf config.GostConf, family string, o logging.LogOpts) (Client, error) { if err := gostlog.SetLogger(o.LogToFile, o.LogDir, o.Debug, o.LogJSON); err != nil { - return nil, xerrors.Errorf("Failed to set gost logger. err: %w", err) + return nil, fmt.Errorf("Failed to set gost logger. err: %w", err) } db, err := newGostDB(&cnf) if err != nil { - return nil, xerrors.Errorf("Failed to newGostDB. err: %w", err) + return nil, fmt.Errorf("Failed to newGostDB. err: %w", err) } base := Base{driver: db, baseURL: cnf.GetURL()} @@ -74,9 +73,9 @@ func NewGostClient(cnf config.GostConf, family string, o logging.LogOpts) (Clien return Pseudo{base}, nil default: if family == "" { - return nil, xerrors.New("Probably an error occurred during scanning. Check the error message") + return nil, errors.New("Probably an error occurred during scanning. Check the error message") } - return nil, xerrors.Errorf("Gost for %s is not implemented yet", family) + return nil, fmt.Errorf("Gost for %s is not implemented yet", family) } } @@ -92,9 +91,9 @@ func newGostDB(cnf config.VulnDictInterface) (gostdb.DB, error) { driver, err := gostdb.NewDB(cnf.GetType(), path, cnf.GetDebugSQL(), gostdb.Option{}) if err != nil { if errors.Is(err, gostdb.ErrDBLocked) { - return nil, xerrors.Errorf("Failed to init gost DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) + return nil, fmt.Errorf("Failed to init gost DB. SQLite3: %s is locked. err: %w", cnf.GetSQLite3Path(), err) } - return nil, xerrors.Errorf("Failed to init gost DB. DB Path: %s, err: %w", path, err) + return nil, fmt.Errorf("Failed to init gost DB. DB Path: %s, err: %w", path, err) } return driver, nil } diff --git a/gost/microsoft.go b/gost/microsoft.go index b9c743cd9b..5c562d327d 100644 --- a/gost/microsoft.go +++ b/gost/microsoft.go @@ -5,6 +5,7 @@ package gost import ( "cmp" "encoding/json" + "errors" "fmt" "maps" "net/http" @@ -16,7 +17,6 @@ import ( "github.com/cenkalti/backoff" "github.com/hashicorp/go-version" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -40,7 +40,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err if ms.driver == nil { u, err := util.URLPathJoin(ms.baseURL, "microsoft", "kbs") if err != nil { - return 0, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return 0, fmt.Errorf("Failed to join URLPath. err: %w", err) } content := map[string]any{"applied": applied, "unapplied": unapplied} @@ -54,7 +54,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err } resp, body, errs = req.EndBytes() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) + return fmt.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) } return nil } @@ -62,7 +62,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err logging.Log.Warnf("Failed to HTTP POST. retrying in %f seconds. err: %+v", t.Seconds(), err) } if err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify); err != nil { - return 0, xerrors.Errorf("HTTP Error: %w", err) + return 0, fmt.Errorf("HTTP Error: %w", err) } var r struct { @@ -70,14 +70,14 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err Unapplied []string `json:"unapplied"` } if err := json.Unmarshal(body, &r); err != nil { - return 0, xerrors.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) + return 0, fmt.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) } applied = r.Applied unapplied = r.Unapplied } else { applied, unapplied, err = ms.driver.GetExpandKB(applied, unapplied) if err != nil { - return 0, xerrors.Errorf("Failed to detect CVEs. err: %w", err) + return 0, fmt.Errorf("Failed to detect CVEs. err: %w", err) } } @@ -85,7 +85,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err if ms.driver == nil { u, err := util.URLPathJoin(ms.baseURL, "microsoft", "products") if err != nil { - return 0, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return 0, fmt.Errorf("Failed to join URLPath. err: %w", err) } content := map[string]any{"release": r.Release, "kbs": append(applied, unapplied...)} @@ -99,7 +99,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err } resp, body, errs = req.EndBytes() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) + return fmt.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) } return nil } @@ -107,16 +107,16 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err logging.Log.Warnf("Failed to HTTP POST. retrying in %f seconds. err: %+v", t.Seconds(), err) } if err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify); err != nil { - return 0, xerrors.Errorf("HTTP Error: %w", err) + return 0, fmt.Errorf("HTTP Error: %w", err) } if err := json.Unmarshal(body, &products); err != nil { - return 0, xerrors.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) + return 0, fmt.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) } } else { ps, err := ms.driver.GetRelatedProducts(r.Release, append(applied, unapplied...)) if err != nil { - return 0, xerrors.Errorf("Failed to detect CVEs. err: %w", err) + return 0, fmt.Errorf("Failed to detect CVEs. err: %w", err) } products = ps } @@ -152,7 +152,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err if ms.driver == nil { u, err := util.URLPathJoin(ms.baseURL, "microsoft", "filtered-cves") if err != nil { - return 0, xerrors.Errorf("Failed to join URLPath. err: %w", err) + return 0, fmt.Errorf("Failed to join URLPath. err: %w", err) } content := map[string]any{"products": filtered, "kbs": append(applied, unapplied...)} @@ -166,7 +166,7 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err } resp, body, errs = req.EndBytes() if 0 < len(errs) || resp == nil || resp.StatusCode != 200 { - return xerrors.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) + return fmt.Errorf("HTTP POST error. url: %s, resp: %v, err: %+v", u, resp, errs) } return nil } @@ -174,23 +174,23 @@ func (ms Microsoft) DetectCVEs(r *models.ScanResult, _ bool) (nCVEs int, err err logging.Log.Warnf("Failed to HTTP POST. retrying in %f seconds. err: %+v", t.Seconds(), err) } if err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify); err != nil { - return 0, xerrors.Errorf("HTTP Error: %w", err) + return 0, fmt.Errorf("HTTP Error: %w", err) } if err := json.Unmarshal(body, &cves); err != nil { - return 0, xerrors.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) + return 0, fmt.Errorf("Failed to Unmarshal. body: %s, err: %w", body, err) } } else { cves, err = ms.driver.GetFilteredCvesMicrosoft(filtered, append(applied, unapplied...)) if err != nil { - return 0, xerrors.Errorf("Failed to detect CVEs. err: %w", err) + return 0, fmt.Errorf("Failed to detect CVEs. err: %w", err) } } for cveID, cve := range cves { v, err := ms.detect(r, cve, applied, unapplied) if err != nil { - return 0, xerrors.Errorf("Failed to detect. err: %w", err) + return 0, fmt.Errorf("Failed to detect. err: %w", err) } if v == nil { continue @@ -289,7 +289,7 @@ func (ms Microsoft) detect(r *models.ScanResult, cve gostmodels.MicrosoftCVE, ap FixState: "unknown", }) default: - return nil, xerrors.Errorf("unexpected product. expected: %q, actual: %q", []string{r.Release, "Microsoft Edge"}, p.Name) + return nil, fmt.Errorf("unexpected product. expected: %q, actual: %q", []string{r.Release, "Microsoft Edge"}, p.Name) } continue } @@ -323,7 +323,7 @@ func (ms Microsoft) detect(r *models.ScanResult, cve gostmodels.MicrosoftCVE, ap FixedIn: kb.FixedBuild, }) default: - return nil, xerrors.Errorf("unexpected product. supported: %q, actual: %q", []string{"Microsoft Edge"}, p.Name) + return nil, fmt.Errorf("unexpected product. supported: %q, actual: %q", []string{"Microsoft Edge"}, p.Name) } } else { kbid := fmt.Sprintf("KB%s", kb.Article) @@ -352,17 +352,17 @@ func (ms Microsoft) detect(r *models.ScanResult, cve gostmodels.MicrosoftCVE, ap case "unknown": cs.AppendIfMissing(models.WindowsRoughMatch) default: - return nil, xerrors.Errorf("unexpected fix state. expected: %q, actual: %q", []string{"fixed", "unfixed", "unknown"}, stat.FixState) + return nil, fmt.Errorf("unexpected fix state. expected: %q, actual: %q", []string{"fixed", "unfixed", "unknown"}, stat.FixState) } } if len(cs) == 0 { - return nil, xerrors.New("confidences not found") + return nil, errors.New("confidences not found") } return cs, nil }() if err != nil { - return nil, xerrors.Errorf("Failed to detect confidences. err: %w", err) + return nil, fmt.Errorf("Failed to detect confidences. err: %w", err) } vinfo.Confidences = confs diff --git a/gost/util.go b/gost/util.go index 3a9cca8043..625dca1d69 100644 --- a/gost/util.go +++ b/gost/util.go @@ -3,6 +3,8 @@ package gost import ( + "errors" + "fmt" "maps" "net/http" "slices" @@ -11,7 +13,6 @@ import ( "github.com/cenkalti/backoff" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -72,11 +73,11 @@ func getCvesViaHTTP(cveIDs []string, urlPrefix string) ( case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching Gost") + return nil, errors.New("Timeout Fetching Gost") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch Gost. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch Gost. err: %w", errors.Join(errs...)) } return } @@ -140,11 +141,11 @@ func getCvesWithFixStateViaHTTP(r *models.ScanResult, urlPrefix, fixState string case err := <-errChan: errs = append(errs, err) case <-timeout: - return nil, xerrors.New("Timeout Fetching Gost") + return nil, errors.New("Timeout Fetching Gost") } } if len(errs) != 0 { - return nil, xerrors.Errorf("Failed to fetch Gost. err: %w", errs) + return nil, fmt.Errorf("Failed to fetch Gost. err: %w", errors.Join(errs...)) } return } @@ -165,7 +166,7 @@ func httpGet(url string, req request, resChan chan<- response, errChan chan<- er if count == retryMax { return nil } - return xerrors.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) + return fmt.Errorf("HTTP GET error, url: %s, resp: %v, err: %+v", url, resp, errs) } return nil } @@ -174,11 +175,11 @@ func httpGet(url string, req request, resChan chan<- response, errChan chan<- er } err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify) if err != nil { - errChan <- xerrors.Errorf("HTTP Error %w", err) + errChan <- fmt.Errorf("HTTP Error %w", err) return } if count == retryMax { - errChan <- xerrors.New("Retry count exceeded") + errChan <- errors.New("Retry count exceeded") return } diff --git a/models/packages.go b/models/packages.go index 72cc425b3d..629d8cc03a 100644 --- a/models/packages.go +++ b/models/packages.go @@ -9,8 +9,6 @@ import ( "strconv" "strings" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/constant" ) @@ -70,7 +68,7 @@ func (ps Packages) FindByFQPN(nameVerRel string) (*Package, error) { return &p, nil } } - return nil, xerrors.Errorf("Failed to find the package: %s", nameVerRel) + return nil, fmt.Errorf("Failed to find the package: %s", nameVerRel) } // Package has installed binary packages. @@ -192,7 +190,7 @@ func NewPortStat(ipPort string) (*PortStat, error) { } sep := strings.LastIndex(ipPort, ":") if sep == -1 { - return nil, xerrors.Errorf("Failed to parse IP:Port: %s", ipPort) + return nil, fmt.Errorf("Failed to parse IP:Port: %s", ipPort) } return &PortStat{ BindAddress: ipPort[:sep], diff --git a/reporter/azureblob.go b/reporter/azureblob.go index 3dd5ec06f6..9dac844e6b 100644 --- a/reporter/azureblob.go +++ b/reporter/azureblob.go @@ -7,7 +7,6 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/models" @@ -50,7 +49,7 @@ func (w AzureBlobWriter) Write(rs ...models.ScanResult) (err error) { k := key + ".json" var b []byte if b, err = json.Marshal(r); err != nil { - return xerrors.Errorf("Failed to Marshal to JSON: %w", err) + return fmt.Errorf("Failed to Marshal to JSON: %w", err) } if err := w.createBlockBlob(cli, k, b, w.Gzip); err != nil { return err @@ -60,7 +59,7 @@ func (w AzureBlobWriter) Write(rs ...models.ScanResult) (err error) { if w.FormatList { text, err := formatList(r) if err != nil { - return xerrors.Errorf("Failed to format list. err: %w", err) + return fmt.Errorf("Failed to format list. err: %w", err) } if err := w.createBlockBlob(cli, key+"_short.txt", []byte(text), w.Gzip); err != nil { return err @@ -70,7 +69,7 @@ func (w AzureBlobWriter) Write(rs ...models.ScanResult) (err error) { if w.FormatFullText { text, err := formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full text. err: %w", err) + return fmt.Errorf("Failed to format full text. err: %w", err) } if err := w.createBlockBlob(cli, key+"_full.txt", []byte(text), w.Gzip); err != nil { return err @@ -91,7 +90,7 @@ func (w AzureBlobWriter) Validate() error { for pager.More() { page, err := pager.NextPage(context.TODO()) if err != nil { - return xerrors.Errorf("Failed to next page. err: %w", err) + return fmt.Errorf("Failed to next page. err: %w", err) } for _, con := range page.ContainerItems { if *con.Name == w.ContainerName { @@ -99,18 +98,18 @@ func (w AzureBlobWriter) Validate() error { } } } - return xerrors.Errorf("Container not found. Container: %s", w.ContainerName) + return fmt.Errorf("Container not found. Container: %s", w.ContainerName) } func (w AzureBlobWriter) getBlobClient() (*azblob.Client, error) { cred, err := azblob.NewSharedKeyCredential(w.AccountName, w.AccountKey) if err != nil { - return nil, xerrors.Errorf("Failed to create SharedKeyCredential. err: %w", err) + return nil, fmt.Errorf("Failed to create SharedKeyCredential. err: %w", err) } client, err := azblob.NewClientWithSharedKeyCredential(w.Endpoint, cred, nil) if err != nil { - return nil, xerrors.Errorf("Failed to create Client. err: %w", err) + return nil, fmt.Errorf("Failed to create Client. err: %w", err) } return client, nil @@ -126,7 +125,7 @@ func (w AzureBlobWriter) createBlockBlob(cli *azblob.Client, k string, b []byte, } if _, err := cli.UploadBuffer(context.TODO(), w.ContainerName, k, b, nil); err != nil { - return xerrors.Errorf("Failed to upload data to %s/%s, err: %w", w.ContainerName, k, err) + return fmt.Errorf("Failed to upload data to %s/%s, err: %w", w.ContainerName, k, err) } return nil } diff --git a/reporter/email.go b/reporter/email.go index 7e8e18a78f..1e0cff482a 100644 --- a/reporter/email.go +++ b/reporter/email.go @@ -2,6 +2,7 @@ package reporter import ( "crypto/tls" + "errors" "fmt" "net" "net/mail" @@ -10,7 +11,6 @@ import ( sasl "github.com/emersion/go-sasl" smtp "github.com/emersion/go-smtp" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/models" @@ -33,7 +33,7 @@ func (w EMailWriter) Write(rs ...models.ScanResult) (err error) { if w.FormatOneEMail { text, err := formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full plain text. err: %w", err) + return fmt.Errorf("Failed to format full plain text. err: %w", err) } message += text + "\r\n\r\n" mm := r.ScannedCves.CountGroupBySeverity() @@ -55,12 +55,12 @@ func (w EMailWriter) Write(rs ...models.ScanResult) (err error) { if w.FormatList { message, err = formatList(r) if err != nil { - return xerrors.Errorf("Failed to format list. err: %w", err) + return fmt.Errorf("Failed to format list. err: %w", err) } } else { message, err = formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full plain text. err: %w", err) + return fmt.Errorf("Failed to format full plain text. err: %w", err) } } if w.FormatOneLineText { @@ -114,20 +114,20 @@ func (e *emailSender) sendMail(smtpServerAddr, message string) (err error) { case "465": c, err = smtp.DialTLS(smtpServerAddr, tlsConfig) if err != nil { - return xerrors.Errorf("Failed to create TLS connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create TLS connection to SMTP server: %w", err) } defer c.Close() default: c, err = smtp.Dial(smtpServerAddr) if err != nil { - return xerrors.Errorf("Failed to create connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create connection to SMTP server: %w", err) } defer c.Close() if ok, _ := c.Extension("STARTTLS"); ok { c, err = smtp.DialStartTLS(smtpServerAddr, tlsConfig) if err != nil { - return xerrors.Errorf("Failed to create STARTTLS connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create STARTTLS connection to SMTP server: %w", err) } defer c.Close() } @@ -135,57 +135,57 @@ func (e *emailSender) sendMail(smtpServerAddr, message string) (err error) { case "None": c, err = smtp.Dial(smtpServerAddr) if err != nil { - return xerrors.Errorf("Failed to create connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create connection to SMTP server: %w", err) } defer c.Close() case "STARTTLS": c, err = smtp.DialStartTLS(smtpServerAddr, tlsConfig) if err != nil { - return xerrors.Errorf("Failed to create STARTTLS connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create STARTTLS connection to SMTP server: %w", err) } defer c.Close() case "SMTPS": c, err = smtp.DialTLS(smtpServerAddr, tlsConfig) if err != nil { - return xerrors.Errorf("Failed to create TLS connection to SMTP server: %w", err) + return fmt.Errorf("Failed to create TLS connection to SMTP server: %w", err) } defer c.Close() default: - return xerrors.New(`invalid TLS mode. accepts: ["", "None", "STARTTLS", "SMTPS"]`) + return errors.New(`invalid TLS mode. accepts: ["", "None", "STARTTLS", "SMTPS"]`) } if ok, param := c.Extension("AUTH"); ok { authList := strings.Split(param, " ") auth = e.newSaslClient(authList) if err = c.Auth(auth); err != nil { - return xerrors.Errorf("Failed to authenticate: %w", err) + return fmt.Errorf("Failed to authenticate: %w", err) } } if err = c.Mail(emailConf.From, nil); err != nil { - return xerrors.Errorf("Failed to send Mail command: %w", err) + return fmt.Errorf("Failed to send Mail command: %w", err) } for _, to := range emailConf.To { if err = c.Rcpt(to, nil); err != nil { - return xerrors.Errorf("Failed to send Rcpt command: %w", err) + return fmt.Errorf("Failed to send Rcpt command: %w", err) } } w, err := c.Data() if err != nil { - return xerrors.Errorf("Failed to send Data command: %w", err) + return fmt.Errorf("Failed to send Data command: %w", err) } _, err = w.Write([]byte(message)) if err != nil { - return xerrors.Errorf("Failed to write EMail message: %w", err) + return fmt.Errorf("Failed to write EMail message: %w", err) } err = w.Close() if err != nil { - return xerrors.Errorf("Failed to close Writer: %w", err) + return fmt.Errorf("Failed to close Writer: %w", err) } err = c.Quit() if err != nil { - return xerrors.Errorf("Failed to close connection: %w", err) + return fmt.Errorf("Failed to close connection: %w", err) } return nil } @@ -196,7 +196,7 @@ func (e *emailSender) Send(subject, body string) (err error) { cc := strings.Join(emailConf.Cc[:], ", ") mailAddresses := append(emailConf.To, emailConf.Cc...) if _, err := mail.ParseAddressList(strings.Join(mailAddresses[:], ", ")); err != nil { - return xerrors.Errorf("Failed to parse email addresses: %w", err) + return fmt.Errorf("Failed to parse email addresses: %w", err) } headers := make(map[string]string) @@ -212,7 +212,7 @@ func (e *emailSender) Send(subject, body string) (err error) { header.WriteString(fmt.Sprintf("%s: %s\r\n", k, v)) } if err := e.sendMail(net.JoinHostPort(emailConf.SMTPAddr, emailConf.SMTPPort), fmt.Sprintf("%s\r\n%s", header.String(), body)); err != nil { - return xerrors.Errorf("Failed to send emails: %w", err) + return fmt.Errorf("Failed to send emails: %w", err) } return nil } diff --git a/reporter/googlechat.go b/reporter/googlechat.go index ebb1b1792c..a3e021cfa5 100644 --- a/reporter/googlechat.go +++ b/reporter/googlechat.go @@ -12,7 +12,6 @@ import ( "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ) // GoogleChatWriter send report to GoogleChat @@ -98,5 +97,5 @@ func (w GoogleChatWriter) checkResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } - return xerrors.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status) + return fmt.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status) } diff --git a/reporter/http.go b/reporter/http.go index 88f49fff1b..d5bdc4359b 100644 --- a/reporter/http.go +++ b/reporter/http.go @@ -3,11 +3,10 @@ package reporter import ( "bytes" "encoding/json" + "fmt" "io" "net/http" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/models" ) @@ -21,20 +20,20 @@ func (w HTTPRequestWriter) Write(rs ...models.ScanResult) (err error) { for _, r := range rs { b := new(bytes.Buffer) if err := json.NewEncoder(b).Encode(r); err != nil { - return xerrors.Errorf("Failed to encode scan result. err: %w", err) + return fmt.Errorf("Failed to encode scan result. err: %w", err) } resp, err := http.Post(w.URL, "application/json; charset=utf-8", b) if err != nil { - return xerrors.Errorf("Failed to post request. err: %w", err) + return fmt.Errorf("Failed to post request. err: %w", err) } if resp.StatusCode != http.StatusOK { - return xerrors.Errorf("Failed to post request. err: error request response with status code %d", resp.StatusCode) + return fmt.Errorf("Failed to post request. err: error request response with status code %d", resp.StatusCode) } defer resp.Body.Close() if _, err := io.Copy(io.Discard, resp.Body); err != nil { - return xerrors.Errorf("Failed to discard response body. err: %w", err) + return fmt.Errorf("Failed to discard response body. err: %w", err) } } return nil @@ -49,12 +48,12 @@ type HTTPResponseWriter struct { func (w HTTPResponseWriter) Write(rs ...models.ScanResult) (err error) { res, err := json.Marshal(rs) if err != nil { - return xerrors.Errorf("Failed to marshal scan results: %w", err) + return fmt.Errorf("Failed to marshal scan results: %w", err) } w.Writer.Header().Set("Content-Type", "application/json") if _, err = w.Writer.Write(res); err != nil { - return xerrors.Errorf("Failed to write response. err: %w", err) + return fmt.Errorf("Failed to write response. err: %w", err) } return nil diff --git a/reporter/localfile.go b/reporter/localfile.go index 0a2fc0cd18..0b5f909613 100644 --- a/reporter/localfile.go +++ b/reporter/localfile.go @@ -7,7 +7,6 @@ import ( "path/filepath" "github.com/CycloneDX/cyclonedx-go" - "golang.org/x/xerrors" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/reporter/sbom" @@ -35,7 +34,7 @@ func (w LocalFileWriter) Write(rs ...models.ScanResult) (err error) { path := filepath.Join(w.CurrentDir, "summary.txt") text := formatOneLineSummary(rs...) if err := w.writeFile(path, []byte(text), 0600); err != nil { - return xerrors.Errorf( + return fmt.Errorf( "Failed to write to file. path: %s, err: %w", path, err) } @@ -52,10 +51,10 @@ func (w LocalFileWriter) Write(rs ...models.ScanResult) (err error) { } var b []byte if b, err = json.MarshalIndent(r, "", " "); err != nil { - return xerrors.Errorf("Failed to Marshal to JSON: %w", err) + return fmt.Errorf("Failed to Marshal to JSON: %w", err) } if err := w.writeFile(p, b, 0600); err != nil { - return xerrors.Errorf("Failed to write JSON. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write JSON. path: %s, err: %w", p, err) } } @@ -66,10 +65,10 @@ func (w LocalFileWriter) Write(rs ...models.ScanResult) (err error) { } text, err := formatList(r) if err != nil { - return xerrors.Errorf("Failed to format list: %w", err) + return fmt.Errorf("Failed to format list: %w", err) } if err := w.writeFile(p, []byte(text), 0600); err != nil { - return xerrors.Errorf("Failed to write text files. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write text files. path: %s, err: %w", p, err) } } @@ -80,10 +79,10 @@ func (w LocalFileWriter) Write(rs ...models.ScanResult) (err error) { } text, err := formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full text: %w", err) + return fmt.Errorf("Failed to format full text: %w", err) } if err := w.writeFile(p, []byte(text), 0600); err != nil { - return xerrors.Errorf("Failed to write text files. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write text files. path: %s, err: %w", p, err) } } @@ -93,40 +92,40 @@ func (w LocalFileWriter) Write(rs ...models.ScanResult) (err error) { p = path + "_diff.csv" } if err := formatCsvList(r, p); err != nil { - return xerrors.Errorf("Failed to write CSV: %s, %w", p, err) + return fmt.Errorf("Failed to write CSV: %s, %w", p, err) } } if w.FormatCycloneDXJSON { bs, err := sbom.SerializeCycloneDX(sbom.ToCycloneDX(r), cyclonedx.BOMFileFormatJSON) if err != nil { - return xerrors.Errorf("Failed to generate CycloneDX JSON. err: %w", err) + return fmt.Errorf("Failed to generate CycloneDX JSON. err: %w", err) } p := fmt.Sprintf("%s_cyclonedx.json", path) if err := w.writeFile(p, bs, 0600); err != nil { - return xerrors.Errorf("Failed to write CycloneDX JSON. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write CycloneDX JSON. path: %s, err: %w", p, err) } } if w.FormatCycloneDXXML { bs, err := sbom.SerializeCycloneDX(sbom.ToCycloneDX(r), cyclonedx.BOMFileFormatXML) if err != nil { - return xerrors.Errorf("Failed to generate CycloneDX XML. err: %w", err) + return fmt.Errorf("Failed to generate CycloneDX XML. err: %w", err) } p := fmt.Sprintf("%s_cyclonedx.xml", path) if err := w.writeFile(p, bs, 0600); err != nil { - return xerrors.Errorf("Failed to write CycloneDX XML. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write CycloneDX XML. path: %s, err: %w", p, err) } } if w.FormatSPDXJSON { bs, err := sbom.SerializeSPDX(sbom.ToSPDX(r, "")) if err != nil { - return xerrors.Errorf("Failed to generate SPDX JSON. err: %w", err) + return fmt.Errorf("Failed to generate SPDX JSON. err: %w", err) } p := fmt.Sprintf("%s_spdx.json", path) if err := w.writeFile(p, bs, 0600); err != nil { - return xerrors.Errorf("Failed to write SPDX JSON. path: %s, err: %w", p, err) + return fmt.Errorf("Failed to write SPDX JSON. path: %s, err: %w", p, err) } } } diff --git a/reporter/s3.go b/reporter/s3.go index aa3c0b54d2..4998c4076a 100644 --- a/reporter/s3.go +++ b/reporter/s3.go @@ -14,7 +14,6 @@ import ( awsConfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/models" @@ -44,11 +43,11 @@ func (w S3Writer) getS3() (*s3.Client, error) { case config.CredentialProviderAnonymous: optFns = append(optFns, awsConfig.WithCredentialsProvider(aws.AnonymousCredentials{})) default: - return nil, xerrors.Errorf("CredentialProvider: %s is not supported", w.CredentialProvider) + return nil, fmt.Errorf("CredentialProvider: %s is not supported", w.CredentialProvider) } cfg, err := awsConfig.LoadDefaultConfig(context.TODO(), optFns...) if err != nil { - return nil, xerrors.Errorf("Failed to load config. err: %w", err) + return nil, fmt.Errorf("Failed to load config. err: %w", err) } return s3.NewFromConfig(cfg, func(o *s3.Options) { @@ -69,7 +68,7 @@ func (w S3Writer) Write(rs ...models.ScanResult) (err error) { svc, err := w.getS3() if err != nil { - return xerrors.Errorf("Failed to get s3 client. err: %w", err) + return fmt.Errorf("Failed to get s3 client. err: %w", err) } if w.FormatOneLineText { @@ -85,7 +84,7 @@ func (w S3Writer) Write(rs ...models.ScanResult) (err error) { if w.FormatJSON { var b []byte if b, err = json.Marshal(r); err != nil { - return xerrors.Errorf("Failed to Marshal to JSON: %w", err) + return fmt.Errorf("Failed to Marshal to JSON: %w", err) } if err := w.putObject(svc, key+".json", b, w.Gzip); err != nil { return err @@ -95,7 +94,7 @@ func (w S3Writer) Write(rs ...models.ScanResult) (err error) { if w.FormatList { text, err := formatList(r) if err != nil { - return xerrors.Errorf("Failed to format list. err: %w", err) + return fmt.Errorf("Failed to format list. err: %w", err) } if err := w.putObject(svc, key+"_short.txt", []byte(text), w.Gzip); err != nil { return err @@ -105,7 +104,7 @@ func (w S3Writer) Write(rs ...models.ScanResult) (err error) { if w.FormatFullText { text, err := formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full text. err: %w", err) + return fmt.Errorf("Failed to format full text. err: %w", err) } if err := w.putObject(svc, key+"_full.txt", []byte(text), w.Gzip); err != nil { return err @@ -116,13 +115,13 @@ func (w S3Writer) Write(rs ...models.ScanResult) (err error) { } // ErrBucketExistCheck : bucket existence cannot be checked because s3:ListBucket or s3:ListAllMyBuckets is not allowed -var ErrBucketExistCheck = xerrors.New("bucket existence cannot be checked because s3:ListBucket or s3:ListAllMyBuckets is not allowed") +var ErrBucketExistCheck = errors.New("bucket existence cannot be checked because s3:ListBucket or s3:ListAllMyBuckets is not allowed") // Validate check the existence of S3 bucket func (w S3Writer) Validate() error { svc, err := w.getS3() if err != nil { - return xerrors.Errorf("Failed to get s3 client. err: %w", err) + return fmt.Errorf("Failed to get s3 client. err: %w", err) } // s3:ListBucket @@ -132,7 +131,7 @@ func (w S3Writer) Validate() error { } var nsb *types.NoSuchBucket if errors.As(err, &nsb) { - return xerrors.Errorf("Failed to find the buckets. profile: %s, region: %s, bucket: %s", w.Profile, w.Region, w.S3Bucket) + return fmt.Errorf("Failed to find the buckets. profile: %s, region: %s, bucket: %s", w.Profile, w.Region, w.S3Bucket) } // s3:ListAllMyBuckets @@ -143,7 +142,7 @@ func (w S3Writer) Validate() error { }) { return nil } - return xerrors.Errorf("Failed to find the buckets. profile: %s, region: %s, bucket: %s", w.Profile, w.Region, w.S3Bucket) + return fmt.Errorf("Failed to find the buckets. profile: %s, region: %s, bucket: %s", w.Profile, w.Region, w.S3Bucket) } return ErrBucketExistCheck @@ -166,7 +165,7 @@ func (w S3Writer) putObject(svc *s3.Client, k string, b []byte, gzip bool) error } if _, err := svc.PutObject(context.TODO(), putObjectInput); err != nil { - return xerrors.Errorf("Failed to upload data to %s/%s, err: %w", + return fmt.Errorf("Failed to upload data to %s/%s, err: %w", w.S3Bucket, path.Join(w.S3ResultsDir, k), err) } return nil diff --git a/reporter/sbom/cyclonedx.go b/reporter/sbom/cyclonedx.go index aee3b8d3ba..8be12ba4ad 100644 --- a/reporter/sbom/cyclonedx.go +++ b/reporter/sbom/cyclonedx.go @@ -11,7 +11,6 @@ import ( cdx "github.com/CycloneDX/cyclonedx-go" "github.com/google/uuid" - "golang.org/x/xerrors" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/models" @@ -32,7 +31,7 @@ func SerializeCycloneDX(bom *cdx.BOM, format cdx.BOMFileFormat) ([]byte, error) enc := cdx.NewBOMEncoder(buf, format) enc.SetPretty(true) if err := enc.Encode(bom); err != nil { - return nil, xerrors.Errorf("Failed to encode CycloneDX. err: %w", err) + return nil, fmt.Errorf("Failed to encode CycloneDX. err: %w", err) } return buf.Bytes(), nil } diff --git a/reporter/slack.go b/reporter/slack.go index 66f2cdeb67..42221ef1fe 100644 --- a/reporter/slack.go +++ b/reporter/slack.go @@ -2,6 +2,7 @@ package reporter import ( "encoding/json" + "errors" "fmt" "slices" "strings" @@ -13,7 +14,6 @@ import ( "github.com/future-architect/vuls/models" "github.com/nlopes/slack" "github.com/parnurzeal/gorequest" - "golang.org/x/xerrors" ) // SlackWriter send report to slack @@ -147,7 +147,7 @@ func (w SlackWriter) send(msg message) error { if count == retryMax { return nil } - return xerrors.Errorf( + return fmt.Errorf( "HTTP POST error. url: %s, resp: %v, body: %s, err: %+v", w.Cnf.HookURL, resp, body, errs) } @@ -159,10 +159,10 @@ func (w SlackWriter) send(msg message) error { } boff := backoff.NewExponentialBackOff() if err := backoff.RetryNotify(f, boff, notify); err != nil { - return xerrors.Errorf("HTTP error: %w", err) + return fmt.Errorf("HTTP error: %w", err) } if count == retryMax { - return xerrors.New("Retry count exceeded") + return errors.New("Retry count exceeded") } return nil } diff --git a/reporter/stdout.go b/reporter/stdout.go index 99b6441e6f..45be223ed5 100644 --- a/reporter/stdout.go +++ b/reporter/stdout.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/future-architect/vuls/models" - "golang.org/x/xerrors" ) // StdoutWriter write to stdout @@ -38,7 +37,7 @@ func (w StdoutWriter) Write(rs ...models.ScanResult) error { for _, r := range rs { text, err := formatList(r) if err != nil { - return xerrors.Errorf("Failed to format list. err: %w", err) + return fmt.Errorf("Failed to format list. err: %w", err) } fmt.Println(text) } @@ -48,7 +47,7 @@ func (w StdoutWriter) Write(rs ...models.ScanResult) error { for _, r := range rs { text, err := formatFullPlainText(r) if err != nil { - return xerrors.Errorf("Failed to format full text. err: %w", err) + return fmt.Errorf("Failed to format full text. err: %w", err) } fmt.Println(text) } diff --git a/reporter/syslog.go b/reporter/syslog.go index 33f04449b0..c492bb0457 100644 --- a/reporter/syslog.go +++ b/reporter/syslog.go @@ -7,8 +7,6 @@ import ( "log/syslog" "strings" - "golang.org/x/xerrors" - syslogConf "github.com/future-architect/vuls/config/syslog" "github.com/future-architect/vuls/models" ) @@ -26,7 +24,7 @@ func (w SyslogWriter) Write(rs ...models.ScanResult) (err error) { sysLog, err := syslog.Dial(w.Cnf.Protocol, raddr, severity|facility, w.Cnf.Tag) if err != nil { - return xerrors.Errorf("Failed to initialize syslog client: %w", err) + return fmt.Errorf("Failed to initialize syslog client: %w", err) } for _, r := range rs { diff --git a/reporter/telegram.go b/reporter/telegram.go index 761630bbec..ff1b6fbad9 100644 --- a/reporter/telegram.go +++ b/reporter/telegram.go @@ -12,7 +12,6 @@ import ( "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ) // TelegramWriter sends report to Telegram @@ -86,5 +85,5 @@ func (w TelegramWriter) checkResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } - return xerrors.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status) + return fmt.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status) } diff --git a/reporter/util.go b/reporter/util.go index 281275ce33..22d6e5de1e 100644 --- a/reporter/util.go +++ b/reporter/util.go @@ -26,7 +26,6 @@ import ( "github.com/olekukonko/tablewriter/renderer" "github.com/olekukonko/tablewriter/tw" "golang.org/x/term" - "golang.org/x/xerrors" ) const ( @@ -40,7 +39,7 @@ func OverwriteJSONFile(dir string, r models.ScanResult) error { FormatJSON: true, } if err := w.Write(r); err != nil { - return xerrors.Errorf("Failed to write summary report: %w", err) + return fmt.Errorf("Failed to write summary report: %w", err) } return nil } @@ -49,7 +48,7 @@ func OverwriteJSONFile(dir string, r models.ScanResult) error { func LoadScanResults(jsonDir string) (results models.ScanResults, err error) { var files []fs.DirEntry if files, err = os.ReadDir(jsonDir); err != nil { - return nil, xerrors.Errorf("Failed to read %s: %w", jsonDir, err) + return nil, fmt.Errorf("Failed to read %s: %w", jsonDir, err) } for _, f := range files { if filepath.Ext(f.Name()) != ".json" || strings.HasSuffix(f.Name(), "_diff.json") { @@ -64,7 +63,7 @@ func LoadScanResults(jsonDir string) (results models.ScanResults, err error) { results = append(results, *r) } if len(results) == 0 { - return nil, xerrors.Errorf("There is no json file under %s", jsonDir) + return nil, fmt.Errorf("There is no json file under %s", jsonDir) } return } @@ -76,11 +75,11 @@ func loadOneServerScanResult(jsonFile string) (*models.ScanResult, error) { err error ) if data, err = os.ReadFile(jsonFile); err != nil { - return nil, xerrors.Errorf("Failed to read %s: %w", jsonFile, err) + return nil, fmt.Errorf("Failed to read %s: %w", jsonFile, err) } result := &models.ScanResult{} if err := json.Unmarshal(data, result); err != nil { - return nil, xerrors.Errorf("Failed to parse %s: %w", jsonFile, err) + return nil, fmt.Errorf("Failed to parse %s: %w", jsonFile, err) } for k, v := range result.ScannedCves { @@ -97,7 +96,7 @@ func loadOneServerScanResult(jsonFile string) (*models.ScanResult, error) { func ListValidJSONDirs(resultsDir string) (dirs []string, err error) { dirInfo, err := os.ReadDir(resultsDir) if err != nil { - return nil, xerrors.Errorf("Failed to read %s: %w", resultsDir, err) + return nil, fmt.Errorf("Failed to read %s: %w", resultsDir, err) } for _, d := range dirInfo { if !d.IsDir() { @@ -136,20 +135,20 @@ func JSONDir(resultsDir string, args []string) (path string, err error) { return path, nil } } - return "", xerrors.Errorf("Invalid path: %s", path) + return "", fmt.Errorf("Invalid path: %s", path) } // TODO remove Pipe flag if config.Conf.Pipe { bytes, err := io.ReadAll(os.Stdin) if err != nil { - return "", xerrors.Errorf("Failed to read stdin: %w", err) + return "", fmt.Errorf("Failed to read stdin: %w", err) } fields := strings.Fields(string(bytes)) if 0 < len(fields) { return filepath.Join(resultsDir, fields[0]), nil } - return "", xerrors.Errorf("Stdin is invalid: %s", string(bytes)) + return "", fmt.Errorf("Stdin is invalid: %s", string(bytes)) } // returns latest dir when no args or no PIPE @@ -157,7 +156,7 @@ func JSONDir(resultsDir string, args []string) (path string, err error) { return "", err } if len(dirs) == 0 { - return "", xerrors.Errorf("No results under %s", resultsDir) + return "", fmt.Errorf("No results under %s", resultsDir) } return dirs[0], nil } @@ -338,10 +337,10 @@ No CVE-IDs are found in updatable packages. "Packages", }) if err := table.Bulk(data); err != nil { - return "", xerrors.Errorf("Failed to bulk to table. err: %w", err) + return "", fmt.Errorf("Failed to bulk to table. err: %w", err) } if err := table.Render(); err != nil { - return "", xerrors.Errorf("Failed to render table. err: %w", err) + return "", fmt.Errorf("Failed to render table. err: %w", err) } return fmt.Sprintf("%s\n%s", header, b.String()), nil } @@ -647,10 +646,10 @@ No CVE-IDs are found in updatable packages. vuln.PatchStatus(r.Packages), }) if err := table.Bulk(data); err != nil { - return "", xerrors.Errorf("Failed to bulk to table. err: %w", err) + return "", fmt.Errorf("Failed to bulk to table. err: %w", err) } if err := table.Render(); err != nil { - return "", xerrors.Errorf("Failed to render table. err: %w", err) + return "", fmt.Errorf("Failed to render table. err: %w", err) } lines.WriteString(b.String() + "\n") @@ -716,11 +715,11 @@ func formatCsvList(r models.ScanResult, path string) error { file, err := os.Create(path) if err != nil { - return xerrors.Errorf("Failed to create a file: %s, err: %w", path, err) + return fmt.Errorf("Failed to create a file: %s, err: %w", path, err) } defer file.Close() if err := csv.NewWriter(file).WriteAll(data); err != nil { - return xerrors.Errorf("Failed to write to file: %s, err: %w", path, err) + return fmt.Errorf("Failed to write to file: %s, err: %w", path, err) } return nil } diff --git a/saas/saas.go b/saas/saas.go index 686ef8d0cf..3a5684854d 100644 --- a/saas/saas.go +++ b/saas/saas.go @@ -17,7 +17,6 @@ import ( "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/sts/types" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" @@ -69,7 +68,7 @@ func (w Writer) Write(rs ...models.ScanResult) error { } body, err := json.Marshal(payload) if err != nil { - return xerrors.Errorf("Failed to Marshal to JSON: %w", err) + return fmt.Errorf("Failed to Marshal to JSON: %w", err) } ctx, cancel := context.WithTimeout(context.Background(), w.Timeout) @@ -90,7 +89,7 @@ func (w Writer) Write(rs ...models.ScanResult) error { } defer resp.Body.Close() if resp.StatusCode != 200 { - return xerrors.Errorf("Failed to get Credential. Request JSON : %s,", string(body)) + return fmt.Errorf("Failed to get Credential. Request JSON : %s,", string(body)) } t, err := io.ReadAll(resp.Body) @@ -99,7 +98,7 @@ func (w Writer) Write(rs ...models.ScanResult) error { } var tempCredential TempCredential if err := json.Unmarshal(t, &tempCredential); err != nil { - return xerrors.Errorf("Failed to unmarshal saas credential file. err : %s", err) + return fmt.Errorf("Failed to unmarshal saas credential file. err : %s", err) } cfg, err := awsConfig.LoadDefaultConfig(ctx, @@ -107,11 +106,11 @@ func (w Writer) Write(rs ...models.ScanResult) error { awsConfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(*tempCredential.Credential.AccessKeyId, *tempCredential.Credential.SecretAccessKey, *tempCredential.Credential.SessionToken)), ) if err != nil { - return xerrors.Errorf("Failed to load config. err: %w", err) + return fmt.Errorf("Failed to load config. err: %w", err) } // For S3 upload of aws sdk if err := os.Setenv("HTTPS_PROXY", w.Proxy); err != nil { - return xerrors.Errorf("Failed to set HTTP proxy: %s", err) + return fmt.Errorf("Failed to set HTTP proxy: %s", err) } svc := s3.NewFromConfig(cfg) @@ -125,7 +124,7 @@ func (w Writer) Write(rs ...models.ScanResult) error { b, err := json.Marshal(r) if err != nil { - return xerrors.Errorf("Failed to Marshal to JSON: %w", err) + return fmt.Errorf("Failed to Marshal to JSON: %w", err) } logging.Log.Infof("Uploading... %s", r.FormatServerName()) s3Key := renameKeyName(r.ServerUUID, r.Container) @@ -135,7 +134,7 @@ func (w Writer) Write(rs ...models.ScanResult) error { Body: bytes.NewReader(b), } if _, err := svc.PutObject(ctx, putObjectInput); err != nil { - return xerrors.Errorf("Failed to upload data to %s/%s, err: %w", + return fmt.Errorf("Failed to upload data to %s/%s, err: %w", tempCredential.S3Bucket, path.Join(tempCredential.S3ResultsDir, s3Key), err) } } diff --git a/saas/uuid.go b/saas/uuid.go index ec26291057..fc28200af4 100644 --- a/saas/uuid.go +++ b/saas/uuid.go @@ -12,7 +12,6 @@ import ( "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" "github.com/hashicorp/go-uuid" - "golang.org/x/xerrors" ) // EnsureUUIDs generate a new UUID of the scan target server if UUID is not assigned yet. @@ -20,7 +19,7 @@ import ( func EnsureUUIDs(servers map[string]config.ServerInfo, path string, scanResults models.ScanResults) (err error) { needsOverwrite, err := ensure(servers, scanResults, uuid.GenerateUUID) if err != nil { - return xerrors.Errorf("Failed to ensure UUIDs. err: %w", err) + return fmt.Errorf("Failed to ensure UUIDs. err: %w", err) } if !needsOverwrite { @@ -122,21 +121,21 @@ func writeToFile(cnf config.Config, path string) error { // rename the current config.toml to config.toml.bak info, err := os.Lstat(path) if err != nil { - return xerrors.Errorf("Failed to lstat %s: %w", path, err) + return fmt.Errorf("Failed to lstat %s: %w", path, err) } realPath := path if info.Mode()&os.ModeSymlink == os.ModeSymlink { if realPath, err = os.Readlink(path); err != nil { - return xerrors.Errorf("Failed to Read link %s: %w", path, err) + return fmt.Errorf("Failed to Read link %s: %w", path, err) } } if err := os.Rename(realPath, realPath+".bak"); err != nil { - return xerrors.Errorf("Failed to rename %s: %w", path, err) + return fmt.Errorf("Failed to rename %s: %w", path, err) } var buf bytes.Buffer if err := toml.NewEncoder(&buf).Encode(c); err != nil { - return xerrors.Errorf("Failed to encode to toml: %w", err) + return fmt.Errorf("Failed to encode to toml: %w", err) } str := strings.ReplaceAll(buf.String(), "\n [", "\n\n [") str = fmt.Sprintf("%s\n\n%s", diff --git a/scanner/alpine.go b/scanner/alpine.go index de14c7a4a2..416f08f112 100644 --- a/scanner/alpine.go +++ b/scanner/alpine.go @@ -2,6 +2,7 @@ package scanner import ( "bufio" + "fmt" "regexp" "strings" @@ -10,7 +11,6 @@ import ( "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ) // inherit OsTypeInterface @@ -67,7 +67,7 @@ func (o *alpine) apkUpdate() error { } r := o.exec("apk update", noSudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to SSH: %s", r) + return fmt.Errorf("Failed to SSH: %s", r) } return nil } @@ -114,7 +114,7 @@ func (o *alpine) scanPackages() error { updatable, err := o.scanUpdatablePackages() if err != nil { - err = xerrors.Errorf("Failed to scan updatable packages: %w", err) + err = fmt.Errorf("Failed to scan updatable packages: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -138,7 +138,7 @@ func (o *alpine) scanInstalledPackages() (models.Packages, models.SrcPackages, e return o.parseApkIndex(rr.Stdout) } - return nil, nil, xerrors.Errorf("Failed to SSH: apk list --installed: %s, cat /lib/apk/db/installed: %s", r, rr) + return nil, nil, fmt.Errorf("Failed to SSH: apk list --installed: %s, cat /lib/apk/db/installed: %s", r, rr) } func (o *alpine) parseInstalledPackages(stdout string) (models.Packages, models.SrcPackages, error) { @@ -153,17 +153,17 @@ func (o *alpine) parseApkInstalledList(stdout string) (models.Packages, models.S re, err := regexp.Compile(apkListPattern) if err != nil { - return nil, nil, xerrors.Errorf("Failed to compile pattern for apk list. err: %w", err) + return nil, nil, fmt.Errorf("Failed to compile pattern for apk list. err: %w", err) } for _, match := range re.FindAllStringSubmatch(stdout, -1) { if match[re.SubexpIndex("status")] != "installed" { - return nil, nil, xerrors.Errorf("Failed to parse `apk list --installed`. err: unexpected status section. expected: %q, actual: %q, stdout: %q", "installed", match[re.SubexpIndex("status")], stdout) + return nil, nil, fmt.Errorf("Failed to parse `apk list --installed`. err: unexpected status section. expected: %q, actual: %q, stdout: %q", "installed", match[re.SubexpIndex("status")], stdout) } ss := strings.Split(match[re.SubexpIndex("pkgver")], "-") if len(ss) < 3 { - return nil, nil, xerrors.Errorf("Failed to parse `apk list --installed`. err: unexpected package name and version section. expected: %q, actual: %q, stdout: %q", "--", match[re.SubexpIndex("pkgver")], stdout) + return nil, nil, fmt.Errorf("Failed to parse `apk list --installed`. err: unexpected package name and version section. expected: %q, actual: %q, stdout: %q", "--", match[re.SubexpIndex("pkgver")], stdout) } bn := strings.Join(ss[:len(ss)-2], "-") version := strings.Join(ss[len(ss)-2:], "-") @@ -201,7 +201,7 @@ func (o *alpine) parseApkIndex(stdout string) (models.Packages, models.SrcPackag t := scanner.Text() lhs, rhs, found := strings.Cut(t, ":") if !found { - return nil, nil, xerrors.Errorf("Failed to parse APKINDEX line. err: unexpected APKINDEX format. expected: %q, actual: %q", "
:", t) + return nil, nil, fmt.Errorf("Failed to parse APKINDEX line. err: unexpected APKINDEX format. expected: %q, actual: %q", "
:", t) } switch lhs { case "P": @@ -216,11 +216,11 @@ func (o *alpine) parseApkIndex(stdout string) (models.Packages, models.SrcPackag } } if err := scanner.Err(); err != nil { - return nil, nil, xerrors.Errorf("Failed to scan by the scanner. err: %w", err) + return nil, nil, fmt.Errorf("Failed to scan by the scanner. err: %w", err) } if bn == "" || version == "" { - return nil, nil, xerrors.Errorf("Failed to parse APKINDEX record. err: package name(P:) and package version(V:) are required fields in APKINDEX Record: %q", s) + return nil, nil, fmt.Errorf("Failed to parse APKINDEX record. err: package name(P:) and package version(V:) are required fields in APKINDEX Record: %q", s) } // https://gitlab.alpinelinux.org/alpine/apk-tools/-/blob/74de0e9bd73d1af8720df40aa68d472943909804/src/app_list.c#L92-95 @@ -259,7 +259,7 @@ func (o *alpine) scanUpdatablePackages() (models.Packages, error) { return o.parseApkVersion(rr.Stdout) } - return nil, xerrors.Errorf("Failed to SSH: apk list --upgradable: %s, apk version: %s", r, rr) + return nil, fmt.Errorf("Failed to SSH: apk list --upgradable: %s, apk version: %s", r, rr) } func (o *alpine) parseApkUpgradableList(stdout string) (models.Packages, error) { @@ -267,17 +267,17 @@ func (o *alpine) parseApkUpgradableList(stdout string) (models.Packages, error) re, err := regexp.Compile(apkListPattern) if err != nil { - return nil, xerrors.Errorf("Failed to compile pattern for apk list. err: %w", err) + return nil, fmt.Errorf("Failed to compile pattern for apk list. err: %w", err) } for _, match := range re.FindAllStringSubmatch(stdout, -1) { if !strings.HasPrefix(match[re.SubexpIndex("status")], "upgradable from: ") { - return nil, xerrors.Errorf("Failed to parse `apk list --upgradable`. err: unexpected status section. expected: %q, actual: %q, stdout: %q", "upgradable from: -", match[re.SubexpIndex("status")], stdout) + return nil, fmt.Errorf("Failed to parse `apk list --upgradable`. err: unexpected status section. expected: %q, actual: %q, stdout: %q", "upgradable from: -", match[re.SubexpIndex("status")], stdout) } ss := strings.Split(match[re.SubexpIndex("pkgver")], "-") if len(ss) < 3 { - return nil, xerrors.Errorf("Failed to parse package name and version in `apk list --upgradable`. err: unexpected package name and version section. expected: %q, actual: %q, stdout: %q", "--", match[re.SubexpIndex("pkgver")], stdout) + return nil, fmt.Errorf("Failed to parse package name and version in `apk list --upgradable`. err: unexpected package name and version section. expected: %q, actual: %q, stdout: %q", "--", match[re.SubexpIndex("pkgver")], stdout) } bn := strings.Join(ss[:len(ss)-2], "-") version := strings.Join(ss[len(ss)-2:], "-") @@ -308,7 +308,7 @@ func (o *alpine) parseApkVersion(stdout string) (models.Packages, error) { } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan by the scanner. err: %w", err) + return nil, fmt.Errorf("Failed to scan by the scanner. err: %w", err) } return packs, nil diff --git a/scanner/amazon.go b/scanner/amazon.go index 569cc276b2..cad25d8930 100644 --- a/scanner/amazon.go +++ b/scanner/amazon.go @@ -1,11 +1,10 @@ package scanner import ( + "errors" "strings" "time" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" @@ -48,7 +47,7 @@ func (o *amazon) checkDeps() error { if o.getServerInfo().Mode.IsDeep() { return o.execCheckDeps(o.depsDeep()) } - return xerrors.New("Unknown scan mode") + return errors.New("Unknown scan mode") } func (o *amazon) depsFast() []string { diff --git a/scanner/base.go b/scanner/base.go index 50194a6b29..24a88eaa14 100644 --- a/scanner/base.go +++ b/scanner/base.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "net" "os" @@ -16,7 +17,6 @@ import ( "time" "golang.org/x/sync/errgroup" - "golang.org/x/xerrors" fanal "github.com/aquasecurity/trivy/pkg/fanal/analyzer" tlog "github.com/aquasecurity/trivy/pkg/log" @@ -146,7 +146,7 @@ func (l *base) getPlatform() models.Platform { func (l *base) runningKernel() (release, version string, err error) { r := l.exec("uname -r", noSudo) if !r.isSuccess() { - return "", "", xerrors.Errorf("Failed to SSH: %s", r) + return "", "", fmt.Errorf("Failed to SSH: %s", r) } release = strings.TrimSpace(r.Stdout) @@ -184,7 +184,7 @@ func (l *base) allContainers() (containers []config.Container, err error) { } return l.parseLxcPs(stdout) default: - return containers, xerrors.Errorf( + return containers, fmt.Errorf( "Not supported yet: %s", l.ServerInfo.ContainerType) } } @@ -210,7 +210,7 @@ func (l *base) runningContainers() (containers []config.Container, err error) { } return l.parseLxcPs(stdout) default: - return containers, xerrors.Errorf( + return containers, fmt.Errorf( "Not supported yet: %s", l.ServerInfo.ContainerType) } } @@ -236,7 +236,7 @@ func (l *base) exitedContainers() (containers []config.Container, err error) { } return l.parseLxcPs(stdout) default: - return containers, xerrors.Errorf( + return containers, fmt.Errorf( "Not supported yet: %s", l.ServerInfo.ContainerType) } } @@ -245,7 +245,7 @@ func (l *base) dockerPs(option string) (string, error) { cmd := fmt.Sprintf("docker ps %s", option) r := l.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to SSH: %s", r) + return "", fmt.Errorf("Failed to SSH: %s", r) } return r.Stdout, nil } @@ -254,7 +254,7 @@ func (l *base) lxdPs(option string) (string, error) { cmd := fmt.Sprintf("lxc list %s", option) r := l.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("failed to SSH: %s", r) + return "", fmt.Errorf("failed to SSH: %s", r) } return r.Stdout, nil } @@ -263,7 +263,7 @@ func (l *base) lxcPs(option string) (string, error) { cmd := fmt.Sprintf("lxc-ls %s 2>/dev/null", option) r := l.exec(cmd, sudo) if !r.isSuccess() { - return "", xerrors.Errorf("failed to SSH: %s", r) + return "", fmt.Errorf("failed to SSH: %s", r) } return r.Stdout, nil } @@ -276,7 +276,7 @@ func (l *base) parseDockerPs(stdout string) (containers []config.Container, err break } if len(fields) != 3 { - return containers, xerrors.Errorf("Unknown format: %s", line) + return containers, fmt.Errorf("Unknown format: %s", line) } containers = append(containers, config.Container{ ContainerID: fields[0], @@ -298,7 +298,7 @@ func (l *base) parseLxdPs(stdout string) (containers []config.Container, err err break } if len(fields) != 1 { - return containers, xerrors.Errorf("Unknown format: %s", line) + return containers, fmt.Errorf("Unknown format: %s", line) } containers = append(containers, config.Container{ ContainerID: fields[0], @@ -331,7 +331,7 @@ func (l *base) ip() ([]string, []string, error) { // 2: eth0 inet6 fe80::5054:ff:fe2a:864c/64 scope link \ valid_lft forever preferred_lft forever r := l.exec("/sbin/ip -o addr", noSudo) if !r.isSuccess() { - return nil, nil, xerrors.Errorf("Failed to detect IP address: %v", r) + return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r) } ipv4Addrs, ipv6Addrs := l.parseIP(r.Stdout) return ipv4Addrs, ipv6Addrs, nil @@ -420,10 +420,10 @@ func (l *base) detectDeepSecurity() (string, error) { line := strings.TrimSpace(r.Stdout) return line[len(dsFingerPrintPrefix):], nil } - l.warns = append(l.warns, xerrors.New("Fail to retrieve deepsecurity fingerprint")) + l.warns = append(l.warns, errors.New("Fail to retrieve deepsecurity fingerprint")) } } - return "", xerrors.Errorf("Failed to detect deepsecurity %s", l.ServerInfo.ServerName) + return "", fmt.Errorf("Failed to detect deepsecurity %s", l.ServerInfo.ServerName) } func (l *base) detectIPS() { @@ -490,7 +490,7 @@ func (l *base) detectRunningOnAws() (ok bool, instanceID string, err error) { return false, "", nil } } - return false, "", xerrors.Errorf( + return false, "", fmt.Errorf( "Failed to curl or wget to AWS instance metadata on %s. container: %s", l.ServerInfo.ServerName, l.ServerInfo.Container.Name) } @@ -579,7 +579,7 @@ func (l *base) detectInitSystem() (string, error) { f = func(cmd string) (string, error) { r := l.exec(cmd, sudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to stat %s: %s", cmd, r) + return "", fmt.Errorf("Failed to stat %s: %s", cmd, r) } scanner := bufio.NewScanner(strings.NewReader(r.Stdout)) scanner.Scan() @@ -601,7 +601,7 @@ func (l *base) detectInitSystem() (string, error) { } return sysVinit, nil } - return "", xerrors.Errorf("Failed to detect a init system: %s", line) + return "", fmt.Errorf("Failed to detect a init system: %s", line) } return f("stat /proc/1/exe") } @@ -610,7 +610,7 @@ func (l *base) detectServiceName(pid string) (string, error) { cmd := fmt.Sprintf("systemctl status --quiet --no-pager %s", pid) r := l.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to stat %s: %s", cmd, r) + return "", fmt.Errorf("Failed to stat %s: %s", cmd, r) } return l.parseSystemctlStatus(r.Stdout), nil } @@ -672,7 +672,7 @@ func (l *base) scanLibraries() (err error) { // find / -type f -and \( -name "package-lock.json" -o -name "yarn.lock" ... \) 2>&1 | grep -v "find: " r := l.exec(fmt.Sprintf(`find %s -type f -and \( %s \) 2>&1 | grep -v "find: "`, dir, findopt), priv) if r.ExitStatus != 0 && r.ExitStatus != 1 { - return xerrors.Errorf("Failed to find lock files: %s", r) + return fmt.Errorf("Failed to find lock files: %s", r) } scanner := bufio.NewScanner(strings.NewReader(r.Stdout)) @@ -680,7 +680,7 @@ func (l *base) scanLibraries() (err error) { detectFiles = append(detectFiles, scanner.Text()) } if err := scanner.Err(); err != nil { - return xerrors.Errorf("Failed to reading find results. err: %w", err) + return fmt.Errorf("Failed to reading find results. err: %w", err) } } @@ -697,13 +697,13 @@ func (l *base) scanLibraries() (err error) { r := l.exec("pwd", noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to get current directory. err: %w", r.Error) + return "", fmt.Errorf("Failed to get current directory. err: %w", r.Error) } return ufilepath.Join(strings.TrimSuffix(r.Stdout, "\n"), path), nil }() if err != nil { - return xerrors.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) + return fmt.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) } if _, ok := found[abspath]; ok { @@ -715,18 +715,18 @@ func (l *base) scanLibraries() (err error) { filemode, contents, err := func() (os.FileMode, []byte, error) { r := l.exec(fmt.Sprintf(`stat -c "%%a" %s`, abspath), priv) if !r.isSuccess() { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to get target file permission. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to get target file permission. filepath: %s, err: %w", abspath, err) } permStr := fmt.Sprintf("0%s", strings.TrimSuffix(r.Stdout, "\n")) perm, err := strconv.ParseUint(permStr, 8, 32) if err != nil { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to parse permission string. , permission string: %s, err: %s", permStr, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to parse permission string. , permission string: %s, err: %s", permStr, err) } filemode := os.FileMode(perm) r = l.exec(fmt.Sprintf("cat %s", abspath), priv) if !r.isSuccess() { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) } contents := []byte(r.Stdout) @@ -739,7 +739,7 @@ func (l *base) scanLibraries() (err error) { libraryScanners, err := AnalyzeLibrary(context.Background(), abspath, contents, filemode, l.ServerInfo.Mode.IsOffline()) if err != nil { - return xerrors.Errorf("Failed to analyze library. err: %w, filepath: %s", err, abspath) + return fmt.Errorf("Failed to analyze library. err: %w, filepath: %s", err, abspath) } for _, libscanner := range libraryScanners { libscanner.LockfilePath = abspath @@ -756,7 +756,7 @@ func AnalyzeLibrary(ctx context.Context, path string, contents []byte, filemode DisabledAnalyzers: disabledAnalyzers, }) if err != nil { - return nil, xerrors.Errorf("Failed to new analyzer group. err: %w", err) + return nil, fmt.Errorf("Failed to new analyzer group. err: %w", err) } // `errgroup` cancels the context after Wait returns, so it can’t be use later. @@ -778,17 +778,17 @@ func AnalyzeLibrary(ctx context.Context, path string, contents []byte, filemode nil, opts, ); err != nil { - return nil, xerrors.Errorf("Failed to get libs. err: %w", err) + return nil, fmt.Errorf("Failed to get libs. err: %w", err) } if err := eg.Wait(); err != nil { - return nil, xerrors.Errorf("analyze error: %w", err) + return nil, fmt.Errorf("analyze error: %w", err) } // Post-analysis composite, err := ag.PostAnalyzerFS() if err != nil { - return nil, xerrors.Errorf("Failed to prepare filesystem for post-analysis. err: %w", err) + return nil, fmt.Errorf("Failed to prepare filesystem for post-analysis. err: %w", err) } defer func() { _ = composite.Cleanup() @@ -799,19 +799,19 @@ func AnalyzeLibrary(ctx context.Context, path string, contents []byte, filemode opener := func() (xio.ReadSeekCloserAt, error) { return xio.NopCloser(bytes.NewReader(contents)), nil } tmpFilePath, err := composite.CopyFileToTemp(opener, info) if err != nil { - return nil, xerrors.Errorf("Failed to copy file to temp. err: %w", err) + return nil, fmt.Errorf("Failed to copy file to temp. err: %w", err) } if err := composite.CreateLink(analyzerTypes, "", path, tmpFilePath); err != nil { - return nil, xerrors.Errorf("Failed to create link. err: %w", err) + return nil, fmt.Errorf("Failed to create link. err: %w", err) } if err = ag.PostAnalyze(ctx, composite, result, opts); err != nil { - return nil, xerrors.Errorf("Failed at post-analysis. err: %w", err) + return nil, fmt.Errorf("Failed at post-analysis. err: %w", err) } } libscan, err := convertLibWithScanner(result.Applications) if err != nil { - return nil, xerrors.Errorf("Failed to convert libs. err: %w", err) + return nil, fmt.Errorf("Failed to convert libs. err: %w", err) } libraryScanners = append(libraryScanners, libscan...) return libraryScanners, nil @@ -943,24 +943,24 @@ func (l *base) scanWordPress() error { shell, err := l.detectShell() if err != nil { - return xerrors.Errorf("Failed to detect shell. err: %w", err) + return fmt.Errorf("Failed to detect shell. err: %w", err) } l.log.Info("Scanning WordPress...") if l.ServerInfo.WordPress.NoSudo && l.ServerInfo.User != l.ServerInfo.WordPress.OSUser { if r := l.exec(fmt.Sprintf("timeout 2 su %s -c exit", l.ServerInfo.WordPress.OSUser), noSudo); !r.isSuccess() { - return xerrors.New("Failed to switch user without password. err: please configure to switch users without password") + return errors.New("Failed to switch user without password. err: please configure to switch users without password") } } cmd := l.buildWpCliCmd("core version", false, shell) if r := exec(l.ServerInfo, cmd, noSudo); !r.isSuccess() { - return xerrors.Errorf("Failed to exec `%s`. Check the OS user, command path of wp-cli, DocRoot and permission: %#v", cmd, l.ServerInfo.WordPress) + return fmt.Errorf("Failed to exec `%s`. Check the OS user, command path of wp-cli, DocRoot and permission: %#v", cmd, l.ServerInfo.WordPress) } wp, err := l.detectWordPress(shell) if err != nil { - return xerrors.Errorf("Failed to scan wordpress: %w", err) + return fmt.Errorf("Failed to scan wordpress: %w", err) } l.WordPress = *wp return nil @@ -989,7 +989,7 @@ func (l *base) detectShell() (string, error) { } } - return "", xerrors.New("shell cannot be determined") + return "", errors.New("shell cannot be determined") } func (l *base) detectWordPress(shell string) (*models.WordPressPackages, error) { @@ -1025,7 +1025,7 @@ func (l *base) detectWpCore(shell string) (string, error) { r := exec(l.ServerInfo, cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to get wp core version: %s", r) + return "", fmt.Errorf("Failed to get wp core version: %s", r) } return strings.TrimSpace(r.Stdout), nil } @@ -1036,11 +1036,11 @@ func (l *base) detectWpThemes(shell string) ([]models.WpPackage, error) { var themes []models.WpPackage r := exec(l.ServerInfo, cmd, noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to get a list of WordPress plugins: %s", r) + return nil, fmt.Errorf("Failed to get a list of WordPress plugins: %s", r) } err := json.Unmarshal([]byte(r.Stdout), &themes) if err != nil { - return nil, xerrors.Errorf("Failed to unmarshal wp theme list: %w", err) + return nil, fmt.Errorf("Failed to unmarshal wp theme list: %w", err) } for i := range themes { themes[i].Type = models.WPTheme @@ -1054,7 +1054,7 @@ func (l *base) detectWpPlugins(shell string) ([]models.WpPackage, error) { var plugins []models.WpPackage r := exec(l.ServerInfo, cmd, noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to wp plugin list: %s", r) + return nil, fmt.Errorf("Failed to wp plugin list: %s", r) } if err := json.Unmarshal([]byte(r.Stdout), &plugins); err != nil { return nil, err @@ -1175,7 +1175,7 @@ func nativeScanPort(scanDest string) (bool, error) { return false, err } if err := conn.Close(); err != nil { - return false, xerrors.Errorf("Failed to close connection. err: %w", err) + return false, fmt.Errorf("Failed to close connection. err: %w", err) } return true, nil @@ -1200,7 +1200,7 @@ func (l *base) execExternalPortScan(scanDestIPPorts map[string][]string) ([]stri scanner, err := nmap.NewScanner(nmap.WithBinaryPath(portScanConf.ScannerBinPath)) if err != nil { - return []string{}, xerrors.Errorf("unable to create nmap scanner: %w", err) + return []string{}, fmt.Errorf("unable to create nmap scanner: %w", err) } scanTechnique, err := l.setScanTechniques() @@ -1218,7 +1218,7 @@ func (l *base) execExternalPortScan(scanDestIPPorts map[string][]string) ([]stri if portScanConf.SourcePort != "" { port, err := strconv.ParseUint(portScanConf.SourcePort, 10, 16) if err != nil { - return []string{}, xerrors.Errorf("failed to strconv.ParseUint(%s, 10, 16) = %w", portScanConf.SourcePort, err) + return []string{}, fmt.Errorf("failed to strconv.ParseUint(%s, 10, 16) = %w", portScanConf.SourcePort, err) } scanner.AddOptions(nmap.WithSourcePort(uint16(port))) } @@ -1235,7 +1235,7 @@ func (l *base) execExternalPortScan(scanDestIPPorts map[string][]string) ([]stri l.log.Debugf("Executing... %s", strings.ReplaceAll(strings.Join(cmd, " "), "\n", "")) result, warnings, err := scanner.Run() if err != nil { - return []string{}, xerrors.Errorf("unable to run nmap scan: %w", err) + return []string{}, fmt.Errorf("unable to run nmap scan: %w", err) } if warnings != nil { @@ -1307,7 +1307,7 @@ func (l *base) setScanTechniques() (func(*nmap.Scanner), error) { } } - return nil, xerrors.Errorf("Failed to setScanTechniques. There is an unsupported option in ScanTechniques.") + return nil, fmt.Errorf("failed to setScanTechniques: there is an unsupported option in ScanTechniques") } func (l *base) updatePortStatus(listenIPPorts []string) { @@ -1351,7 +1351,7 @@ func (l *base) ps() (string, error) { cmd := `LANGUAGE=en_US.UTF-8 ps --no-headers --ppid 2 -p 2 --deselect -o pid,comm` r := l.exec(util.PrependProxyEnv(cmd), noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to SSH: %s", r) + return "", fmt.Errorf("Failed to SSH: %s", r) } return r.Stdout, nil } @@ -1374,7 +1374,7 @@ func (l *base) lsProcExe(pid string) (string, error) { cmd := fmt.Sprintf("ls -l /proc/%s/exe", pid) r := l.exec(util.PrependProxyEnv(cmd), sudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to SSH: %s", r) + return "", fmt.Errorf("Failed to SSH: %s", r) } return r.Stdout, nil } @@ -1382,7 +1382,7 @@ func (l *base) lsProcExe(pid string) (string, error) { func (l *base) parseLsProcExe(stdout string) (string, error) { ss := strings.Fields(stdout) if len(ss) < 11 { - return "", xerrors.Errorf("Unknown format: %s", stdout) + return "", fmt.Errorf("Unknown format: %s", stdout) } return ss[10], nil } @@ -1391,7 +1391,7 @@ func (l *base) grepProcMap(pid string) (string, error) { cmd := fmt.Sprintf(`cat /proc/%s/maps 2>/dev/null | grep -v " 00:00 " | awk '{print $6}' | sort -n | uniq`, pid) r := l.exec(util.PrependProxyEnv(cmd), sudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to SSH: %s", r) + return "", fmt.Errorf("Failed to SSH: %s", r) } return r.Stdout, nil } @@ -1410,7 +1410,7 @@ func (l *base) lsOfListen() (string, error) { cmd := `lsof -i -P -n` r := l.exec(util.PrependProxyEnv(cmd), sudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to lsof: %s", r) + return "", fmt.Errorf("Failed to lsof: %s", r) } return r.Stdout, nil } @@ -1436,7 +1436,7 @@ func (l *base) parseLsOf(stdout string) map[string][]string { func (l *base) pkgPs(getOwnerPkgs func([]string) ([]string, error)) error { stdout, err := l.ps() if err != nil { - return xerrors.Errorf("Failed to pkgPs: %w", err) + return fmt.Errorf("Failed to pkgPs: %w", err) } pidNames := l.parsePs(stdout) pidLoadedFiles := map[string][]string{} diff --git a/scanner/debian.go b/scanner/debian.go index b62a9e0822..d0022e9ebe 100644 --- a/scanner/debian.go +++ b/scanner/debian.go @@ -4,6 +4,7 @@ import ( "bufio" "crypto/rand" "encoding/binary" + "errors" "fmt" "regexp" "slices" @@ -18,7 +19,6 @@ import ( "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" version "github.com/knqyf263/go-deb-version" - "golang.org/x/xerrors" ) // inherit OsTypeInterface @@ -146,7 +146,7 @@ func (o *debian) checkIfSudoNoPasswd() error { r := o.exec(cmd, sudo) if !r.isSuccess() { o.log.Errorf("sudo error on %s", r) - return xerrors.Errorf("Failed to sudo: %s", r) + return fmt.Errorf("Failed to sudo: %s", r) } } @@ -157,7 +157,7 @@ func (o *debian) checkIfSudoNoPasswd() error { r := o.exec(cmd, sudo) if !r.isSuccess() { o.log.Errorf("sudo error on %s", r) - return xerrors.Errorf("Failed to sudo: %s", r) + return fmt.Errorf("Failed to sudo: %s", r) } } @@ -216,7 +216,7 @@ func (o *debian) checkDeps() error { } dep.logFunc(msg) if dep.required { - return xerrors.New(msg) + return errors.New(msg) } continue } @@ -228,7 +228,7 @@ func (o *debian) checkDeps() error { } dep.logFunc(msg) if dep.required { - return xerrors.New(msg) + return errors.New(msg) } } @@ -249,14 +249,14 @@ func (o *debian) preCure() error { func (o *debian) postScan() error { if o.getServerInfo().Mode.IsDeep() || o.getServerInfo().Mode.IsFastRoot() { if err := o.pkgPs(o.getOwnerPkgs); err != nil { - err = xerrors.Errorf("Failed to dpkg-ps: %w", err) + err = fmt.Errorf("Failed to dpkg-ps: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error } if err := o.checkrestart(); err != nil { - err = xerrors.Errorf("Failed to scan need-restarting processes: %w", err) + err = fmt.Errorf("Failed to scan need-restarting processes: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -335,7 +335,7 @@ func (o *debian) rebootRequired() (bool, error) { case 1: return false, nil default: - return false, xerrors.Errorf("Failed to check reboot required: %s", r) + return false, fmt.Errorf("Failed to check reboot required: %s", r) } } @@ -345,7 +345,7 @@ func (o *debian) scanInstalledPackages() (models.Packages, models.Packages, mode updatable := models.Packages{} r := o.exec(dpkgQuery, noSudo) if !r.isSuccess() { - return nil, nil, nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, nil, nil, fmt.Errorf("Failed to SSH: %s", r) } installed, srcPacks, err := o.parseInstalledPackages(r.Stdout) @@ -376,7 +376,7 @@ func (o *debian) scanInstalledPackages() (models.Packages, models.Packages, mode // Fill the candidate versions of upgradable packages err = o.fillCandidateVersion(updatable) if err != nil { - return nil, nil, nil, xerrors.Errorf("Failed to fill candidate versions. err: %w", err) + return nil, nil, nil, fmt.Errorf("Failed to fill candidate versions. err: %w", err) } installed.MergeNewVersion(updatable) @@ -396,7 +396,7 @@ func (o *debian) parseInstalledPackages(stdout string) (models.Packages, models. if trimmed := strings.TrimSpace(line); len(trimmed) != 0 { name, status, version, srcName, srcVersion, err := o.parseScannedPackagesLine(trimmed) if err != nil || len(status) < 2 { - return nil, nil, xerrors.Errorf( + return nil, nil, fmt.Errorf( "Debian: Failed to parse package line: %s", line) } @@ -454,7 +454,7 @@ func (o *debian) parseInstalledPackages(stdout string) (models.Packages, models. } } default: - return nil, nil, xerrors.Errorf("unknown distro: %s", o.getDistro().Family) + return nil, nil, fmt.Errorf("unknown distro: %s", o.getDistro().Family) } } } @@ -514,14 +514,14 @@ func (o *debian) parseScannedPackagesLine(line string) (name, status, version, s return } - return "", "", "", "", "", xerrors.Errorf("Unknown format: %s", line) + return "", "", "", "", "", fmt.Errorf("Unknown format: %s", line) } func (o *debian) aptGetUpdate() error { o.log.Infof("apt-get update...") cmd := util.PrependProxyEnv("apt-get update") if r := o.exec(cmd, sudo); !r.isSuccess() { - return xerrors.Errorf("Failed to apt-get update: %s", r) + return fmt.Errorf("Failed to apt-get update: %s", r) } return nil } @@ -563,14 +563,14 @@ func (o *debian) scanUnsecurePackages(updatable models.Packages) (models.VulnInf // Collect CVE information of upgradable packages vulnInfos, err := o.scanChangelogs(updatable, meta, tmpClogPath) if err != nil { - return nil, xerrors.Errorf("Failed to scan unsecure packages. err: %w", err) + return nil, fmt.Errorf("Failed to scan unsecure packages. err: %w", err) } // Delete a directory for saving changelog to get changelog in Raspbian if o.Distro.Family == constant.Raspbian { err := o.deleteTempChangelogDir(tmpClogPath) if err != nil { - return nil, xerrors.Errorf("Failed to delete directory to save changelog for Raspbian. err: %w", err) + return nil, fmt.Errorf("Failed to delete directory to save changelog for Raspbian. err: %w", err) } } @@ -581,7 +581,7 @@ func (o *debian) ensureChangelogCache(current cache.Meta) (*cache.Meta, error) { // Search from cache cached, found, err := cache.DB.GetMeta(current.Name) if err != nil { - return nil, xerrors.Errorf( + return nil, fmt.Errorf( "Failed to get meta. Please remove cache.db and then try again. err: %w", err) } @@ -589,7 +589,7 @@ func (o *debian) ensureChangelogCache(current cache.Meta) (*cache.Meta, error) { o.log.Debugf("Not found in meta: %s", current.Name) err = cache.DB.EnsureBuckets(current) if err != nil { - return nil, xerrors.Errorf("Failed to ensure buckets. err: %w", err) + return nil, fmt.Errorf("Failed to ensure buckets. err: %w", err) } return ¤t, nil } @@ -599,7 +599,7 @@ func (o *debian) ensureChangelogCache(current cache.Meta) (*cache.Meta, error) { o.log.Debugf("Need to refresh meta: %s", current.Name) err = cache.DB.EnsureBuckets(current) if err != nil { - return nil, xerrors.Errorf("Failed to ensure buckets. err: %w", err) + return nil, fmt.Errorf("Failed to ensure buckets. err: %w", err) } return ¤t, nil @@ -608,7 +608,7 @@ func (o *debian) ensureChangelogCache(current cache.Meta) (*cache.Meta, error) { o.log.Debugf("Reuse meta: %s", current.Name) if config.Conf.Debug { if err := cache.DB.PrettyPrint(current); err != nil { - return nil, xerrors.Errorf("Failed to pretty print: %w", err) + return nil, fmt.Errorf("Failed to pretty print: %w", err) } } return &cached, nil @@ -622,17 +622,17 @@ func (o *debian) fillCandidateVersion(updatables models.Packages) (err error) { cmd := fmt.Sprintf("LANGUAGE=en_US.UTF-8 apt-cache policy %s", strings.Join(names, " ")) r := o.exec(cmd, noSudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to SSH: %s", r) + return fmt.Errorf("Failed to SSH: %s", r) } packAptPolicy := o.splitAptCachePolicy(r.Stdout) for k, v := range packAptPolicy { ver, err := o.parseAptCachePolicy(v, k) if err != nil { - return xerrors.Errorf("Failed to parse %w", err) + return fmt.Errorf("Failed to parse %w", err) } pack, ok := updatables[k] if !ok { - return xerrors.Errorf("Not found: %s", k) + return fmt.Errorf("Not found: %s", k) } pack.NewVersion = ver.Candidate pack.Repository = ver.Repo @@ -647,7 +647,7 @@ func (o *debian) getUpdatablePackNames() (packNames []string, err error) { if r.isSuccess(0, 1) { return o.parseAptGetUpgrade(r.Stdout) } - return packNames, xerrors.Errorf( + return packNames, fmt.Errorf( "Failed to %s. status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } @@ -669,11 +669,11 @@ func (o *debian) parseAptGetUpgrade(stdout string) (updatableNames []string, err if len(result) == 2 { nUpdatable, err := strconv.Atoi(result[1]) if err != nil { - return nil, xerrors.Errorf( + return nil, fmt.Errorf( "Failed to scan upgradable packages number. line: %s", line) } if nUpdatable != len(updatableNames) { - return nil, xerrors.Errorf( + return nil, fmt.Errorf( "Failed to scan upgradable packages, expected: %s, detected: %d", result[1], len(updatableNames)) } @@ -688,7 +688,7 @@ func (o *debian) parseAptGetUpgrade(stdout string) (updatableNames []string, err } if !stopLineFound { // There are upgrades, but not found the stop line. - return nil, xerrors.New("Failed to scan upgradable packages") + return nil, errors.New("Failed to scan upgradable packages") } return } @@ -703,7 +703,7 @@ func (o *debian) makeTempChangelogDir() (string, error) { cmd = util.PrependProxyEnv(cmd) r := o.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to create directory to save changelog for Raspbian. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) + return "", fmt.Errorf("Failed to create directory to save changelog for Raspbian. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } return path, nil } @@ -711,7 +711,7 @@ func (o *debian) makeTempChangelogDir() (string, error) { func generateSuffix() (string, error) { var n uint64 if err := binary.Read(rand.Reader, binary.LittleEndian, &n); err != nil { - return "", xerrors.Errorf("Failed to generate Suffix. err: %w", err) + return "", fmt.Errorf("Failed to generate Suffix. err: %w", err) } return strconv.FormatUint(n, 36), nil } @@ -721,7 +721,7 @@ func (o *debian) deleteTempChangelogDir(tmpClogPath string) error { cmd = util.PrependProxyEnv(cmd) r := o.exec(cmd, noSudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to delete directory to save changelog for Raspbian. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) + return fmt.Errorf("Failed to delete directory to save changelog for Raspbian. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } return nil } @@ -802,11 +802,11 @@ func (o *debian) scanChangelogs(updatablePacks models.Packages, meta *cache.Meta case err := <-errChan: errs = append(errs, err) case <-timeout: - errs = append(errs, xerrors.New("Timeout scanPackageCveIDs")) + errs = append(errs, errors.New("Timeout scanPackageCveIDs")) } } if 0 < len(errs) { - return nil, xerrors.Errorf("errs: %w", errs) + return nil, fmt.Errorf("errs: %w", errors.Join(errs...)) } cveIDs := []DetectedCveID{} @@ -899,7 +899,7 @@ func (o *debian) fetchParseChangelog(pack models.Package, tmpClogPath string) ([ err := cache.DB.PutChangelog( o.getServerInfo().GetServerName(), pack.Name, stdout) if err != nil { - return nil, nil, xerrors.New("Failed to put changelog into cache") + return nil, nil, errors.New("Failed to put changelog into cache") } } @@ -913,14 +913,14 @@ func (o *debian) getChangelogPath(packName, tmpClogPath string) (string, error) cmd = util.PrependProxyEnv(cmd) r := o.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to Fetch deb package. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) + return "", fmt.Errorf("Failed to Fetch deb package. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } cmd = fmt.Sprintf(`find %s -name "%s_*.deb"`, tmpClogPath, packName) cmd = util.PrependProxyEnv(cmd) r = o.exec(cmd, noSudo) if !r.isSuccess() || r.Stdout == "" { - return "", xerrors.Errorf("Failed to find deb package. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) + return "", fmt.Errorf("Failed to find deb package. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } // e.g. /ffmpeg_7%3a4.1.6-1~deb10u1+rpt1_armhf.deb\n => /ffmpeg_7%3a4.1.6-1~deb10u1+rpt1_armhf @@ -929,7 +929,7 @@ func (o *debian) getChangelogPath(packName, tmpClogPath string) (string, error) cmd = util.PrependProxyEnv(cmd) r = o.exec(cmd, noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to dpkg-deb. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) + return "", fmt.Errorf("Failed to dpkg-deb. cmd: %s, status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } // recurse if doc/packName is symbolic link @@ -960,7 +960,7 @@ func (o *debian) getChangelogPath(packName, tmpClogPath string) (string, error) } results["changelog.gz"] = r - return "", xerrors.Errorf( + return "", fmt.Errorf( "Failed to get changelog.\nresult(changelog.Debian.gz):%v\nresult(changelog.Debian.gz):%v", results["changelog.Debian.gz"], results["changelog.gz"]) } @@ -1031,7 +1031,7 @@ var cveRe = regexp.MustCompile(`(CVE-\d{4}-\d{4,})`) func (o *debian) parseChangelog(changelog, name, ver string, confidence models.Confidence) ([]DetectedCveID, *models.Package, error) { installedVer, err := version.NewVersion(ver) if err != nil { - return nil, nil, xerrors.Errorf("Failed to parse installed version: %s, err: %w", ver, err) + return nil, nil, fmt.Errorf("Failed to parse installed version: %s, err: %w", ver, err) } buf, cveIDs := []string{}, []string{} scanner := bufio.NewScanner(strings.NewReader(changelog)) @@ -1084,7 +1084,7 @@ func (o *debian) parseChangelog(changelog, name, ver string, confidence models.C Contents: "", Method: models.FailedToFindVersionInChangelog, } - return nil, &pack, xerrors.Errorf( + return nil, &pack, fmt.Errorf( "Failed to scan CVE IDs. The version is not in changelog. name: %s, version: %s", name, ver) } @@ -1166,7 +1166,7 @@ func (o *debian) parseAptCachePolicy(stdout, name string) (packCandidateVer, err } nextline: } - return ver, xerrors.Errorf("Unknown Format: %s", stdout) + return ver, fmt.Errorf("Unknown Format: %s", stdout) } func (o *debian) checkrestart() error { @@ -1179,7 +1179,7 @@ func (o *debian) checkrestart() error { cmd := "LANGUAGE=en_US.UTF-8 checkrestart" r := o.exec(cmd, sudo) if !r.isSuccess() { - return xerrors.Errorf( + return fmt.Errorf( "Failed to %s. status: %d, stdout: %s, stderr: %s", cmd, r.ExitStatus, r.Stdout, r.Stderr) } @@ -1310,7 +1310,7 @@ func (o *debian) getOwnerPkgs(paths []string) (pkgNames []string, err error) { cmd := "dpkg -S " + strings.Join(paths, " ") r := o.exec(util.PrependProxyEnv(cmd), noSudo) if !r.isSuccess(0, 1) { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } return o.parseGetPkgName(r.Stdout), nil } diff --git a/scanner/executil.go b/scanner/executil.go index 71f60f2f2a..042a333fc2 100644 --- a/scanner/executil.go +++ b/scanner/executil.go @@ -18,7 +18,6 @@ import ( "golang.org/x/text/encoding/japanese" "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" - "golang.org/x/xerrors" "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" @@ -127,7 +126,7 @@ func parallelExec(fn func(osTypeInterface) error, timeoutSec ...int) { } } if !found { - err := xerrors.Errorf("Timed out: %s", s.getServerInfo().GetServerName()) + err := fmt.Errorf("Timed out: %s", s.getServerInfo().GetServerName()) logging.Log.Errorf("%+v", err) s.setErrs([]error{err}) errServers = append(errServers, s) diff --git a/scanner/freebsd.go b/scanner/freebsd.go index 7a7682eb06..5a3d5459b3 100644 --- a/scanner/freebsd.go +++ b/scanner/freebsd.go @@ -2,6 +2,7 @@ package scanner import ( "bufio" + "errors" "fmt" "maps" "strings" @@ -11,7 +12,6 @@ import ( "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ) // inherit OsTypeInterface @@ -55,7 +55,7 @@ func detectFreebsd(c config.ServerInfo) (bool, osTypeInterface) { func (o *bsd) checkScanMode() error { if o.getServerInfo().Mode.IsOffline() { - return xerrors.New("Remove offline scan mode, FreeBSD needs internet connection") + return errors.New("Remove offline scan mode, FreeBSD needs internet connection") } return nil } @@ -87,7 +87,7 @@ func (o *bsd) postScan() error { func (o *bsd) detectIPAddr() (err error) { r := o.exec("/sbin/ifconfig", noSudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to detect IP address: %v", r) + return fmt.Errorf("Failed to detect IP address: %v", r) } o.ServerInfo.IPv4Addrs, o.ServerInfo.IPv6Addrs = o.parseIfconfig(r.Stdout) return nil @@ -108,7 +108,7 @@ func (o *bsd) scanPackages() error { o.Kernel.RebootRequired, err = o.rebootRequired() if err != nil { - err = xerrors.Errorf("Failed to detect the kernel reboot required: %w", err) + err = fmt.Errorf("Failed to detect the kernel reboot required: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -137,7 +137,7 @@ func (o *bsd) parseInstalledPackages(string) (models.Packages, models.SrcPackage func (o *bsd) rebootRequired() (bool, error) { r := o.exec("freebsd-version -k", noSudo) if !r.isSuccess() { - return false, xerrors.Errorf("Failed to SSH: %s", r) + return false, fmt.Errorf("Failed to SSH: %s", r) } return o.Kernel.Release != strings.TrimSpace(r.Stdout), nil } @@ -147,14 +147,14 @@ func (o *bsd) scanInstalledPackages() (models.Packages, error) { cmd := util.PrependProxyEnv("pkg info") r := o.exec(cmd, noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } pkgs := o.parsePkgInfo(r.Stdout) cmd = util.PrependProxyEnv("pkg version -v") r = o.exec(cmd, noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } // `pkg-audit` has a new version, overwrite it. maps.Copy(pkgs, o.parsePkgVersion(r.Stdout)) @@ -166,13 +166,13 @@ func (o *bsd) scanUnsecurePackages() (models.VulnInfos, error) { cmd := "rm -f " + vulndbPath r := o.exec(cmd, noSudo) if !r.isSuccess(0) { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } cmd = util.PrependProxyEnv("pkg audit -F -r -f " + vulndbPath) r = o.exec(cmd, noSudo) if !r.isSuccess(0, 1) { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } if r.ExitStatus == 0 { // no vulnerabilities @@ -188,7 +188,7 @@ func (o *bsd) scanUnsecurePackages() (models.VulnInfos, error) { } pack, found := o.Packages[name] if !found { - return nil, xerrors.Errorf("Vulnerable package: %s is not found", name) + return nil, fmt.Errorf("Vulnerable package: %s is not found", name) } packAdtRslt = append(packAdtRslt, pkgAuditResult{ pack: pack, diff --git a/scanner/macos.go b/scanner/macos.go index b3734ce2dc..75f252d573 100644 --- a/scanner/macos.go +++ b/scanner/macos.go @@ -2,12 +2,11 @@ package scanner import ( "bufio" + "errors" "fmt" "path/filepath" "strings" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/logging" @@ -38,7 +37,7 @@ func detectMacOS(c config.ServerInfo) (bool, osTypeInterface) { m := newMacOS(c) family, version, err := parseSWVers(r.Stdout) if err != nil { - m.setErrs([]error{xerrors.Errorf("Failed to parse sw_vers. err: %w", err)}) + m.setErrs([]error{fmt.Errorf("Failed to parse sw_vers. err: %w", err)}) return true, m } m.setDistro(family, version) @@ -60,7 +59,7 @@ func parseSWVers(stdout string) (string, string, error) { } } if err := scanner.Err(); err != nil { - return "", "", xerrors.Errorf("Failed to scan by the scanner. err: %w", err) + return "", "", fmt.Errorf("Failed to scan by the scanner. err: %w", err) } var family string @@ -74,11 +73,11 @@ func parseSWVers(stdout string) (string, string, error) { case "macOS Server": family = constant.MacOSServer default: - return "", "", xerrors.Errorf("Failed to detect MacOS Family. err: \"%s\" is unexpected product name", name) + return "", "", fmt.Errorf("Failed to detect MacOS Family. err: \"%s\" is unexpected product name", name) } if version == "" { - return "", "", xerrors.New("Failed to get ProductVersion string. err: ProductVersion is empty") + return "", "", errors.New("Failed to get ProductVersion string. err: ProductVersion is empty") } return family, version, nil @@ -107,7 +106,7 @@ func (o *macos) preCure() error { func (o *macos) detectIPAddr() (err error) { r := o.exec("/sbin/ifconfig", noSudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to detect IP address: %v", r) + return fmt.Errorf("Failed to detect IP address: %v", r) } o.ServerInfo.IPv4Addrs, o.ServerInfo.IPv6Addrs = o.parseIfconfig(r.Stdout) return nil @@ -133,7 +132,7 @@ func (o *macos) scanPackages() error { installed, err := o.scanInstalledPackages() if err != nil { - return xerrors.Errorf("Failed to scan installed packages. err: %w", err) + return fmt.Errorf("Failed to scan installed packages. err: %w", err) } o.Packages = installed @@ -143,7 +142,7 @@ func (o *macos) scanPackages() error { func (o *macos) scanInstalledPackages() (models.Packages, error) { r := o.exec("find -L /Applications /System/Applications -type f -path \"*.app/Contents/Info.plist\" -not -path \"*.app/**/*.app/*\"", noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to exec: %v", r) + return nil, fmt.Errorf("Failed to exec: %v", r) } installed := models.Packages{} @@ -174,7 +173,7 @@ func (o *macos) scanInstalledPackages() (models.Packages, error) { } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan by the scanner. err: %w", err) + return nil, fmt.Errorf("Failed to scan by the scanner. err: %w", err) } return installed, nil @@ -204,7 +203,7 @@ func (o *macos) parseInstalledPackages(stdout string) (models.Packages, models.S lhs, rhs, ok := strings.Cut(t, ":") if !ok { - return nil, nil, xerrors.Errorf("unexpected installed packages line. expected: \": \", actual: \"%s\"", t) + return nil, nil, fmt.Errorf("unexpected installed packages line. expected: \": \", actual: \"%s\"", t) } switch lhs { @@ -230,7 +229,7 @@ func (o *macos) parseInstalledPackages(stdout string) (models.Packages, models.S id = strings.TrimSpace(rhs) } default: - return nil, nil, xerrors.Errorf("unexpected installed packages line tag. expected: [\"Info.plist\", \"CFBundleDisplayName\", \"CFBundleName\", \"CFBundleShortVersionString\", \"CFBundleIdentifier\"], actual: \"%s\"", lhs) + return nil, nil, fmt.Errorf("unexpected installed packages line tag. expected: [\"Info.plist\", \"CFBundleDisplayName\", \"CFBundleName\", \"CFBundleShortVersionString\", \"CFBundleIdentifier\"], actual: \"%s\"", lhs) } } if file != "" { @@ -244,7 +243,7 @@ func (o *macos) parseInstalledPackages(stdout string) (models.Packages, models.S } } if err := scanner.Err(); err != nil { - return nil, nil, xerrors.Errorf("Failed to scan by the scanner. err: %w", err) + return nil, nil, fmt.Errorf("Failed to scan by the scanner. err: %w", err) } return pkgs, nil, nil diff --git a/scanner/pseudo.go b/scanner/pseudo.go index bbc642bce4..46a4fd470c 100644 --- a/scanner/pseudo.go +++ b/scanner/pseudo.go @@ -2,13 +2,12 @@ package scanner import ( "context" + "errors" "fmt" "os" "path/filepath" "strings" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/logging" @@ -92,7 +91,7 @@ func (o *pseudo) scanLibraries() (err error) { detectFiles := o.getServerInfo().Lockfiles if o.getServerInfo().FindLock { - return xerrors.New("FindLock is not supported in pseudo") + return errors.New("FindLock is not supported in pseudo") } found := make(map[string]bool) @@ -103,7 +102,7 @@ func (o *pseudo) scanLibraries() (err error) { abspath, err := filepath.Abs(path) if err != nil { - return xerrors.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) + return fmt.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) } if _, ok := found[abspath]; ok { @@ -114,13 +113,13 @@ func (o *pseudo) scanLibraries() (err error) { filemode, contents, err := func() (os.FileMode, []byte, error) { fileinfo, err := os.Stat(abspath) if err != nil { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to get target file info. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to get target file info. filepath: %s, err: %w", abspath, err) } filemode := fileinfo.Mode().Perm() contents, err := os.ReadFile(abspath) if err != nil { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) } return filemode, contents, nil @@ -133,7 +132,7 @@ func (o *pseudo) scanLibraries() (err error) { trivypath := o.cleanPath(abspath) libraryScanners, err := AnalyzeLibrary(context.Background(), trivypath, contents, filemode, o.getServerInfo().Mode.IsOffline()) if err != nil { - return xerrors.Errorf("Failed to analyze library. err: %w, filepath: %s", err, trivypath) + return fmt.Errorf("Failed to analyze library. err: %w, filepath: %s", err, trivypath) } for _, libscanner := range libraryScanners { libscanner.LockfilePath = abspath diff --git a/scanner/redhatbase.go b/scanner/redhatbase.go index 93a44ae560..e033492c36 100644 --- a/scanner/redhatbase.go +++ b/scanner/redhatbase.go @@ -12,7 +12,6 @@ import ( "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ver "github.com/knqyf263/go-rpm-version" ) @@ -26,17 +25,17 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { fed := newFedora(c) result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { - fed.setErrs([]error{xerrors.Errorf("Failed to parse /etc/fedora-release. r.Stdout: %s", r.Stdout)}) + fed.setErrs([]error{fmt.Errorf("Failed to parse /etc/fedora-release. r.Stdout: %s", r.Stdout)}) return true, fed } release := result[2] major, err := strconv.Atoi(util.Major(release)) if err != nil { - fed.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + fed.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, fed } if major < 32 { - fed.setErrs([]error{xerrors.Errorf("Failed to init Fedora. err: not supported major version. versions prior to Fedora 32 are not supported, detected version is %s", release)}) + fed.setErrs([]error{fmt.Errorf("Failed to init Fedora. err: not supported major version. versions prior to Fedora 32 are not supported, detected version is %s", release)}) return true, fed } fed.setDistro(constant.Fedora, release) @@ -51,17 +50,17 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { ora := newOracle(c) result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { - ora.setErrs([]error{xerrors.Errorf("Failed to parse /etc/oracle-release. r.Stdout: %s", r.Stdout)}) + ora.setErrs([]error{fmt.Errorf("Failed to parse /etc/oracle-release. r.Stdout: %s", r.Stdout)}) return true, ora } release := result[2] major, err := strconv.Atoi(util.Major(release)) if err != nil { - ora.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + ora.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, ora } if major < 5 { - ora.setErrs([]error{xerrors.Errorf("Failed to init Oracle Linux. err: not supported major version. versions prior to Oracle Linux 5 are not supported, detected version is %s", release)}) + ora.setErrs([]error{fmt.Errorf("Failed to init Oracle Linux. err: not supported major version. versions prior to Oracle Linux 5 are not supported, detected version is %s", release)}) return true, ora } ora.setDistro(constant.Oracle, release) @@ -74,18 +73,18 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { alma := newAlma(c) result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { - alma.setErrs([]error{xerrors.Errorf("Failed to parse /etc/almalinux-release. r.Stdout: %s", r.Stdout)}) + alma.setErrs([]error{fmt.Errorf("Failed to parse /etc/almalinux-release. r.Stdout: %s", r.Stdout)}) return true, alma } release := result[2] major, err := strconv.Atoi(util.Major(release)) if err != nil { - alma.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + alma.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, alma } if major < 8 { - alma.setErrs([]error{xerrors.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) + alma.setErrs([]error{fmt.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) return true, alma } switch strings.ToLower(result[1]) { @@ -93,7 +92,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { alma.setDistro(constant.Alma, release) return true, alma default: - alma.setErrs([]error{xerrors.Errorf("Failed to parse AlmaLinux Name. release: %s", release)}) + alma.setErrs([]error{fmt.Errorf("Failed to parse AlmaLinux Name. release: %s", release)}) return true, alma } } @@ -104,18 +103,18 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { rocky := newRocky(c) result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { - rocky.setErrs([]error{xerrors.Errorf("Failed to parse /etc/rocky-release. r.Stdout: %s", r.Stdout)}) + rocky.setErrs([]error{fmt.Errorf("Failed to parse /etc/rocky-release. r.Stdout: %s", r.Stdout)}) return true, rocky } release := result[2] major, err := strconv.Atoi(util.Major(release)) if err != nil { - rocky.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + rocky.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, rocky } if major < 8 { - rocky.setErrs([]error{xerrors.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) + rocky.setErrs([]error{fmt.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) return true, rocky } switch strings.ToLower(result[1]) { @@ -123,7 +122,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { rocky.setDistro(constant.Rocky, release) return true, rocky default: - rocky.setErrs([]error{xerrors.Errorf("Failed to parse Rocky Linux Name. release: %s", release)}) + rocky.setErrs([]error{fmt.Errorf("Failed to parse Rocky Linux Name. release: %s", release)}) return true, rocky } } @@ -136,7 +135,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { cent := newCentOS(c) - cent.setErrs([]error{xerrors.Errorf("Failed to parse /etc/centos-release. r.Stdout: %s", r.Stdout)}) + cent.setErrs([]error{fmt.Errorf("Failed to parse /etc/centos-release. r.Stdout: %s", r.Stdout)}) return true, cent } @@ -144,14 +143,14 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { major, err := strconv.Atoi(util.Major(release)) if err != nil { cent := newCentOS(c) - cent.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, cent } switch strings.ToLower(result[1]) { case "centos", "centos linux": cent := newCentOS(c) if major < 5 { - cent.setErrs([]error{xerrors.Errorf("Failed to init CentOS. err: not supported major version. versions prior to CentOS 5 are not supported, detected version is %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to init CentOS. err: not supported major version. versions prior to CentOS 5 are not supported, detected version is %s", release)}) return true, cent } cent.setDistro(constant.CentOS, release) @@ -159,7 +158,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "centos stream": cent := newCentOS(c) if major < 8 { - cent.setErrs([]error{xerrors.Errorf("Failed to init CentOS Stream. err: not supported major version. versions prior to CentOS Stream 8 are not supported, detected version is %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to init CentOS Stream. err: not supported major version. versions prior to CentOS Stream 8 are not supported, detected version is %s", release)}) return true, cent } cent.setDistro(constant.CentOS, fmt.Sprintf("stream%s", release)) @@ -167,7 +166,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "alma", "almalinux": alma := newAlma(c) if major < 8 { - alma.setErrs([]error{xerrors.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) + alma.setErrs([]error{fmt.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) return true, alma } alma.setDistro(constant.Alma, release) @@ -175,14 +174,14 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "rocky", "rocky linux": rocky := newRocky(c) if major < 8 { - rocky.setErrs([]error{xerrors.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) + rocky.setErrs([]error{fmt.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) return true, rocky } rocky.setDistro(constant.Rocky, release) return true, rocky default: cent := newCentOS(c) - cent.setErrs([]error{xerrors.Errorf("Failed to parse CentOS Name. release: %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to parse CentOS Name. release: %s", release)}) return true, cent } } @@ -197,18 +196,18 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { amazon := newAmazon(c) result := releasePattern.FindStringSubmatch(strings.TrimSpace(r.Stdout)) if len(result) != 3 { - amazon.setErrs([]error{xerrors.Errorf("Failed to parse /etc/amazon-linux-release. r.Stdout: %s", r.Stdout)}) + amazon.setErrs([]error{fmt.Errorf("Failed to parse /etc/amazon-linux-release. r.Stdout: %s", r.Stdout)}) return true, amazon } release := result[2] major, err := strconv.Atoi(util.Major(release)) if err != nil { - amazon.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + amazon.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, amazon } if major < 2022 { - amazon.setErrs([]error{xerrors.Errorf("Failed to init Amazon Linux. err: not supported major version. versions prior to Amazon Linux 2022 are not supported, detected version is %s", release)}) + amazon.setErrs([]error{fmt.Errorf("Failed to init Amazon Linux. err: not supported major version. versions prior to Amazon Linux 2022 are not supported, detected version is %s", release)}) return true, amazon } switch strings.ToLower(result[1]) { @@ -216,7 +215,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { amazon.setDistro(constant.Amazon, release) return true, amazon default: - amazon.setErrs([]error{xerrors.Errorf("Failed to parse Amazon Linux Name. release: %s", release)}) + amazon.setErrs([]error{fmt.Errorf("Failed to parse Amazon Linux Name. release: %s", release)}) return true, amazon } } @@ -239,14 +238,14 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { major, err := strconv.Atoi(util.Major(release)) if err != nil { rhel := newRHEL(c) - rhel.setErrs([]error{xerrors.Errorf("Failed to parse major version from release: %s", release)}) + rhel.setErrs([]error{fmt.Errorf("Failed to parse major version from release: %s", release)}) return true, rhel } switch strings.ToLower(result[1]) { case "fedora": fed := newFedora(c) if major < 32 { - fed.setErrs([]error{xerrors.Errorf("Failed to init Fedora. err: not supported major version. versions prior to Fedora 32 are not supported, detected version is %s", release)}) + fed.setErrs([]error{fmt.Errorf("Failed to init Fedora. err: not supported major version. versions prior to Fedora 32 are not supported, detected version is %s", release)}) return true, fed } fed.setDistro(constant.Fedora, release) @@ -254,7 +253,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "centos", "centos linux": cent := newCentOS(c) if major < 5 { - cent.setErrs([]error{xerrors.Errorf("Failed to init CentOS. err: not supported major version. versions prior to CentOS 5 are not supported, detected version is %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to init CentOS. err: not supported major version. versions prior to CentOS 5 are not supported, detected version is %s", release)}) return true, cent } cent.setDistro(constant.CentOS, release) @@ -262,7 +261,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "centos stream": cent := newCentOS(c) if major < 8 { - cent.setErrs([]error{xerrors.Errorf("Failed to init CentOS Stream. err: not supported major version. versions prior to CentOS Stream 8 are not supported, detected version is %s", release)}) + cent.setErrs([]error{fmt.Errorf("Failed to init CentOS Stream. err: not supported major version. versions prior to CentOS Stream 8 are not supported, detected version is %s", release)}) return true, cent } cent.setDistro(constant.CentOS, fmt.Sprintf("stream%s", release)) @@ -270,7 +269,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "alma", "almalinux": alma := newAlma(c) if major < 8 { - alma.setErrs([]error{xerrors.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) + alma.setErrs([]error{fmt.Errorf("Failed to init AlmaLinux. err: not supported major version. versions prior to AlmaLinux 8 are not supported, detected version is %s", release)}) return true, alma } alma.setDistro(constant.Alma, release) @@ -278,7 +277,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { case "rocky", "rocky linux": rocky := newRocky(c) if major < 8 { - rocky.setErrs([]error{xerrors.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) + rocky.setErrs([]error{fmt.Errorf("Failed to init Rocky Linux. err: not supported major version. versions prior to Rocky Linux 8 are not supported, detected version is %s", release)}) return true, rocky } rocky.setDistro(constant.Rocky, release) @@ -286,7 +285,7 @@ func detectRedhat(c config.ServerInfo) (bool, osTypeInterface) { default: rhel := newRHEL(c) if major < 5 { - rhel.setErrs([]error{xerrors.Errorf("Failed to init RedHat Enterprise Linux. err: not supported major version. versions prior to RedHat Enterprise Linux 5 are not supported, detected version is %s", release)}) + rhel.setErrs([]error{fmt.Errorf("Failed to init RedHat Enterprise Linux. err: not supported major version. versions prior to RedHat Enterprise Linux 5 are not supported, detected version is %s", release)}) return true, rhel } rhel.setDistro(constant.RedHat, release) @@ -360,7 +359,7 @@ func (o *redhatBase) execCheckIfSudoNoPasswd(cmds []cmd) error { r := o.exec(util.PrependProxyEnv(cmd), sudo) if !r.isSuccess(c.expectedStatusCodes...) { o.log.Errorf("Check sudo or proxy settings: %s", r) - return xerrors.Errorf("Failed to sudo: %s", r) + return fmt.Errorf("Failed to sudo: %s", r) } } o.log.Infof("Sudo... Pass") @@ -372,7 +371,7 @@ func (o *redhatBase) execCheckDeps(packNames []string) error { cmd := "rpm -q " + name if r := o.exec(cmd, noSudo); !r.isSuccess() { o.log.Errorf("%s is not installed", name) - return xerrors.Errorf("%s is not installed", name) + return fmt.Errorf("%s is not installed", name) } } o.log.Infof("Dependencies ... Pass") @@ -391,7 +390,7 @@ func (o *redhatBase) preCure() error { func (o *redhatBase) postScan() error { if o.isExecYumPS() { if err := o.pkgPs(o.getOwnerPkgs); err != nil { - err = xerrors.Errorf("Failed to execute yum-ps: %w", err) + err = fmt.Errorf("Failed to execute yum-ps: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -400,7 +399,7 @@ func (o *redhatBase) postScan() error { if o.isExecNeedsRestarting() { if err := o.needsRestarting(); err != nil { - err = xerrors.Errorf("Failed to execute need-restarting: %w", err) + err = fmt.Errorf("Failed to execute need-restarting: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -418,13 +417,13 @@ func (o *redhatBase) scanPackages() (err error) { o.log.Infof("Scanning OS pkg in %s", o.getServerInfo().Mode) o.Packages, o.SrcPackages, err = o.scanInstalledPackages() if err != nil { - return xerrors.Errorf("Failed to scan installed packages: %w", err) + return fmt.Errorf("Failed to scan installed packages: %w", err) } fn := func(pkgName string) execResult { return o.exec(fmt.Sprintf("rpm -q --last %s", pkgName), noSudo) } o.Kernel.RebootRequired, err = o.rebootRequired(fn) if err != nil { - err = xerrors.Errorf("Failed to detect the kernel reboot required: %w", err) + err = fmt.Errorf("Failed to detect the kernel reboot required: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -436,7 +435,7 @@ func (o *redhatBase) scanPackages() (err error) { updatable, err := o.scanUpdatablePackages() if err != nil { - err = xerrors.Errorf("Failed to scan updatable packages: %w", err) + err = fmt.Errorf("Failed to scan updatable packages: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -455,7 +454,7 @@ func (o *redhatBase) rebootRequired(fn func(s string) execResult) (bool, error) r := fn(pkgName) scanner := bufio.NewScanner(strings.NewReader(r.Stdout)) if !r.isSuccess(0, 1) { - return false, xerrors.Errorf("Failed to detect the last installed kernel : %v", r) + return false, fmt.Errorf("Failed to detect the last installed kernel : %v", r) } if !r.isSuccess() || !scanner.Scan() { return false, nil @@ -492,11 +491,11 @@ func (o *redhatBase) scanInstalledPackages() (models.Packages, models.SrcPackage r = o.exec(o.rpmQa(), noSudo) } if !r.isSuccess() { - return nil, nil, xerrors.Errorf("Scan packages failed: %s", r) + return nil, nil, fmt.Errorf("Scan packages failed: %s", r) } bins, srcs, err := o.parseInstalledPackages(r.Stdout) if err != nil { - return nil, nil, xerrors.Errorf("Failed to parse installed packages. err: %w", err) + return nil, nil, fmt.Errorf("Failed to parse installed packages. err: %w", err) } return bins, srcs, nil } @@ -529,7 +528,7 @@ func (o *redhatBase) parseInstalledPackages(stdout string) (models.Packages, mod case 7: binpkg, srcpkg, err = o.parseInstalledPackagesLineFromRepoquery(line) default: - return nil, nil, xerrors.Errorf("Failed to parse package line: %s", line) + return nil, nil, fmt.Errorf("Failed to parse package line: %s", line) } default: binpkg, srcpkg, err = o.parseInstalledPackagesLine(line) @@ -584,7 +583,7 @@ func (o *redhatBase) parseInstalledPackagesLine(line string) (*models.Package, * default: n, v, r, _, _, err := splitFileName(fields[5]) if err != nil { - o.warns = append(o.warns, xerrors.Errorf("Failed to parse source rpm file. err: %w", err)) + o.warns = append(o.warns, fmt.Errorf("Failed to parse source rpm file. err: %w", err)) return nil, nil } return &models.SrcPackage{ @@ -609,7 +608,7 @@ func (o *redhatBase) parseInstalledPackagesLine(line string) (*models.Package, * } }() if err != nil { - return nil, nil, xerrors.Errorf("Failed to parse sourcepkg. err: %w", err) + return nil, nil, fmt.Errorf("Failed to parse sourcepkg. err: %w", err) } return &models.Package{ @@ -632,7 +631,7 @@ func (o *redhatBase) parseInstalledPackagesLine(line string) (*models.Package, * }(), }, sp, nil default: - return nil, nil, xerrors.Errorf("Failed to parse package line: %s", line) + return nil, nil, fmt.Errorf("Failed to parse package line: %s", line) } } @@ -646,7 +645,7 @@ func (o *redhatBase) parseInstalledPackagesLineFromRepoquery(line string) (*mode default: n, v, r, _, _, err := splitFileName(fields[5]) if err != nil { - o.warns = append(o.warns, xerrors.Errorf("Failed to parse source rpm file. err: %w", err)) + o.warns = append(o.warns, fmt.Errorf("Failed to parse source rpm file. err: %w", err)) return nil, nil } return &models.SrcPackage{ @@ -671,7 +670,7 @@ func (o *redhatBase) parseInstalledPackagesLineFromRepoquery(line string) (*mode } }() if err != nil { - return nil, nil, xerrors.Errorf("Failed to parse sourcepkg. err: %w", err) + return nil, nil, fmt.Errorf("Failed to parse sourcepkg. err: %w", err) } return &models.Package{ @@ -696,7 +695,7 @@ func (o *redhatBase) parseInstalledPackagesLineFromRepoquery(line string) (*mode }(), }, sp, nil default: - return nil, nil, xerrors.Errorf("Failed to parse package line: %s", line) + return nil, nil, fmt.Errorf("Failed to parse package line: %s", line) } } @@ -719,19 +718,19 @@ func splitFileName(filename string) (name, ver, rel, epoch, arch string, err err archIndex = archIndex + (i + 1) } if archIndex == -1 { - return "", "", "", "", "", xerrors.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) + return "", "", "", "", "", fmt.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) } arch = basename[archIndex+1:] relIndex := strings.LastIndex(basename[:archIndex], "-") if relIndex == -1 { - return "", "", "", "", "", xerrors.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) + return "", "", "", "", "", fmt.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) } rel = basename[relIndex+1 : archIndex] verIndex := strings.LastIndex(basename[:relIndex], "-") if verIndex == -1 { - return "", "", "", "", "", xerrors.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) + return "", "", "", "", "", fmt.Errorf("unexpected file name. expected: %q, actual: %q", "(:)--()(.|-).rpm", filename) } ver = basename[verIndex+1 : relIndex] @@ -762,7 +761,7 @@ func (o *redhatBase) yumMakeCache() error { cmd := `yum makecache --assumeyes` r := o.exec(util.PrependProxyEnv(cmd), o.sudo.yumMakeCache()) if !r.isSuccess(0, 1) { - return xerrors.Errorf("Failed to SSH: %s", r) + return fmt.Errorf("Failed to SSH: %s", r) } return nil } @@ -791,7 +790,7 @@ func (o *redhatBase) scanUpdatablePackages() (models.Packages, error) { r := o.exec(util.PrependProxyEnv(cmd), o.sudo.repoquery()) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to SSH: %s", r) + return nil, fmt.Errorf("Failed to SSH: %s", r) } // Collect Updatable packages, installed, candidate version and repository. @@ -830,7 +829,7 @@ func (o *redhatBase) parseUpdatablePacksLine(line string) (*models.Package, erro switch fields := strings.Split(line, "\" \""); len(fields) { case 5: if !strings.HasPrefix(fields[0], "\"") { - return nil, xerrors.Errorf("unexpected format. expected: %q, actual: %q", "\"\" \"\" \"\" \"\" \"\"", line) + return nil, fmt.Errorf("unexpected format. expected: %q, actual: %q", "\"\" \"\" \"\" \"\" \"\"", line) } return &models.Package{ Name: strings.TrimPrefix(fields[0], "\""), @@ -844,7 +843,7 @@ func (o *redhatBase) parseUpdatablePacksLine(line string) (*models.Package, erro Repository: strings.TrimSuffix(fields[4], "\""), }, nil default: - return nil, xerrors.Errorf("unexpected format. expected: %q, actual: %q", "\"\" \"\" \"\" \"\" \"\"", line) + return nil, fmt.Errorf("unexpected format. expected: %q, actual: %q", "\"\" \"\" \"\" \"\" \"\"", line) } } @@ -907,7 +906,7 @@ func (o *redhatBase) needsRestarting() error { cmd := "LANGUAGE=en_US.UTF-8 needs-restarting" r := o.exec(cmd, sudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to SSH: %w", r) + return fmt.Errorf("Failed to SSH: %v", r) } procs := o.parseNeedsRestarting(r.Stdout) for _, proc := range procs { @@ -983,14 +982,14 @@ func (o *redhatBase) procPathToFQPN(execCommand string) (string, error) { cmd := fmt.Sprintf("%s %s", o.rpmQf(), strings.Fields(execCommand)[0]) r := o.exec(util.PrependProxyEnv(cmd), noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to SSH: %s", r) + return "", fmt.Errorf("Failed to SSH: %s", r) } pack, ignroed, err := o.parseRpmQfLine(r.Stdout) if err != nil { - return "", xerrors.Errorf("Failed to parse rpm -qf line: %s, err: %+v", r.Stdout, err) + return "", fmt.Errorf("Failed to parse rpm -qf line: %s, err: %+v", r.Stdout, err) } if ignroed { - return "", xerrors.Errorf("Failed to return FQPN. line: %s, err: ignore line", r.Stdout) + return "", fmt.Errorf("Failed to return FQPN. line: %s, err: ignore line", r.Stdout) } return pack.FQPN(), nil } diff --git a/scanner/rhel.go b/scanner/rhel.go index dcadf88f37..7db1eb1f4a 100644 --- a/scanner/rhel.go +++ b/scanner/rhel.go @@ -1,10 +1,11 @@ package scanner import ( + "errors" + "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" - "golang.org/x/xerrors" ) // inherit OsTypeInterface @@ -44,7 +45,7 @@ func (o *rhel) checkDeps() error { if o.getServerInfo().Mode.IsDeep() { return o.execCheckDeps(o.depsDeep()) } - return xerrors.New("Unknown scan mode") + return errors.New("Unknown scan mode") } func (o *rhel) depsFast() []string { diff --git a/scanner/scanner.go b/scanner/scanner.go index 6ccd0d948c..5c72487cb1 100644 --- a/scanner/scanner.go +++ b/scanner/scanner.go @@ -1,6 +1,7 @@ package scanner import ( + "errors" "fmt" "maps" "math/rand" @@ -14,7 +15,6 @@ import ( "time" xos "github.com/aquasecurity/trivy/pkg/x/os" - "golang.org/x/xerrors" "github.com/future-architect/vuls/cache" "github.com/future-architect/vuls/config" @@ -31,9 +31,9 @@ const ( ) var ( - errOSFamilyHeader = xerrors.New("X-Vuls-OS-Family header is required") - errOSReleaseHeader = xerrors.New("X-Vuls-OS-Release header is required") - errServerNameHeader = xerrors.New("X-Vuls-Server-Name header is required") + errOSFamilyHeader = errors.New("X-Vuls-OS-Family header is required") + errOSReleaseHeader = errors.New("X-Vuls-OS-Release header is required") + errServerNameHeader = errors.New("X-Vuls-Server-Name header is required") ) var servers, errServers []osTypeInterface @@ -90,12 +90,12 @@ type Scanner struct { func (s Scanner) Scan() error { logging.Log.Info("Detecting Server/Container OS... ") if err := s.initServers(); err != nil { - return xerrors.Errorf("Failed to init servers. err: %w", err) + return fmt.Errorf("Failed to init servers. err: %w", err) } logging.Log.Info("Checking Scan Modes... ") if err := s.checkScanModes(); err != nil { - return xerrors.Errorf("Fix config.toml. err: %w", err) + return fmt.Errorf("Fix config.toml. err: %w", err) } logging.Log.Info("Detecting Platforms... ") @@ -107,7 +107,7 @@ func (s Scanner) Scan() error { } if err := s.execScan(); err != nil { - return xerrors.Errorf("Failed to scan. err: %w", err) + return fmt.Errorf("Failed to scan. err: %w", err) } return nil } @@ -116,12 +116,12 @@ func (s Scanner) Scan() error { func (s Scanner) Configtest() error { logging.Log.Info("Detecting Server/Container OS... ") if err := s.initServers(); err != nil { - return xerrors.Errorf("Failed to init servers. err: %w", err) + return fmt.Errorf("Failed to init servers. err: %w", err) } logging.Log.Info("Checking Scan Modes...") if err := s.checkScanModes(); err != nil { - return xerrors.Errorf("Fix config.toml. err: %w", err) + return fmt.Errorf("Fix config.toml. err: %w", err) } logging.Log.Info("Checking dependencies...") @@ -133,7 +133,7 @@ func (s Scanner) Configtest() error { logging.Log.Info("It can be scanned with fast scan mode even if warn or err messages are displayed due to lack of dependent packages or sudo settings in fast-root or deep scan mode") if len(servers) == 0 { - return xerrors.Errorf("No scannable servers") + return fmt.Errorf("No scannable servers") } logging.Log.Info("Scannable servers are below...") @@ -167,7 +167,7 @@ func ViaHTTP(header http.Header, body string, toLocalFile bool) (models.ScanResu case constant.Windows: osInfo, hotfixs, err := parseSystemInfo(toUTF8(body)) if err != nil { - return models.ScanResult{}, xerrors.Errorf("Failed to parse systeminfo.exe. err: %w", err) + return models.ScanResult{}, fmt.Errorf("Failed to parse systeminfo.exe. err: %w", err) } release := header.Get("X-Vuls-OS-Release") @@ -175,7 +175,7 @@ func ViaHTTP(header http.Header, body string, toLocalFile bool) (models.ScanResu logging.Log.Debugf("osInfo(systeminfo.exe): %+v", osInfo) release, err = detectOSName(osInfo) if err != nil { - return models.ScanResult{}, xerrors.Errorf("Failed to detect os name. err: %w", err) + return models.ScanResult{}, fmt.Errorf("Failed to detect os name. err: %w", err) } } @@ -186,7 +186,7 @@ func ViaHTTP(header http.Header, body string, toLocalFile bool) (models.ScanResu kbs, err := DetectKBsFromKernelVersion(release, kernelVersion) if err != nil { - return models.ScanResult{}, xerrors.Errorf("Failed to detect KBs from kernel version. err: %w", err) + return models.ScanResult{}, fmt.Errorf("Failed to detect KBs from kernel version. err: %w", err) } applied, unapplied := map[string]struct{}{}, map[string]struct{}{} @@ -289,7 +289,7 @@ func ParseInstalledPkgs(distro config.Distro, kernel models.Kernel, pkgList stri case constant.MacOSX, constant.MacOSXServer, constant.MacOS, constant.MacOSServer: osType = &macos{base: base} default: - return models.Packages{}, models.SrcPackages{}, xerrors.Errorf("Server mode for %s is not implemented yet", base.Distro.Family) + return models.Packages{}, models.SrcPackages{}, fmt.Errorf("Server mode for %s is not implemented yet", base.Distro.Family) } return osType.parseInstalledPackages(pkgList) @@ -299,7 +299,7 @@ func ParseInstalledPkgs(distro config.Distro, kernel models.Kernel, pkgList stri func (s Scanner) initServers() error { hosts, errHosts := s.detectServerOSes() if (len(hosts) + len(errHosts)) == 0 { - return xerrors.New("No host defined. Check the configuration") + return errors.New("No host defined. Check the configuration") } for _, srv := range hosts { @@ -321,7 +321,7 @@ func (s Scanner) initServers() error { errServers = append(errHosts, errContainers...) if (len(servers) + len(errServers)) == 0 { - return xerrors.New("No server defined. Check the configuration") + return errors.New("No server defined. Check the configuration") } return nil } @@ -372,7 +372,7 @@ func (s Scanner) detectServerOSes() (servers, errServers []osTypeInterface) { if !found { u := &unknown{} u.setServerInfo(sInfo) - u.setErrs([]error{xerrors.New("Timed out")}) + u.setErrs([]error{errors.New("Timed out")}) errServers = append(errServers, u) logging.Log.Errorf("(%d/%d) Timed out: %s", i+1, len(s.Targets), servername) } @@ -398,7 +398,7 @@ func validateSSHConfig(c *config.ServerInfo) error { sshBinaryPath, err := lookpath(c.Distro.Family, "ssh") if err != nil { - return xerrors.Errorf("Failed to lookup ssh binary path. err: %w", err) + return fmt.Errorf("Failed to lookup ssh binary path. err: %w", err) } sshConfigCmd := buildSSHConfigCmd(sshBinaryPath, c) @@ -409,7 +409,7 @@ func validateSSHConfig(c *config.ServerInfo) error { logging.Log.Warn("SSH configuration validation is skipped. To enable validation, G option introduced in OpenSSH 6.8 must be enabled.") return nil } - return xerrors.Errorf("Failed to print SSH configuration. err: %w", configResult.Error) + return fmt.Errorf("Failed to print SSH configuration. err: %w", configResult.Error) } sshConfig := parseSSHConfiguration(configResult.Stdout) c.User = sshConfig.user @@ -417,7 +417,7 @@ func validateSSHConfig(c *config.ServerInfo) error { c.Port = sshConfig.port logging.Log.Debugf("Setting SSH Port:%s for Server:%s ...", sshConfig.port, c.GetServerName()) if c.User == "" || c.Port == "" { - return xerrors.New("Failed to find User or Port setting. Please check the User or Port settings for SSH") + return errors.New("Failed to find User or Port setting. Please check the User or Port settings for SSH") } if sshConfig.strictHostKeyChecking == "false" { @@ -436,12 +436,12 @@ func validateSSHConfig(c *config.ServerInfo) error { } } if len(knownHostsPaths) == 0 { - return xerrors.New("Failed to find any known_hosts to use. Please check the UserKnownHostsFile and GlobalKnownHostsFile settings for SSH") + return errors.New("Failed to find any known_hosts to use. Please check the UserKnownHostsFile and GlobalKnownHostsFile settings for SSH") } sshKeyscanBinaryPath, err := lookpath(c.Distro.Family, "ssh-keyscan") if err != nil { - return xerrors.Errorf("Failed to lookup ssh-keyscan binary path. err: %w", err) + return fmt.Errorf("Failed to lookup ssh-keyscan binary path. err: %w", err) } sshScanCmd := strings.Join([]string{sshKeyscanBinaryPath, "-p", c.Port, sshConfig.hostname}, " ") r := localExec(*c, sshScanCmd, noSudo) @@ -453,7 +453,7 @@ func validateSSHConfig(c *config.ServerInfo) error { sshKeygenBinaryPath, err := lookpath(c.Distro.Family, "ssh-keygen") if err != nil { - return xerrors.Errorf("Failed to lookup ssh-keygen binary path. err: %w", err) + return fmt.Errorf("Failed to lookup ssh-keygen binary path. err: %w", err) } for _, knownHosts := range knownHostsPaths { var hostname string @@ -477,13 +477,13 @@ func validateSSHConfig(c *config.ServerInfo) error { if serverKey, ok := serverKeys[keyType]; ok && serverKey == clientKey { return nil } - return xerrors.Errorf("Failed to find the server key that matches the key registered in the client. The server key may have been changed. Please exec `$ %s` and `$ %s` or `$ %s`", + return fmt.Errorf("Failed to find the server key that matches the key registered in the client. The server key may have been changed. Please exec `$ %s` and `$ %s` or `$ %s`", fmt.Sprintf("%s -R %s -f %s", sshKeygenBinaryPath, hostname, knownHosts), strings.Join(buildSSHBaseCmd(sshBinaryPath, c, nil), " "), buildSSHKeyScanCmd(sshKeyscanBinaryPath, c.Port, knownHostsPaths[0], sshConfig)) } } - return xerrors.Errorf("Failed to find the host in known_hosts. Please exec `$ %s` or `$ %s`", + return fmt.Errorf("Failed to find the host in known_hosts. Please exec `$ %s` or `$ %s`", strings.Join(buildSSHBaseCmd(sshBinaryPath, c, nil), " "), buildSSHKeyScanCmd(sshKeyscanBinaryPath, c.Port, knownHostsPaths[0], sshConfig)) } @@ -628,7 +628,7 @@ func parseSSHKeygen(stdout string) (string, string, error) { } } } - return "", "", xerrors.New("Failed to parse ssh-keygen result. err: public key not found") + return "", "", errors.New("Failed to parse ssh-keygen result. err: public key not found") } func (s Scanner) detectContainerOSes(hosts []osTypeInterface) (actives, inactives []osTypeInterface) { @@ -677,7 +677,7 @@ func (s Scanner) detectContainerOSesOnServer(containerHost osTypeInterface) (ose running, err := containerHost.runningContainers() if err != nil { - containerHost.setErrs([]error{xerrors.Errorf( + containerHost.setErrs([]error{fmt.Errorf( "Failed to get running containers on %s. err: %w", containerHost.getServerInfo().ServerName, err)}) return append(oses, containerHost) @@ -709,7 +709,7 @@ func (s Scanner) detectContainerOSesOnServer(containerHost osTypeInterface) (ose exitedContainers, err := containerHost.exitedContainers() if err != nil { - containerHost.setErrs([]error{xerrors.Errorf( + containerHost.setErrs([]error{fmt.Errorf( "Failed to get exited containers on %s. err: %w", containerHost.getServerInfo().ServerName, err)}) return append(oses, containerHost) @@ -744,7 +744,7 @@ func (s Scanner) detectContainerOSesOnServer(containerHost osTypeInterface) (ose } } if 0 < len(exited) || 0 < len(unknown) { - containerHost.setErrs([]error{xerrors.Errorf( + containerHost.setErrs([]error{fmt.Errorf( "Some containers on %s are exited or unknown. exited: %s, unknown: %s", containerHost.getServerInfo().ServerName, exited, unknown)}) return append(oses, containerHost) @@ -760,7 +760,7 @@ func (s Scanner) detectOS(c config.ServerInfo) osTypeInterface { if !isLocalExec(c.Port, c.Host) { if err := testFirstSSHConnection(c); err != nil { osType := &unknown{base{ServerInfo: c}} - osType.setErrs([]error{xerrors.Errorf("Failed to test first SSH Connection. err: %w", err)}) + osType.setErrs([]error{fmt.Errorf("Failed to test first SSH Connection. err: %w", err)}) return osType } } @@ -801,7 +801,7 @@ func (s Scanner) detectOS(c config.ServerInfo) osTypeInterface { } osType := &unknown{base{ServerInfo: c}} - osType.setErrs([]error{xerrors.New("Unknown OS Type")}) + osType.setErrs([]error{errors.New("Unknown OS Type")}) return osType } @@ -814,7 +814,7 @@ func testFirstSSHConnection(c config.ServerInfo) error { select { case r := <-rChan: if r.ExitStatus == 255 { - return xerrors.Errorf("Unable to connect via SSH. Scan with -vvv option to print SSH debugging messages and check SSH settings.\n%s", r) + return fmt.Errorf("Unable to connect via SSH. Scan with -vvv option to print SSH debugging messages and check SSH settings.\n%s", r) } return nil case <-time.After(time.Duration(3) * time.Second): @@ -828,7 +828,7 @@ func testFirstSSHConnection(c config.ServerInfo) error { func (s Scanner) checkScanModes() error { for _, s := range servers { if err := s.checkScanMode(); err != nil { - return xerrors.Errorf("servers.%s.scanMode err: %w", + return fmt.Errorf("servers.%s.scanMode err: %w", s.getServerInfo().GetServerName(), err) } } @@ -898,7 +898,7 @@ func (s Scanner) detectIPS() { // execScan scan func (s Scanner) execScan() error { if (len(servers) + len(errServers)) == 0 { - return xerrors.New("No server defined. Check the configuration") + return errors.New("No server defined. Check the configuration") } if err := s.setupChangelogCache(); err != nil { @@ -972,12 +972,12 @@ func (s Scanner) getScanResults(scannedAt time.Time) (results models.ScanResults } if o.getServerInfo().Module.IsScanWordPress() { if err = o.scanWordPress(); err != nil { - return xerrors.Errorf("Failed to scan WordPress: %w", err) + return fmt.Errorf("Failed to scan WordPress: %w", err) } } if o.getServerInfo().Module.IsScanLockFile() { if err = o.scanLibraries(); err != nil { - return xerrors.Errorf("Failed to scan Library: %w", err) + return fmt.Errorf("Failed to scan Library: %w", err) } } return nil diff --git a/scanner/suse.go b/scanner/suse.go index 6fc67f3f0f..616b1d61e4 100644 --- a/scanner/suse.go +++ b/scanner/suse.go @@ -2,6 +2,7 @@ package scanner import ( "bufio" + "errors" "fmt" "regexp" "strings" @@ -11,7 +12,6 @@ import ( "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" "github.com/future-architect/vuls/util" - "golang.org/x/xerrors" ) // inherit OsTypeInterface @@ -44,7 +44,7 @@ func detectSUSE(c config.ServerInfo) (bool, osTypeInterface) { s := newSUSE(c) name, ver := s.parseOSRelease(r.Stdout) if name == "" || ver == "" { - s.setErrs([]error{xerrors.Errorf("Failed to parse /etc/os-release: %s", r.Stdout)}) + s.setErrs([]error{fmt.Errorf("Failed to parse /etc/os-release: %s", r.Stdout)}) return true, s } s.setDistro(name, ver) @@ -73,7 +73,7 @@ func detectSUSE(c config.ServerInfo) (bool, osTypeInterface) { return true, s } } - s.setErrs([]error{xerrors.Errorf("Failed to parse /etc/SuSE-release: %s", r.Stdout)}) + s.setErrs([]error{fmt.Errorf("Failed to parse /etc/SuSE-release: %s", r.Stdout)}) return true, s } } @@ -119,7 +119,7 @@ func (o *suse) checkDeps() error { if o.getServerInfo().Mode.IsDeep() { return o.execCheckDeps(o.depsDeep()) } - return xerrors.New("Unknown scan mode") + return errors.New("Unknown scan mode") } func (o *suse) depsFast() []string { @@ -178,7 +178,7 @@ func (o *suse) scanPackages() (err error) { o.Kernel.RebootRequired, err = o.rebootRequired() if err != nil { - err = xerrors.Errorf("Failed to detect the kernel reboot required: %w", err) + err = fmt.Errorf("Failed to detect the kernel reboot required: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -190,7 +190,7 @@ func (o *suse) scanPackages() (err error) { updatable, err := o.scanUpdatablePackages() if err != nil { - err = xerrors.Errorf("Failed to scan updatable packages: %w", err) + err = fmt.Errorf("Failed to scan updatable packages: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -218,7 +218,7 @@ func (o *suse) scanUpdatablePackages() (models.Packages, error) { } r := o.exec(cmd, noSudo) if !r.isSuccess() { - return nil, xerrors.Errorf("Failed to scan updatable packages: %v", r) + return nil, fmt.Errorf("Failed to scan updatable packages: %v", r) } return o.parseZypperLULines(r.Stdout) } @@ -261,11 +261,11 @@ func (o *suse) parseZypperLULines(stdout string) (models.Packages, error) { func (o *suse) parseZypperLUOneLine(line string) (*models.Package, error) { ss := strings.Split(line, "|") if len(ss) != 6 { - return nil, xerrors.Errorf("zypper -q lu Unknown format: %s", line) + return nil, fmt.Errorf("zypper -q lu Unknown format: %s", line) } available := strings.Split(strings.TrimSpace(ss[4]), "-") if len(available) != 2 { - return nil, xerrors.Errorf("unexpected Available Version. expected: %q, actual: %q", "-", strings.TrimSpace(ss[4])) + return nil, fmt.Errorf("unexpected Available Version. expected: %q, actual: %q", "-", strings.TrimSpace(ss[4])) } return &models.Package{ Name: strings.TrimSpace(ss[2]), @@ -284,7 +284,7 @@ func (o *suse) hasZypperColorOption() bool { func (o *suse) postScan() error { if o.isExecYumPS() { if err := o.pkgPs(o.getOwnerPkgs); err != nil { - err = xerrors.Errorf("Failed to execute zypper-ps: %w", err) + err = fmt.Errorf("Failed to execute zypper-ps: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -293,7 +293,7 @@ func (o *suse) postScan() error { if o.isExecNeedsRestarting() { if err := o.needsRestarting(); err != nil { - err = xerrors.Errorf("Failed to execute need-restarting: %w", err) + err = fmt.Errorf("Failed to execute need-restarting: %w", err) o.log.Warnf("err: %+v", err) o.warns = append(o.warns, err) // Only warning this error @@ -312,7 +312,7 @@ func (o *suse) needsRestarting() error { cmd := "LANGUAGE=en_US.UTF-8 zypper ps -s" r := o.exec(cmd, sudo) if !r.isSuccess() { - return xerrors.Errorf("Failed to SSH: %w", r) + return fmt.Errorf("Failed to SSH: %v", r) } procs := o.parseNeedsRestarting(r.Stdout) for _, proc := range procs { diff --git a/scanner/trivy/jar/jar.go b/scanner/trivy/jar/jar.go index a191840437..cf117bc660 100644 --- a/scanner/trivy/jar/jar.go +++ b/scanner/trivy/jar/jar.go @@ -2,13 +2,12 @@ package jar import ( "context" + "fmt" "io/fs" "os" "path/filepath" "strings" - "golang.org/x/xerrors" - "github.com/aquasecurity/trivy/pkg/fanal/analyzer" "github.com/aquasecurity/trivy/pkg/fanal/types" "github.com/aquasecurity/trivy/pkg/parallel" @@ -45,7 +44,7 @@ func (a *javaLibraryAnalyzer) PostAnalyze(ctx context.Context, input analyzer.Po p := newParser(withSize(info.Size()), withFilePath(path)) parsedLibs, err := p.parse(r) if err != nil { - return nil, xerrors.Errorf("Failed to parse %s. err: %w", path, err) + return nil, fmt.Errorf("Failed to parse %s. err: %w", path, err) } return toApplication(path, parsedLibs), nil @@ -61,7 +60,7 @@ func (a *javaLibraryAnalyzer) PostAnalyze(ctx context.Context, input analyzer.Po } if err := parallel.WalkDir(ctx, input.FS, ".", a.parallel, onFile, onResult); err != nil { - return nil, xerrors.Errorf("Failed to walk dir. err: %w", err) + return nil, fmt.Errorf("Failed to walk dir. err: %w", err) } return &analyzer.AnalysisResult{ diff --git a/scanner/trivy/jar/parse.go b/scanner/trivy/jar/parse.go index dee8f5c87c..628e62d299 100644 --- a/scanner/trivy/jar/parse.go +++ b/scanner/trivy/jar/parse.go @@ -3,6 +3,7 @@ package jar import ( "archive/zip" "bufio" + "errors" "fmt" "io" "os" @@ -16,7 +17,6 @@ import ( xio "github.com/aquasecurity/trivy/pkg/x/io" xos "github.com/aquasecurity/trivy/pkg/x/os" "github.com/samber/lo" - "golang.org/x/xerrors" ) var ( @@ -90,7 +90,7 @@ func newParser(opts ...option) *parser { func (p *parser) parse(r xio.ReadSeekerAt) ([]jarLibrary, error) { libs, err := p.parseArtifact(p.rootFilePath, p.size, r) if err != nil { - return nil, xerrors.Errorf("Failed to parse %s. err: %w", p.rootFilePath, err) + return nil, fmt.Errorf("Failed to parse %s. err: %w", p.rootFilePath, err) } return removeLibraryDuplicates(libs), nil } @@ -103,12 +103,12 @@ func (p *parser) parseArtifact(filePath string, size int64, r xio.ReadSeekerAt) sha1, err := digest.CalcSHA1(r) if err != nil { - return nil, xerrors.Errorf("Failed to calculate SHA1. err: %w", err) + return nil, fmt.Errorf("Failed to calculate SHA1. err: %w", err) } zr, err := zip.NewReader(r, size) if err != nil { - return nil, xerrors.Errorf("Failed to open zip. err: %w", err) + return nil, fmt.Errorf("Failed to open zip. err: %w", err) } // Try to extract artifactId and version from the file name @@ -124,7 +124,7 @@ func (p *parser) parseArtifact(filePath string, size int64, r xio.ReadSeekerAt) case filepath.Base(fileInJar.Name) == "pom.properties": props, err := parsePomProperties(fileInJar, filePath) if err != nil { - return nil, xerrors.Errorf("Failed to parse %s. err: %w", fileInJar.Name, err) + return nil, fmt.Errorf("Failed to parse %s. err: %w", fileInJar.Name, err) } libs = append(libs, props.library()) @@ -135,7 +135,7 @@ func (p *parser) parseArtifact(filePath string, size int64, r xio.ReadSeekerAt) case filepath.Base(fileInJar.Name) == "MANIFEST.MF": m, err = parseManifest(fileInJar) if err != nil { - return nil, xerrors.Errorf("Failed to parse MANIFEST.MF. err: %w", err) + return nil, fmt.Errorf("Failed to parse MANIFEST.MF. err: %w", err) } case isArtifact(fileInJar.Name): innerLibs, err := p.parseInnerJar(fileInJar, filePath) //TODO process inner deps @@ -166,23 +166,23 @@ func (p *parser) parseArtifact(filePath string, size int64, r xio.ReadSeekerAt) func (p *parser) parseInnerJar(zf *zip.File, rootPath string) ([]jarLibrary, error) { fr, err := zf.Open() if err != nil { - return nil, xerrors.Errorf("Failed to open file %s. err: %w", zf.Name, err) + return nil, fmt.Errorf("Failed to open file %s. err: %w", zf.Name, err) } defer fr.Close() f, err := xos.CreateTemp("", "jar-inner-") if err != nil { - return nil, xerrors.Errorf("Failed to create tmp file for %s. err: %w", zf.Name, err) + return nil, fmt.Errorf("Failed to create tmp file for %s. err: %w", zf.Name, err) } defer os.Remove(f.Name()) defer f.Close() // Copy the file content to the temp file and rewind it at the beginning if _, err = io.Copy(f, fr); err != nil { - return nil, xerrors.Errorf("Failed to copy file %s. err: %w", zf.Name, err) + return nil, fmt.Errorf("Failed to copy file %s. err: %w", zf.Name, err) } if _, err = f.Seek(0, io.SeekStart); err != nil { - return nil, xerrors.Errorf("Failed to seek file %s. err: %w", zf.Name, err) + return nil, fmt.Errorf("Failed to seek file %s. err: %w", zf.Name, err) } // build full path to inner jar @@ -191,7 +191,7 @@ func (p *parser) parseInnerJar(zf *zip.File, rootPath string) ([]jarLibrary, err // Parse jar/war/ear recursively innerLibs, err := p.parseArtifact(fullPath, int64(zf.UncompressedSize64), f) if err != nil { - return nil, xerrors.Errorf("Failed to parse file %s. err: %w", zf.Name, err) + return nil, fmt.Errorf("Failed to parse file %s. err: %w", zf.Name, err) } return innerLibs, nil @@ -226,7 +226,7 @@ func parseFileName(filePath string, sha1 digest.Digest) properties { func parsePomProperties(f *zip.File, filePath string) (properties, error) { file, err := f.Open() if err != nil { - return properties{}, xerrors.Errorf("Failed to open pom.properties. err: %w", err) + return properties{}, fmt.Errorf("Failed to open pom.properties. err: %w", err) } defer file.Close() @@ -247,7 +247,7 @@ func parsePomProperties(f *zip.File, filePath string) (properties, error) { } if err = scanner.Err(); err != nil { - return properties{}, xerrors.Errorf("Failed to scan %s. err: %w", f.Name, err) + return properties{}, fmt.Errorf("Failed to scan %s. err: %w", f.Name, err) } return p, nil } @@ -268,7 +268,7 @@ type manifest struct { func parseManifest(f *zip.File) (manifest, error) { file, err := f.Open() if err != nil { - return manifest{}, xerrors.Errorf("Failed to open MANIFEST.MF. err: %w", err) + return manifest{}, fmt.Errorf("Failed to open MANIFEST.MF. err: %w", err) } defer file.Close() @@ -310,7 +310,7 @@ func parseManifest(f *zip.File) (manifest, error) { } if err = scanner.Err(); err != nil { - return manifest{}, xerrors.Errorf("Failed to scan %s. err: %w", f.Name, err) + return manifest{}, fmt.Errorf("Failed to scan %s. err: %w", f.Name, err) } return m, nil } @@ -358,7 +358,7 @@ func (m manifest) determineGroupID() (string, error) { case m.specificationVendor != "": groupID = m.specificationVendor default: - return "", xerrors.New("No groupID found") + return "", errors.New("No groupID found") } return strings.TrimSpace(groupID), nil } @@ -373,7 +373,7 @@ func (m manifest) determineArtifactID() (string, error) { case m.bundleName != "": artifactID = m.bundleName default: - return "", xerrors.New("No artifactID found") + return "", errors.New("No artifactID found") } return strings.TrimSpace(artifactID), nil } @@ -388,7 +388,7 @@ func (m manifest) determineVersion() (string, error) { case m.bundleVersion != "": version = m.bundleVersion default: - return "", xerrors.New("No version found") + return "", errors.New("No version found") } return strings.TrimSpace(version), nil } diff --git a/scanner/utils.go b/scanner/utils.go index dd92122388..ecd9b8b59c 100644 --- a/scanner/utils.go +++ b/scanner/utils.go @@ -8,8 +8,6 @@ import ( "strings" "time" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/logging" "github.com/future-architect/vuls/models" @@ -101,7 +99,7 @@ func EnsureResultDir(resultsDir string, scannedAt time.Time) (currentDir string, } jsonDir := filepath.Join(resultsDir, jsonDirName) if err := os.MkdirAll(jsonDir, 0700); err != nil { - return "", xerrors.Errorf("Failed to create dir: %w", err) + return "", fmt.Errorf("Failed to create dir: %w", err) } return jsonDir, nil } @@ -113,7 +111,7 @@ func writeScanResults(jsonDir string, results models.ScanResults) error { }} for _, w := range ws { if err := w.Write(results...); err != nil { - return xerrors.Errorf("Failed to write summary: %s", err) + return fmt.Errorf("Failed to write summary: %s", err) } } diff --git a/scanner/windows.go b/scanner/windows.go index de4bee7309..dd262cbc4f 100644 --- a/scanner/windows.go +++ b/scanner/windows.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "encoding/base64" + "errors" "fmt" "io" "maps" @@ -14,8 +15,6 @@ import ( "strconv" "strings" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/constant" "github.com/future-architect/vuls/logging" @@ -79,14 +78,14 @@ func detectWindows(c config.ServerInfo) (bool, osTypeInterface) { if r := w.exec(w.translateCmd(`Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion" | Format-List -Property ProductName, CurrentVersion, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR, CSDVersion, EditionID, InstallationType; Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" | Format-List -Property PROCESSOR_ARCHITECTURE`), noSudo); r.isSuccess() { osInfo, err := parseRegistry(r.Stdout) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to parse Registry. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to parse Registry. err: %w", err)}) return true, w } logging.Log.Debugf("osInfo(Registry): %+v", osInfo) release, err := detectOSName(osInfo) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to detect os name. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to detect os name. err: %w", err)}) return true, w } w.setDistro(constant.Windows, release) @@ -97,14 +96,14 @@ func detectWindows(c config.ServerInfo) (bool, osTypeInterface) { if r := w.exec(w.translateCmd(`$ProgressPreference = "SilentlyContinue"; Get-ComputerInfo -Property WindowsProductName, OsVersion, WindowsEditionId, OsCSDVersion, CsSystemType, WindowsInstallationType`), noSudo); r.isSuccess() { osInfo, err := parseGetComputerInfo(r.Stdout) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to parse Get-ComputerInfo. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to parse Get-ComputerInfo. err: %w", err)}) return true, w } logging.Log.Debugf("osInfo(Get-ComputerInfo): %+v", osInfo) release, err := detectOSName(osInfo) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to detect os name. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to detect os name. err: %w", err)}) return true, w } w.setDistro(constant.Windows, release) @@ -115,14 +114,14 @@ func detectWindows(c config.ServerInfo) (bool, osTypeInterface) { if r := w.exec(w.translateCmd("Get-WmiObject Win32_OperatingSystem | Format-List -Property Caption, Version, OperatingSystemSKU, CSDVersion; Get-WmiObject Win32_ComputerSystem | Format-List -Property SystemType, DomainRole"), noSudo); r.isSuccess() { osInfo, err := parseWmiObject(r.Stdout) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to parse Get-WmiObject. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to parse Get-WmiObject. err: %w", err)}) return true, w } logging.Log.Debugf("osInfo(Get-WmiObject): %+v", osInfo) release, err := detectOSName(osInfo) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to detect os name. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to detect os name. err: %w", err)}) return true, w } w.setDistro(constant.Windows, release) @@ -133,14 +132,14 @@ func detectWindows(c config.ServerInfo) (bool, osTypeInterface) { if r := w.exec("systeminfo.exe", noSudo); r.isSuccess() { osInfo, _, err := parseSystemInfo(r.Stdout) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to parse systeminfo.exe. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to parse systeminfo.exe. err: %w", err)}) return true, w } logging.Log.Debugf("osInfo(systeminfo.exe): %+v", osInfo) release, err := detectOSName(osInfo) if err != nil { - w.setErrs([]error{xerrors.Errorf("Failed to detect os name. err: %w", err)}) + w.setErrs([]error{fmt.Errorf("Failed to detect os name. err: %w", err)}) return true, w } w.setDistro(constant.Windows, release) @@ -208,12 +207,12 @@ func parseSystemInfo(stdout string) (osInfo, []string, error) { case strings.Contains(line, "Domain Controller"): o.installationType = "Domain Controller" default: - return osInfo{}, nil, xerrors.Errorf("Failed to detect installation type. line: %s", line) + return osInfo{}, nil, fmt.Errorf("Failed to detect installation type. line: %s", line) } case strings.HasPrefix(line, "Hotfix(s):"): nKB, err := strconv.Atoi(strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "Hotfix(s):"), "Hotfix(s) Installed."))) if err != nil { - return osInfo{}, nil, xerrors.Errorf("Failed to detect number of installed hotfix from %s", line) + return osInfo{}, nil, fmt.Errorf("Failed to detect number of installed hotfix from %s", line) } for range nKB { scanner.Scan() @@ -231,7 +230,7 @@ func parseSystemInfo(stdout string) (osInfo, []string, error) { } } if err := scanner.Err(); err != nil { - return osInfo{}, nil, xerrors.Errorf("Failed to scan systeminfo stdout. err: %w", err) + return osInfo{}, nil, fmt.Errorf("Failed to scan systeminfo stdout. err: %w", err) } return o, kbs, nil } @@ -247,13 +246,13 @@ func parseGetComputerInfo(stdout string) (osInfo, error) { case strings.HasPrefix(line, "WindowsProductName"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect ProductName. expected: "WindowsProductName : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect ProductName. expected: "WindowsProductName : ", line: "%s"`, line) } o.productName = strings.TrimSpace(rhs) case strings.HasPrefix(line, "OsVersion"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect OsVersion. expected: "OsVersion : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect OsVersion. expected: "OsVersion : ", line: "%s"`, line) } ss := strings.Split(strings.TrimSpace(rhs), ".") o.version = strings.Join(ss[0:len(ss)-1], ".") @@ -261,32 +260,32 @@ func parseGetComputerInfo(stdout string) (osInfo, error) { case strings.HasPrefix(line, "WindowsEditionId"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect WindowsEditionId. expected: "WindowsEditionId : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect WindowsEditionId. expected: "WindowsEditionId : ", line: "%s"`, line) } o.edition = strings.TrimSpace(rhs) case strings.HasPrefix(line, "OsCSDVersion"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect OsCSDVersion. expected: "OsCSDVersion : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect OsCSDVersion. expected: "OsCSDVersion : ", line: "%s"`, line) } o.servicePack = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CsSystemType"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CsSystemType. expected: "CsSystemType : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CsSystemType. expected: "CsSystemType : ", line: "%s"`, line) } o.arch = strings.TrimSpace(strings.TrimSuffix(rhs, "PC")) case strings.HasPrefix(line, "WindowsInstallationType"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect WindowsInstallationType. expected: "WindowsInstallationType : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect WindowsInstallationType. expected: "WindowsInstallationType : ", line: "%s"`, line) } o.installationType = strings.TrimSpace(rhs) default: } } if err := scanner.Err(); err != nil { - return osInfo{}, xerrors.Errorf("Failed to scan Get-ComputerInfo stdout. err: %w", err) + return osInfo{}, fmt.Errorf("Failed to scan Get-ComputerInfo stdout. err: %w", err) } return o, nil } @@ -302,13 +301,13 @@ func parseWmiObject(stdout string) (osInfo, error) { case strings.HasPrefix(line, "Caption"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect Caption. expected: "Caption : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect Caption. expected: "Caption : ", line: "%s"`, line) } o.productName = strings.TrimSpace(rhs) case strings.HasPrefix(line, "Version"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect Version. expected: "Version : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect Version. expected: "Version : ", line: "%s"`, line) } ss := strings.Split(strings.TrimSpace(rhs), ".") o.version = strings.Join(ss[0:len(ss)-1], ".") @@ -316,7 +315,7 @@ func parseWmiObject(stdout string) (osInfo, error) { case strings.HasPrefix(line, "OperatingSystemSKU"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect OperatingSystemSKU. expected: "OperatingSystemSKU : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect OperatingSystemSKU. expected: "OperatingSystemSKU : ", line: "%s"`, line) } switch n := strings.TrimSpace(rhs); n { case "0": @@ -473,13 +472,13 @@ func parseWmiObject(stdout string) (osInfo, error) { case strings.HasPrefix(line, "CSDVersion"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CSDVersion. expected: "CSDVersion : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CSDVersion. expected: "CSDVersion : ", line: "%s"`, line) } o.servicePack = strings.TrimSpace(rhs) case strings.HasPrefix(line, "SystemType"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect SystemType. expected: "SystemType : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect SystemType. expected: "SystemType : ", line: "%s"`, line) } o.arch = strings.TrimSpace(strings.TrimSuffix(rhs, "PC")) case strings.HasPrefix(line, "DomainRole"): @@ -489,7 +488,7 @@ func parseWmiObject(stdout string) (osInfo, error) { _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect DomainRole. expected: "DomainRole : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect DomainRole. expected: "DomainRole : ", line: "%s"`, line) } switch domainRole := strings.TrimSpace(rhs); domainRole { // https://learn.microsoft.com/en-us/windows/win32/api/dsrole/ne-dsrole-dsrole_machine_role case "0", "1": @@ -499,13 +498,13 @@ func parseWmiObject(stdout string) (osInfo, error) { case "4", "5": o.installationType = "Domain Controller" default: - return osInfo{}, xerrors.Errorf("Failed to detect Installation Type from DomainRole. err: %s is invalid DomainRole", domainRole) + return osInfo{}, fmt.Errorf("Failed to detect Installation Type from DomainRole. err: %s is invalid DomainRole", domainRole) } default: } } if err := scanner.Err(); err != nil { - return osInfo{}, xerrors.Errorf("Failed to scan Get-WmiObject stdout. err: %w", err) + return osInfo{}, fmt.Errorf("Failed to scan Get-WmiObject stdout. err: %w", err) } return o, nil } @@ -526,68 +525,68 @@ func parseRegistry(stdout string) (osInfo, error) { case strings.HasPrefix(line, "ProductName"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect ProductName. expected: "ProductName : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect ProductName. expected: "ProductName : ", line: "%s"`, line) } o.productName = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CurrentVersion"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CurrentVersion. expected: "CurrentVersion : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CurrentVersion. expected: "CurrentVersion : ", line: "%s"`, line) } o.version = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CurrentMajorVersionNumber"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CurrentMajorVersionNumber. expected: "CurrentMajorVersionNumber : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CurrentMajorVersionNumber. expected: "CurrentMajorVersionNumber : ", line: "%s"`, line) } major = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CurrentMinorVersionNumber"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CurrentMinorVersionNumber. expected: "CurrentMinorVersionNumber : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CurrentMinorVersionNumber. expected: "CurrentMinorVersionNumber : ", line: "%s"`, line) } minor = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CurrentBuildNumber"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CurrentBuildNumber. expected: "CurrentBuildNumber : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CurrentBuildNumber. expected: "CurrentBuildNumber : ", line: "%s"`, line) } o.build = strings.TrimSpace(rhs) case strings.HasPrefix(line, "UBR"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect UBR. expected: "UBR : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect UBR. expected: "UBR : ", line: "%s"`, line) } o.revision = strings.TrimSpace(rhs) case strings.HasPrefix(line, "EditionID"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect EditionID. expected: "EditionID : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect EditionID. expected: "EditionID : ", line: "%s"`, line) } o.edition = strings.TrimSpace(rhs) case strings.HasPrefix(line, "CSDVersion"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect CSDVersion. expected: "CSDVersion : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect CSDVersion. expected: "CSDVersion : ", line: "%s"`, line) } o.servicePack = strings.TrimSpace(rhs) case strings.HasPrefix(line, "InstallationType"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect InstallationType. expected: "InstallationType : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect InstallationType. expected: "InstallationType : ", line: "%s"`, line) } o.installationType = strings.TrimSpace(rhs) case strings.HasPrefix(line, "PROCESSOR_ARCHITECTURE"): _, rhs, found := strings.Cut(line, ":") if !found { - return osInfo{}, xerrors.Errorf(`Failed to detect PROCESSOR_ARCHITECTURE. expected: "PROCESSOR_ARCHITECTURE : ", line: "%s"`, line) + return osInfo{}, fmt.Errorf(`Failed to detect PROCESSOR_ARCHITECTURE. expected: "PROCESSOR_ARCHITECTURE : ", line: "%s"`, line) } o.arch = strings.TrimSpace(rhs) default: } } if err := scanner.Err(); err != nil { - return osInfo{}, xerrors.Errorf("Failed to scan registry stdout. err: %w", err) + return osInfo{}, fmt.Errorf("Failed to scan registry stdout. err: %w", err) } if major != "" && minor != "" { @@ -599,7 +598,7 @@ func parseRegistry(stdout string) (osInfo, error) { func detectOSName(osInfo osInfo) (string, error) { osName, err := detectOSNameFromOSInfo(osInfo) if err != nil { - return "", xerrors.Errorf("Failed to detect OS Name from OSInfo: %+v, err: %w", osInfo, err) + return "", fmt.Errorf("Failed to detect OS Name from OSInfo: %+v, err: %w", osInfo, err) } return osName, nil } @@ -635,7 +634,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { } arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } switch arch { @@ -663,7 +662,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { } arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } switch arch { case "x64-based": @@ -680,7 +679,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { } arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } switch arch { case "x64-based": @@ -703,7 +702,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { var n string arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } switch arch { case "x64-based": @@ -718,7 +717,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Server", "Domain Controller": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } if osInfo.servicePack != "" { return fmt.Sprintf("Windows Server 2008 for %s Systems %s", arch, osInfo.servicePack), nil @@ -727,7 +726,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Server Core": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } if osInfo.servicePack != "" { return fmt.Sprintf("Windows Server 2008 for %s Systems %s (Server Core installation)", arch, osInfo.servicePack), nil @@ -739,7 +738,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Client": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } if osInfo.servicePack != "" { return fmt.Sprintf("Windows 7 for %s Systems %s", arch, osInfo.servicePack), nil @@ -748,7 +747,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Server", "Domain Controller": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } if osInfo.servicePack != "" { return fmt.Sprintf("Windows Server 2008 R2 for %s Systems %s", arch, osInfo.servicePack), nil @@ -757,7 +756,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Server Core": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } if osInfo.servicePack != "" { return fmt.Sprintf("Windows Server 2008 R2 for %s Systems %s (Server Core installation)", arch, osInfo.servicePack), nil @@ -769,7 +768,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Client": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } return fmt.Sprintf("Windows 8 for %s Systems", arch), nil case "Server", "Domain Controller": @@ -782,7 +781,7 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Client": arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } return fmt.Sprintf("Windows 8.1 for %s Systems", arch), nil case "Server", "Domain Controller": @@ -796,22 +795,22 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { if strings.Contains(osInfo.productName, "Windows 11") { arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } name, err := formatNamebyBuild("11", osInfo.build) if err != nil { - return "", xerrors.Errorf("Failed to format name by build: %w", err) + return "", fmt.Errorf("Failed to format name by build: %w", err) } return fmt.Sprintf("%s for %s Systems", name, arch), nil } arch, err := formatArch(osInfo.arch) if err != nil { - return "", xerrors.Errorf("Failed to format architecture: %w", err) + return "", fmt.Errorf("Failed to format architecture: %w", err) } name, err := formatNamebyBuild("10", osInfo.build) if err != nil { - return "", xerrors.Errorf("Failed to format name by build: %w", err) + return "", fmt.Errorf("Failed to format name by build: %w", err) } return fmt.Sprintf("%s for %s Systems", name, arch), nil case "Server", "Nano Server", "Domain Controller": @@ -819,12 +818,12 @@ func detectOSNameFromOSInfo(osInfo osInfo) (string, error) { case "Server Core": name, err := formatNamebyBuild("Server", osInfo.build) if err != nil { - return "", xerrors.Errorf("Failed to format name by build: %w", err) + return "", fmt.Errorf("Failed to format name by build: %w", err) } return fmt.Sprintf("%s (Server Core installation)", name), nil } } - return "", xerrors.New("OS Name not found") + return "", errors.New("OS Name not found") } func formatArch(arch string) (string, error) { @@ -838,7 +837,7 @@ func formatArch(arch string) (string, error) { case "x86", "X86-based": return "32-bit", nil default: - return "", xerrors.Errorf("CPU Architecture not found. expected: %q, actual: %q", []string{"AMD64", "x64-based", "ARM64", "ARM64-based", "IA64", "Itanium-based", "x86", "X86-based"}, arch) + return "", fmt.Errorf("CPU Architecture not found. expected: %q, actual: %q", []string{"AMD64", "x64-based", "ARM64", "ARM64-based", "IA64", "Itanium-based", "x86", "X86-based"}, arch) } } @@ -1007,19 +1006,19 @@ var ( func formatNamebyBuild(osType string, mybuild string) (string, error) { builds, ok := winBuilds[osType] if !ok { - return "", xerrors.New("OS Type not found") + return "", errors.New("OS Type not found") } nMybuild, err := strconv.Atoi(mybuild) if err != nil { - return "", xerrors.Errorf("Failed to parse build number. err: %w", err) + return "", fmt.Errorf("Failed to parse build number. err: %w", err) } v := builds[0].name for _, b := range builds { nBuild, err := strconv.Atoi(b.build) if err != nil { - return "", xerrors.Errorf("Failed to parse build number. err: %w", err) + return "", fmt.Errorf("Failed to parse build number. err: %w", err) } if nMybuild < nBuild { break @@ -1070,11 +1069,11 @@ func (w *windows) detectIPAddr() error { func (w *windows) ip() ([]string, []string, error) { r := w.exec("ipconfig.exe", noSudo) if !r.isSuccess() { - return nil, nil, xerrors.Errorf("Failed to detect IP address: %v", r) + return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r) } ipv4Addrs, ipv6Addrs, err := w.parseIP(r.Stdout) if err != nil { - return nil, nil, xerrors.Errorf("Failed to parse IP address: %w", err) + return nil, nil, fmt.Errorf("Failed to parse IP address: %w", err) } return ipv4Addrs, ipv6Addrs, nil } @@ -1111,7 +1110,7 @@ func (w *windows) parseIP(stdout string) ([]string, []string, error) { } } if err := scanner.Err(); err != nil { - return nil, nil, xerrors.Errorf("Failed to scan ipconfig output. err: %w", err) + return nil, nil, fmt.Errorf("Failed to scan ipconfig output. err: %w", err) } return ipv4Addrs, ipv6Addrs, nil @@ -1121,7 +1120,7 @@ func (w *windows) scanPackages() error { if r := w.exec(w.translateCmd("Get-Package | Select-Object Name, Version, ProviderName, @{Name='Publisher';Expression={$_.Metadata['Publisher']}} | Format-List | Out-String -Width 1024"), noSudo); r.isSuccess() { installed, _, err := w.parseInstalledPackages(r.Stdout) if err != nil { - return xerrors.Errorf("Failed to parse installed packages. err: %w", err) + return fmt.Errorf("Failed to parse installed packages. err: %w", err) } // Fill in missing vendor info from registry for packages where Get-Package Metadata['Publisher'] is empty (e.g. msi provider) @@ -1135,7 +1134,7 @@ func (w *windows) scanPackages() error { if r := w.exec(w.translateCmd("Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue | Select-Object DisplayName, Publisher | Format-List"), noSudo); r.isSuccess() { regVendors, err := w.parseRegistryPublishers(r.Stdout) if err != nil { - return xerrors.Errorf("Failed to parse registry publishers. err: %w", err) + return fmt.Errorf("Failed to parse registry publishers. err: %w", err) } for _, name := range missingVendorPkgs { if vendor, ok := regVendors[name]; ok && vendor != "" { @@ -1152,7 +1151,7 @@ func (w *windows) scanPackages() error { kbs, err := w.scanKBs() if err != nil { - return xerrors.Errorf("Failed to scan KB. err: %w", err) + return fmt.Errorf("Failed to scan KB. err: %w", err) } w.windowsKB = kbs @@ -1175,25 +1174,25 @@ func (w *windows) parseInstalledPackages(stdout string) (models.Packages, models case strings.HasPrefix(line, "Name"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, nil, xerrors.Errorf(`Failed to detect PackageName. expected: "Name : ", line: "%s"`, line) + return nil, nil, fmt.Errorf(`Failed to detect PackageName. expected: "Name : ", line: "%s"`, line) } name = strings.TrimSpace(rhs) case strings.HasPrefix(line, "Version"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, nil, xerrors.Errorf(`Failed to detect Version. expected: "Version : ", line: "%s"`, line) + return nil, nil, fmt.Errorf(`Failed to detect Version. expected: "Version : ", line: "%s"`, line) } version = strings.TrimSpace(rhs) case strings.HasPrefix(line, "ProviderName"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, nil, xerrors.Errorf(`Failed to detect ProviderName. expected: "ProviderName : ", line: "%s"`, line) + return nil, nil, fmt.Errorf(`Failed to detect ProviderName. expected: "ProviderName : ", line: "%s"`, line) } providerName = strings.TrimSpace(rhs) case strings.HasPrefix(line, "Publisher"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, nil, xerrors.Errorf(`Failed to detect Publisher. expected: "Publisher : ", line: "%s"`, line) + return nil, nil, fmt.Errorf(`Failed to detect Publisher. expected: "Publisher : ", line: "%s"`, line) } vendor = strings.TrimSpace(rhs) default: @@ -1201,7 +1200,7 @@ func (w *windows) parseInstalledPackages(stdout string) (models.Packages, models } if err := scanner.Err(); err != nil { - return nil, nil, xerrors.Errorf("Failed to scan installed packages stdout: %w", err) + return nil, nil, fmt.Errorf("Failed to scan installed packages stdout: %w", err) } // Handle the last entry if stdout does not end with an empty line @@ -1240,7 +1239,7 @@ func (w *windows) parseRegistryPublishers(stdout string) (map[string]string, err } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan registry publishers stdout: %w", err) + return nil, fmt.Errorf("Failed to scan registry publishers stdout: %w", err) } // Handle last entry @@ -1257,7 +1256,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if r := w.exec(w.translateCmd("Get-Hotfix | Format-List -Property HotFixID"), noSudo); r.isSuccess() { kbs, err := w.parseGetHotfix(r.Stdout) if err != nil { - return nil, xerrors.Errorf("Failed to parse Get-Hotifx. err: %w", err) + return nil, fmt.Errorf("Failed to parse Get-Hotifx. err: %w", err) } for _, kb := range kbs { applied[kb] = struct{}{} @@ -1267,7 +1266,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if r := w.exec(w.translateCmd("Get-Package -ProviderName msu | Format-List -Property Name | Out-String -Width 1024"), noSudo); r.isSuccess() { kbs, err := w.parseGetPackageMSU(r.Stdout) if err != nil { - return nil, xerrors.Errorf("Failed to parse Get-Package. err: %w", err) + return nil, fmt.Errorf("Failed to parse Get-Package. err: %w", err) } for _, kb := range kbs { applied[kb] = struct{}{} @@ -1288,7 +1287,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if r := w.exec(w.translateCmd(fmt.Sprintf(`%s $UpdateSearcher.search("IsInstalled = 1 and RebootRequired = 0 and Type='Software'").Updates | ForEach-Object -MemberName KBArticleIDs`, searcher)), noSudo); r.isSuccess() { kbs, err := w.parseWindowsUpdaterSearch(r.Stdout) if err != nil { - return xerrors.Errorf("Failed to parse Windows Update Search. err: %w", err) + return fmt.Errorf("Failed to parse Windows Update Search. err: %w", err) } for _, kb := range kbs { applied[kb] = struct{}{} @@ -1298,7 +1297,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if r := w.exec(w.translateCmd(fmt.Sprintf(`%s $UpdateSearcher.search("IsInstalled = 0 and Type='Software'").Updates | ForEach-Object -MemberName KBArticleIDs`, searcher)), noSudo); r.isSuccess() { kbs, err := w.parseWindowsUpdaterSearch(r.Stdout) if err != nil { - return xerrors.Errorf("Failed to parse Windows Update Search. err: %w", err) + return fmt.Errorf("Failed to parse Windows Update Search. err: %w", err) } for _, kb := range kbs { unapplied[kb] = struct{}{} @@ -1308,7 +1307,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if r := w.exec(w.translateCmd(fmt.Sprintf(`%s $UpdateSearcher.search("IsInstalled = 1 and RebootRequired = 1 and Type='Software'").Updates | ForEach-Object -MemberName KBArticleIDs`, searcher)), noSudo); r.isSuccess() { kbs, err := w.parseWindowsUpdaterSearch(r.Stdout) if err != nil { - return xerrors.Errorf("Failed to parse Windows Update Search. err: %w", err) + return fmt.Errorf("Failed to parse Windows Update Search. err: %w", err) } for _, kb := range kbs { unapplied[kb] = struct{}{} @@ -1317,19 +1316,19 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { if w.getServerInfo().Windows.ServerSelection == 3 { if r := w.exec(w.translateCmd(`$UpdateServiceManager = (New-Object -ComObject Microsoft.Update.ServiceManager); $UpdateServiceManager.Services | Where-Object {$_.Name -eq "Offline Sync Service"} | ForEach-Object { $UpdateServiceManager.RemoveService($_.ServiceID) };`), noSudo); !r.isSuccess() { - return xerrors.Errorf("Failed to remove Windows Update Offline Sync Service: %v", r) + return fmt.Errorf("Failed to remove Windows Update Offline Sync Service: %v", r) } } return nil }(); err != nil { - return nil, xerrors.Errorf("Failed to check Windows Update Serach. err: %w", err) + return nil, fmt.Errorf("Failed to check Windows Update Serach. err: %w", err) } if r := w.exec(w.translateCmd("$UpdateSearcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher(); $HistoryCount = $UpdateSearcher.GetTotalHistoryCount(); $UpdateSearcher.QueryHistory(0, $HistoryCount) | Sort-Object -Property Date | Format-List -Property Title, Operation, ResultCode | Out-String -Width 1024"), noSudo); r.isSuccess() { kbs, err := w.parseWindowsUpdateHistory(r.Stdout) if err != nil { - return nil, xerrors.Errorf("Failed to parse Windows Update History. err: %w", err) + return nil, fmt.Errorf("Failed to parse Windows Update History. err: %w", err) } for _, kb := range kbs { applied[kb] = struct{}{} @@ -1338,7 +1337,7 @@ func (w *windows) scanKBs() (*models.WindowsKB, error) { kbs, err := DetectKBsFromKernelVersion(w.getDistro().Release, w.Kernel.Version) if err != nil { - return nil, xerrors.Errorf("Failed to detect KBs from kernel version. err: %w", err) + return nil, fmt.Errorf("Failed to detect KBs from kernel version. err: %w", err) } for _, kb := range kbs.Applied { applied[kb] = struct{}{} @@ -1361,14 +1360,14 @@ func (w *windows) parseGetHotfix(stdout string) ([]string, error) { case strings.HasPrefix(line, "HotFixID"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, xerrors.Errorf(`Failed to detect HotFixID. expected: "HotFixID : ", line: "%s"`, line) + return nil, fmt.Errorf(`Failed to detect HotFixID. expected: "HotFixID : ", line: "%s"`, line) } kbs = append(kbs, strings.TrimPrefix(strings.TrimSpace(rhs), "KB")) default: } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan Get-Hotfix stdout. err: %w", err) + return nil, fmt.Errorf("Failed to scan Get-Hotfix stdout. err: %w", err) } return kbs, nil @@ -1386,7 +1385,7 @@ func (w *windows) parseGetPackageMSU(stdout string) ([]string, error) { case strings.HasPrefix(line, "Name"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, xerrors.Errorf(`Failed to detect PackageName. expected: "Name : ", line: "%s"`, line) + return nil, fmt.Errorf(`Failed to detect PackageName. expected: "Name : ", line: "%s"`, line) } for _, m := range kbIDPattern.FindAllStringSubmatch(strings.TrimSpace(rhs), -1) { @@ -1396,7 +1395,7 @@ func (w *windows) parseGetPackageMSU(stdout string) ([]string, error) { } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan Get-PackageMSU stdout. err: %w", err) + return nil, fmt.Errorf("Failed to scan Get-PackageMSU stdout. err: %w", err) } return kbs, nil @@ -1415,7 +1414,7 @@ func (w *windows) parseWindowsUpdaterSearch(stdout string) ([]string, error) { } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan Windows Update Search stdout. err: %w", err) + return nil, fmt.Errorf("Failed to scan Windows Update Search stdout. err: %w", err) } return kbs, nil @@ -1435,19 +1434,19 @@ func (w *windows) parseWindowsUpdateHistory(stdout string) ([]string, error) { case strings.HasPrefix(line, "Title"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, xerrors.Errorf(`Failed to detect Title. expected: "Title : ", line: "%s"`, line) + return nil, fmt.Errorf(`Failed to detect Title. expected: "Title : <Title>", line: "%s"`, line) } title = strings.TrimSpace(rhs) case strings.HasPrefix(line, "Operation"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, xerrors.Errorf(`Failed to detect Operation. expected: "Operation : <Operation>", line: "%s"`, line) + return nil, fmt.Errorf(`Failed to detect Operation. expected: "Operation : <Operation>", line: "%s"`, line) } operation = strings.TrimSpace(rhs) case strings.HasPrefix(line, "ResultCode"): _, rhs, found := strings.Cut(line, ":") if !found { - return nil, xerrors.Errorf(`Failed to detect ResultCode. expected: "ResultCode : <ResultCode>", line: "%s"`, line) + return nil, fmt.Errorf(`Failed to detect ResultCode. expected: "ResultCode : <ResultCode>", line: "%s"`, line) } // https://learn.microsoft.com/en-us/windows/win32/api/wuapi/ne-wuapi-operationresultcode @@ -1467,7 +1466,7 @@ func (w *windows) parseWindowsUpdateHistory(stdout string) ([]string, error) { } } if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("Failed to scan Windows Update History stdout. err: %w", err) + return nil, fmt.Errorf("Failed to scan Windows Update History stdout. err: %w", err) } return slices.Collect(maps.Keys(kbs)), nil @@ -5240,14 +5239,14 @@ func DetectKBsFromKernelVersion(release, kernelVersion string) (models.WindowsKB nMyRevision, err := strconv.Atoi(ss[3]) if err != nil { - return models.WindowsKB{}, xerrors.Errorf("Failed to parse revision number. err: %w", err) + return models.WindowsKB{}, fmt.Errorf("Failed to parse revision number. err: %w", err) } var index int for i, r := range rels.rollup { nRevision, err := strconv.Atoi(r.revision) if err != nil { - return models.WindowsKB{}, xerrors.Errorf("Failed to parse revision number. err: %w", err) + return models.WindowsKB{}, fmt.Errorf("Failed to parse revision number. err: %w", err) } if nMyRevision < nRevision { break @@ -5269,7 +5268,7 @@ func DetectKBsFromKernelVersion(release, kernelVersion string) (models.WindowsKB return kbs, nil default: - return models.WindowsKB{}, xerrors.Errorf("unexpected kernel version. expected: <major version>.<minor version>.<build>(.<revision>), actual: %s", kernelVersion) + return models.WindowsKB{}, fmt.Errorf("unexpected kernel version. expected: <major version>.<minor version>.<build>(.<revision>), actual: %s", kernelVersion) } } @@ -5334,7 +5333,7 @@ func (w *windows) detectRunningOnAws() (bool, string, error) { } } - return false, "", xerrors.Errorf("Failed to Invoke-WebRequest or curl.exe to AWS instance metadata on %s. container: %s", w.ServerInfo.ServerName, w.ServerInfo.Container.Name) + return false, "", fmt.Errorf("Failed to Invoke-WebRequest or curl.exe to AWS instance metadata on %s. container: %s", w.ServerInfo.ServerName, w.ServerInfo.Container.Name) } func (w *windows) scanLibraries() (err error) { @@ -5421,7 +5420,7 @@ func (w *windows) scanLibraries() (err error) { }() r := w.exec(cmd, priv) if r.ExitStatus != 0 && r.ExitStatus != 1 { - return xerrors.Errorf("Failed to find lock files: %s", r) + return fmt.Errorf("Failed to find lock files: %s", r) } scanner := bufio.NewScanner(strings.NewReader(r.Stdout)) @@ -5429,7 +5428,7 @@ func (w *windows) scanLibraries() (err error) { detectFiles = append(detectFiles, scanner.Text()) } if err := scanner.Err(); err != nil { - return xerrors.Errorf("Failed to reading find results. err: %w", err) + return fmt.Errorf("Failed to reading find results. err: %w", err) } } @@ -5446,13 +5445,13 @@ func (w *windows) scanLibraries() (err error) { r := w.exec(w.translateCmd("Get-Location | Select-object -ExpandProperty Path"), noSudo) if !r.isSuccess() { - return "", xerrors.Errorf("Failed to get current directory. err: %w", err) + return "", fmt.Errorf("Failed to get current directory. err: %w", err) } return ufilepath.Join(strings.TrimSuffix(strings.TrimSuffix(r.Stdout, "\n"), "\r"), path), nil }() if err != nil { - return xerrors.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) + return fmt.Errorf("Failed to abs the lockfile. filepath: %s, err: %w", path, err) } if _, ok := found[abspath]; ok { @@ -5467,18 +5466,18 @@ func (w *windows) scanLibraries() (err error) { r := w.exec(w.translateCmd(fmt.Sprintf("[Convert]::ToBase64String([System.IO.File]::ReadAllBytes('%s'))", abspath)), priv) if !r.isSuccess() { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to read target file contents. filepath: %s, err: %w", abspath, err) } contents, err := func() ([]byte, error) { bs, err := io.ReadAll(base64.NewDecoder(base64.StdEncoding, strings.NewReader(r.Stdout))) if err != nil { - return nil, xerrors.Errorf("Failed to decode base64 contents. err: %w", err) + return nil, fmt.Errorf("Failed to decode base64 contents. err: %w", err) } return bs, nil }() if err != nil { - return os.FileMode(0000), nil, xerrors.Errorf("Failed to read file contents from stdout. filepath: %s, err: %w", abspath, err) + return os.FileMode(0000), nil, fmt.Errorf("Failed to read file contents from stdout. filepath: %s, err: %w", abspath, err) } return filemode, contents, nil @@ -5491,7 +5490,7 @@ func (w *windows) scanLibraries() (err error) { trivypath := w.cleanPath(abspath) libraryScanners, err := AnalyzeLibrary(context.Background(), trivypath, contents, filemode, w.ServerInfo.Mode.IsOffline()) if err != nil { - return xerrors.Errorf("Failed to analyze library. err: %w, filepath: %s", err, trivypath) + return fmt.Errorf("Failed to analyze library. err: %w, filepath: %s", err, trivypath) } for _, libscanner := range libraryScanners { libscanner.LockfilePath = abspath diff --git a/tui/tui.go b/tui/tui.go index 8137966fcc..99971c0848 100644 --- a/tui/tui.go +++ b/tui/tui.go @@ -3,6 +3,7 @@ package tui import ( "bytes" "cmp" + "errors" "fmt" "os" "slices" @@ -10,8 +11,6 @@ import ( "text/template" "time" - "golang.org/x/xerrors" - "github.com/future-architect/vuls/config" "github.com/future-architect/vuls/cti" "github.com/future-architect/vuls/logging" @@ -564,7 +563,7 @@ func setSideLayout(g *gocui.Gui) error { } } if len(scanResults) == 0 { - return xerrors.New("No scan results") + return errors.New("No scan results") } currentScanResult = scanResults[0] vinfos = scanResults[0].ScannedCves.ToSortedSlice()