errors.Wrap -> fmt.Errorf; clean up imports (#2301)

This commit is contained in:
mmetc 2023-06-23 14:04:58 +02:00 committed by GitHub
parent d4c0643122
commit 9beb5388cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 83 additions and 93 deletions

View file

@ -13,7 +13,6 @@ import (
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
@ -124,7 +123,7 @@ func (k *KinesisSource) UnmarshalConfig(yamlConfig []byte) error {
err := yaml.UnmarshalStrict(yamlConfig, &k.Config)
if err != nil {
return errors.Wrap(err, "Cannot parse kinesis datasource configuration")
return fmt.Errorf("Cannot parse kinesis datasource configuration: %w", err)
}
if k.Config.Mode == "" {
@ -218,7 +217,7 @@ func (k *KinesisSource) WaitForConsumerDeregistration(consumerName string, strea
return nil
default:
k.logger.Errorf("Error while waiting for consumer deregistration: %s", err)
return errors.Wrap(err, "Cannot describe stream consumer")
return fmt.Errorf("cannot describe stream consumer: %w", err)
}
}
time.Sleep(time.Millisecond * 200 * time.Duration(i+1))
@ -236,12 +235,12 @@ func (k *KinesisSource) DeregisterConsumer() error {
switch err.(type) {
case *kinesis.ResourceNotFoundException:
default:
return errors.Wrap(err, "Cannot deregister stream consumer")
return fmt.Errorf("cannot deregister stream consumer: %w", err)
}
}
err = k.WaitForConsumerDeregistration(k.Config.ConsumerName, k.Config.StreamARN)
if err != nil {
return errors.Wrap(err, "Cannot wait for consumer deregistration")
return fmt.Errorf("cannot wait for consumer deregistration: %w", err)
}
return nil
}
@ -253,7 +252,7 @@ func (k *KinesisSource) WaitForConsumerRegistration(consumerARN string) error {
ConsumerARN: aws.String(consumerARN),
})
if err != nil {
return errors.Wrap(err, "Cannot describe stream consumer")
return fmt.Errorf("cannot describe stream consumer: %w", err)
}
if *describeOutput.ConsumerDescription.ConsumerStatus == "ACTIVE" {
k.logger.Debugf("Consumer %s is active", consumerARN)
@ -272,11 +271,11 @@ func (k *KinesisSource) RegisterConsumer() (*kinesis.RegisterStreamConsumerOutpu
StreamARN: aws.String(k.Config.StreamARN),
})
if err != nil {
return nil, errors.Wrap(err, "Cannot register stream consumer")
return nil, fmt.Errorf("cannot register stream consumer: %w", err)
}
err = k.WaitForConsumerRegistration(*streamConsumer.Consumer.ConsumerARN)
if err != nil {
return nil, errors.Wrap(err, "Timeout while waiting for consumer to be active")
return nil, fmt.Errorf("timeout while waiting for consumer to be active: %w", err)
}
return streamConsumer, nil
}
@ -339,7 +338,7 @@ func (k *KinesisSource) ReadFromSubscription(reader kinesis.SubscribeToShardEven
logger.Infof("Subscribed shard reader is dying")
err := reader.Close()
if err != nil {
return errors.Wrap(err, "Cannot close kinesis subscribed shard reader")
return fmt.Errorf("cannot close kinesis subscribed shard reader: %w", err)
}
return nil
case event, ok := <-reader.Events():
@ -362,7 +361,7 @@ func (k *KinesisSource) SubscribeToShards(arn arn.ARN, streamConsumer *kinesis.R
StreamName: aws.String(arn.Resource[7:]),
})
if err != nil {
return errors.Wrap(err, "Cannot list shards for enhanced_read")
return fmt.Errorf("cannot list shards for enhanced_read: %w", err)
}
for _, shard := range shards.Shards {
@ -373,7 +372,7 @@ func (k *KinesisSource) SubscribeToShards(arn arn.ARN, streamConsumer *kinesis.R
ConsumerARN: streamConsumer.Consumer.ConsumerARN,
})
if err != nil {
return errors.Wrap(err, "Cannot subscribe to shard")
return fmt.Errorf("cannot subscribe to shard: %w", err)
}
k.shardReaderTomb.Go(func() error {
return k.ReadFromSubscription(r.GetEventStream().Reader, out, shardId, arn.Resource[7:])
@ -385,7 +384,7 @@ func (k *KinesisSource) SubscribeToShards(arn arn.ARN, streamConsumer *kinesis.R
func (k *KinesisSource) EnhancedRead(out chan types.Event, t *tomb.Tomb) error {
parsedARN, err := arn.Parse(k.Config.StreamARN)
if err != nil {
return errors.Wrap(err, "Cannot parse stream ARN")
return fmt.Errorf("cannot parse stream ARN: %w", err)
}
if !strings.HasPrefix(parsedARN.Resource, "stream/") {
return fmt.Errorf("resource part of stream ARN %s does not start with stream/", k.Config.StreamARN)
@ -395,12 +394,12 @@ func (k *KinesisSource) EnhancedRead(out chan types.Event, t *tomb.Tomb) error {
k.logger.Info("starting kinesis acquisition with enhanced fan-out")
err = k.DeregisterConsumer()
if err != nil {
return errors.Wrap(err, "Cannot deregister consumer")
return fmt.Errorf("cannot deregister consumer: %w", err)
}
streamConsumer, err := k.RegisterConsumer()
if err != nil {
return errors.Wrap(err, "Cannot register consumer")
return fmt.Errorf("cannot register consumer: %w", err)
}
for {
@ -408,7 +407,7 @@ func (k *KinesisSource) EnhancedRead(out chan types.Event, t *tomb.Tomb) error {
err = k.SubscribeToShards(parsedARN, streamConsumer, out)
if err != nil {
return errors.Wrap(err, "Cannot subscribe to shards")
return fmt.Errorf("cannot subscribe to shards: %w", err)
}
select {
case <-t.Dying():
@ -417,7 +416,7 @@ func (k *KinesisSource) EnhancedRead(out chan types.Event, t *tomb.Tomb) error {
_ = k.shardReaderTomb.Wait() //we don't care about the error as we kill the tomb ourselves
err = k.DeregisterConsumer()
if err != nil {
return errors.Wrap(err, "Cannot deregister consumer")
return fmt.Errorf("cannot deregister consumer: %w", err)
}
return nil
case <-k.shardReaderTomb.Dying():
@ -440,7 +439,7 @@ func (k *KinesisSource) ReadFromShard(out chan types.Event, shardId string) erro
ShardIteratorType: aws.String(kinesis.ShardIteratorTypeLatest)})
if err != nil {
logger.Errorf("Cannot get shard iterator: %s", err)
return errors.Wrap(err, "Cannot get shard iterator")
return fmt.Errorf("cannot get shard iterator: %w", err)
}
it := sharIt.ShardIterator
//AWS recommends to wait for a second between calls to GetRecords for a given shard
@ -461,7 +460,7 @@ func (k *KinesisSource) ReadFromShard(out chan types.Event, shardId string) erro
continue
default:
logger.Error("Cannot get records")
return errors.Wrap(err, "Cannot get records")
return fmt.Errorf("cannot get records: %w", err)
}
}
k.ParseAndPushRecords(records.Records, out, logger, shardId)
@ -486,7 +485,7 @@ func (k *KinesisSource) ReadFromStream(out chan types.Event, t *tomb.Tomb) error
StreamName: aws.String(k.Config.StreamName),
})
if err != nil {
return errors.Wrap(err, "Cannot list shards")
return fmt.Errorf("cannot list shards: %w", err)
}
k.shardReaderTomb = &tomb.Tomb{}
for _, shard := range shards.Shards {

View file

@ -6,6 +6,7 @@ import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
@ -21,13 +22,13 @@ import (
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
type S3Configuration struct {
@ -563,7 +564,7 @@ func (s *S3Source) ConfigureByDSN(dsn string, labels map[string]string, logger *
if len(args) == 2 && len(args[1]) != 0 {
params, err := url.ParseQuery(args[1])
if err != nil {
return errors.Wrap(err, "could not parse s3 args")
return fmt.Errorf("could not parse s3 args: %w", err)
}
for key, value := range params {
switch key {
@ -573,7 +574,7 @@ func (s *S3Source) ConfigureByDSN(dsn string, labels map[string]string, logger *
}
lvl, err := log.ParseLevel(value[0])
if err != nil {
return errors.Wrapf(err, "unknown level %s", value[0])
return fmt.Errorf("unknown level %s: %w", value[0], err)
}
s.logger.Logger.SetLevel(lvl)
case "max_buffer_size":
@ -582,7 +583,7 @@ func (s *S3Source) ConfigureByDSN(dsn string, labels map[string]string, logger *
}
maxBufferSize, err := strconv.Atoi(value[0])
if err != nil {
return errors.Wrapf(err, "invalid value for 'max_buffer_size'")
return fmt.Errorf("invalid value for 'max_buffer_size': %w", err)
}
s.logger.Debugf("Setting max buffer size to %d", maxBufferSize)
s.Config.MaxBufferSize = maxBufferSize

View file

@ -6,7 +6,6 @@ import (
"strings"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
)
@ -31,18 +30,18 @@ func (s *SyslogServer) Listen(listenAddr string, port int) error {
s.port = port
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", s.listenAddr, s.port))
if err != nil {
return errors.Wrapf(err, "could not resolve addr %s", s.listenAddr)
return fmt.Errorf("could not resolve addr %s: %w", s.listenAddr, err)
}
udpConn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return errors.Wrapf(err, "could not listen on port %d", s.port)
return fmt.Errorf("could not listen on port %d: %w", s.port, err)
}
s.Logger.Debugf("listening on %s:%d", s.listenAddr, s.port)
s.udpConn = udpConn
err = s.udpConn.SetReadDeadline(time.Now().UTC().Add(100 * time.Millisecond))
if err != nil {
return errors.Wrap(err, "could not set read deadline on UDP socket")
return fmt.Errorf("could not set read deadline on UDP socket: %w", err)
}
return nil
}
@ -87,7 +86,7 @@ func (s *SyslogServer) StartServer() *tomb.Tomb {
func (s *SyslogServer) KillServer() error {
err := s.udpConn.Close()
if err != nil {
return errors.Wrap(err, "could not close UDP connection")
return fmt.Errorf("could not close UDP connection: %w", err)
}
close(s.channel)
return nil

View file

@ -6,7 +6,6 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
@ -100,7 +99,7 @@ func (s *SyslogSource) UnmarshalConfig(yamlConfig []byte) error {
err := yaml.UnmarshalStrict(yamlConfig, &s.config)
if err != nil {
return errors.Wrap(err, "Cannot parse syslog configuration")
return fmt.Errorf("cannot parse syslog configuration: %w", err)
}
if s.config.Addr == "" {
@ -140,7 +139,7 @@ func (s *SyslogSource) StreamingAcquisition(out chan types.Event, t *tomb.Tomb)
s.server.SetChannel(c)
err := s.server.Listen(s.config.Addr, s.config.Port)
if err != nil {
return errors.Wrap(err, "could not start syslog server")
return fmt.Errorf("could not start syslog server: %w", err)
}
s.serverTomb = s.server.StartServer()
t.Go(func() error {

View file

@ -2,17 +2,15 @@ package v1
import (
"context"
"fmt"
"net"
//"github.com/crowdsecurity/crowdsec/pkg/apiserver/controllers"
middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/csplugin"
"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/pkg/errors"
)
type Controller struct {
@ -48,7 +46,7 @@ func New(cfg *ControllerV1Config) (*Controller, error) {
profiles, err := csprofiles.NewProfile(cfg.ProfilesCfg)
if err != nil {
return &Controller{}, errors.Wrapf(err, "failed to compile profiles")
return &Controller{}, fmt.Errorf("failed to compile profiles: %w", err)
}
v1 := &Controller{

View file

@ -12,7 +12,6 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ocsp"
)
@ -176,9 +175,9 @@ func (ta *TLSAuth) isInvalid(cert *x509.Certificate, issuer *x509.Certificate) (
}
revoked, err := ta.isRevoked(cert, issuer)
if err != nil {
//Fail securely, if we can't check the revokation status, let's consider the cert invalid
//Fail securely, if we can't check the revocation status, let's consider the cert invalid
//We may change this in the future based on users feedback, but this seems the most sensible thing to do
return true, errors.Wrap(err, "could not check for client certification revokation status")
return true, fmt.Errorf("could not check for client certification revocation status: %w", err)
}
return revoked, nil
@ -231,7 +230,7 @@ func (ta *TLSAuth) ValidateCert(c *gin.Context) (bool, string, error) {
revoked, err := ta.isInvalid(clientCert, c.Request.TLS.VerifiedChains[0][1])
if err != nil {
ta.logger.Errorf("TLSAuth: error checking if client certificate is revoked: %s", err)
return false, "", errors.Wrap(err, "could not check for client certification revokation status")
return false, "", fmt.Errorf("could not check for client certification revokation status: %w", err)
}
if revoked {
return false, "", fmt.Errorf("client certificate is revoked")

View file

@ -4,7 +4,6 @@ import (
"fmt"
"path/filepath"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -39,7 +38,7 @@ func (c *Config) LoadCommon() error {
}
*k, err = filepath.Abs(*k)
if err != nil {
return errors.Wrapf(err, "failed to get absolute path of '%s'", *k)
return fmt.Errorf("failed to get absolute path of '%s': %w", *k, err)
}
}

View file

@ -3,8 +3,6 @@ package csconfig
import (
"fmt"
"path/filepath"
"github.com/pkg/errors"
)
type ConfigurationPaths struct {
@ -50,7 +48,7 @@ func (c *Config) LoadConfigurationPaths() error {
}
*k, err = filepath.Abs(*k)
if err != nil {
return errors.Wrapf(err, "failed to get absolute path of '%s'", *k)
return fmt.Errorf("failed to get absolute path of '%s': %w", *k, err)
}
}

View file

@ -2,13 +2,13 @@ package csconfig
import (
"bytes"
"errors"
"fmt"
"io"
"github.com/crowdsecurity/go-cs-lib/pkg/yamlpatch"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
@ -53,7 +53,7 @@ func (c *LocalApiServerCfg) LoadProfiles() error {
if errors.Is(err, io.EOF) {
break
}
return errors.Wrapf(err, "while decoding %s", c.ProfilesPath)
return fmt.Errorf("while decoding %s: %w", c.ProfilesPath, err)
}
c.Profiles = append(c.Profiles, &t)
}

View file

@ -2,6 +2,7 @@ package csplugin
import (
"context"
"errors"
"fmt"
"io"
"os"
@ -14,7 +15,6 @@ import (
"github.com/Masterminds/sprig/v3"
"github.com/google/uuid"
plugin "github.com/hashicorp/go-plugin"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
"gopkg.in/yaml.v2"
@ -83,10 +83,10 @@ func (pb *PluginBroker) Init(pluginCfg *csconfig.PluginCfg, profileConfigs []*cs
pb.pluginProcConfig = pluginCfg
pb.pluginsTypesToDispatch = make(map[string]struct{})
if err := pb.loadConfig(configPaths.NotificationDir); err != nil {
return errors.Wrap(err, "while loading plugin config")
return fmt.Errorf("while loading plugin config: %w", err)
}
if err := pb.loadPlugins(configPaths.PluginDir); err != nil {
return errors.Wrap(err, "while loading plugin")
return fmt.Errorf("while loading plugin: %w", err)
}
pb.watcher = PluginWatcher{}
pb.watcher.Init(pb.pluginConfigByName, pb.alertsByPluginName)
@ -268,7 +268,7 @@ func (pb *PluginBroker) loadPlugins(path string) error {
data = []byte(csstring.StrictExpand(string(data), os.LookupEnv))
_, err = pluginClient.Configure(context.Background(), &protobufs.Config{Config: data})
if err != nil {
return errors.Wrapf(err, "while configuring %s", pc.Name)
return fmt.Errorf("while configuring %s: %w", pc.Name, err)
}
log.Infof("registered plugin %s", pc.Name)
pb.notificationPluginByName[pc.Name] = pluginClient
@ -354,7 +354,7 @@ func ParsePluginConfigFile(path string) ([]PluginConfig, error) {
parsedConfigs := make([]PluginConfig, 0)
yamlFile, err := os.Open(path)
if err != nil {
return parsedConfigs, errors.Wrapf(err, "while opening %s", path)
return nil, fmt.Errorf("while opening %s: %w", path, err)
}
dec := yaml.NewDecoder(yamlFile)
dec.SetStrict(true)
@ -365,7 +365,7 @@ func ParsePluginConfigFile(path string) ([]PluginConfig, error) {
if errors.Is(err, io.EOF) {
break
}
return []PluginConfig{}, fmt.Errorf("while decoding %s got error %s", path, err)
return nil, fmt.Errorf("while decoding %s got error %s", path, err)
}
// if the yaml document is empty, skip
if reflect.DeepEqual(pc, PluginConfig{}) {

View file

@ -3,6 +3,7 @@
package csplugin
import (
"errors"
"fmt"
"io/fs"
"math"
@ -13,8 +14,6 @@ import (
"strconv"
"strings"
"syscall"
"github.com/pkg/errors"
)
func CheckCredential(uid int, gid int) *syscall.SysProcAttr {
@ -35,7 +34,7 @@ func (pb *PluginBroker) CreateCmd(binaryPath string) (*exec.Cmd, error) {
}
cmd.SysProcAttr, err = getProcessAttr(pb.pluginProcConfig.User, pb.pluginProcConfig.Group)
if err != nil {
return nil, errors.Wrap(err, "while getting process attributes")
return nil, fmt.Errorf("while getting process attributes: %w", err)
}
cmd.SysProcAttr.Credential.NoSetGroups = true
}
@ -105,17 +104,17 @@ func pluginIsValid(path string) error {
// check if it exists
if details, err = os.Stat(path); err != nil {
return errors.Wrap(err, fmt.Sprintf("plugin at %s does not exist", path))
return fmt.Errorf("plugin at %s does not exist: %w", path, err)
}
// check if it is owned by current user
currentUser, err := user.Current()
if err != nil {
return errors.Wrap(err, "while getting current user")
return fmt.Errorf("while getting current user: %w", err)
}
currentUID, err := getUID(currentUser.Username)
if err != nil {
return errors.Wrap(err, "while looking up the current uid")
return fmt.Errorf("while looking up the current uid: %w", err)
}
stat := details.Sys().(*syscall.Stat_t)
if stat.Uid != currentUID {

View file

@ -13,7 +13,6 @@ import (
"syscall"
"unsafe"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
)
@ -54,38 +53,38 @@ func CheckPerms(path string) error {
systemSid, err := windows.CreateWellKnownSid(windows.WELL_KNOWN_SID_TYPE(windows.WinLocalSystemSid))
if err != nil {
return errors.Wrap(err, "while creating SYSTEM well known sid")
return fmt.Errorf("while creating SYSTEM well known sid: %w", err)
}
adminSid, err := windows.CreateWellKnownSid(windows.WELL_KNOWN_SID_TYPE(windows.WinBuiltinAdministratorsSid))
if err != nil {
return errors.Wrap(err, "while creating built-in Administrators well known sid")
return fmt.Errorf("while creating built-in Administrators well known sid: %w", err)
}
currentUser, err := user.Current()
if err != nil {
return errors.Wrap(err, "while getting current user")
return fmt.Errorf("while getting current user: %w", err)
}
currentUserSid, _, _, err := windows.LookupSID("", currentUser.Username)
if err != nil {
return errors.Wrap(err, "while looking up current user sid")
return fmt.Errorf("while looking up current user sid: %w", err)
}
sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)
if err != nil {
return errors.Wrap(err, "while getting owner security info")
return fmt.Errorf("while getting owner security info: %w", err)
}
if !sd.IsValid() {
return errors.New("security descriptor is invalid")
return fmt.Errorf("security descriptor is invalid")
}
owner, _, err := sd.Owner()
if err != nil {
return errors.Wrap(err, "while getting owner")
return fmt.Errorf("while getting owner: %w", err)
}
if !owner.IsValid() {
return errors.New("owner is invalid")
return fmt.Errorf("owner is invalid")
}
if !owner.Equals(systemSid) && !owner.Equals(currentUserSid) && !owner.Equals(adminSid) {
@ -94,7 +93,7 @@ func CheckPerms(path string) error {
dacl, _, err := sd.DACL()
if err != nil {
return errors.Wrap(err, "while getting DACL")
return fmt.Errorf("while getting DACL: %w", err)
}
if dacl == nil {
@ -102,7 +101,7 @@ func CheckPerms(path string) error {
}
if err != nil {
return errors.Wrap(err, "while looking up current user sid")
return fmt.Errorf("while looking up current user sid: %w", err)
}
rs := reflect.ValueOf(dacl).Elem()
@ -124,7 +123,7 @@ func CheckPerms(path string) error {
ace := &AccessAllowedAce{}
ret, _, _ := procGetAce.Call(uintptr(unsafe.Pointer(dacl)), uintptr(i), uintptr(unsafe.Pointer(&ace)))
if ret == 0 {
return errors.Wrap(windows.GetLastError(), "while getting ACE")
return fmt.Errorf("while getting ACE: %w", windows.GetLastError())
}
log.Debugf("ACE %d: %+v\n", i, ace)
@ -162,14 +161,14 @@ func getProcessAtr() (*syscall.SysProcAttr, error) {
err := windows.OpenProcessToken(proc, windows.TOKEN_DUPLICATE|windows.TOKEN_ADJUST_DEFAULT|
windows.TOKEN_QUERY|windows.TOKEN_ASSIGN_PRIMARY|windows.TOKEN_ADJUST_GROUPS|windows.TOKEN_ADJUST_PRIVILEGES, &procToken)
if err != nil {
return nil, errors.Wrapf(err, "while opening process token")
return nil, fmt.Errorf("while opening process token: %w", err)
}
defer procToken.Close()
err = windows.DuplicateTokenEx(procToken, 0, nil, windows.SecurityImpersonation,
windows.TokenPrimary, &token)
if err != nil {
return nil, errors.Wrapf(err, "while duplicating token")
return nil, fmt.Errorf("while duplicating token: %w", err)
}
//Remove all privileges from the token
@ -177,7 +176,7 @@ func getProcessAtr() (*syscall.SysProcAttr, error) {
err = windows.AdjustTokenPrivileges(token, true, nil, 0, nil, nil)
if err != nil {
return nil, errors.Wrapf(err, "while adjusting token privileges")
return nil, fmt.Errorf("while adjusting token privileges: %w", err)
}
//Run the plugin as a medium integrity level process
@ -195,7 +194,7 @@ func getProcessAtr() (*syscall.SysProcAttr, error) {
(*byte)(unsafe.Pointer(tml)), tml.Size())
if err != nil {
token.Close()
return nil, errors.Wrapf(err, "while setting token information")
return nil, fmt.Errorf("while setting token information: %w", err)
}
return &windows.SysProcAttr{
@ -209,7 +208,7 @@ func (pb *PluginBroker) CreateCmd(binaryPath string) (*exec.Cmd, error) {
cmd := exec.Command(binaryPath)
cmd.SysProcAttr, err = getProcessAtr()
if err != nil {
return nil, errors.Wrap(err, "while getting process attributes")
return nil, fmt.Errorf("while getting process attributes: %w", err)
}
return cmd, err
}
@ -229,7 +228,7 @@ func pluginIsValid(path string) error {
// check if it exists
if _, err = os.Stat(path); err != nil {
return errors.Wrap(err, fmt.Sprintf("plugin at %s does not exist", path))
return fmt.Errorf("plugin at %s does not exist", path)
}
// check if it is owned by root

View file

@ -2,16 +2,17 @@ package cwhub
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"golang.org/x/mod/semver"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
)
/*the walk/parser_visit function can't receive extra args*/
@ -102,7 +103,7 @@ func parser_visit(path string, f os.DirEntry, err error) error {
when the collection is installed, both files are created
*/
//non symlinks are local user files or hub files
if f.Type() & os.ModeSymlink == 0 {
if f.Type()&os.ModeSymlink == 0 {
local = true
log.Tracef("%s isn't a symlink", path)
} else {
@ -365,7 +366,7 @@ func GetHubIdx(hub *csconfig.Hub) error {
log.Debugf("loading hub idx %s", hub.HubIndexFile)
bidx, err := os.ReadFile(hub.HubIndexFile)
if err != nil {
return errors.Wrap(err, "unable to read index file")
return fmt.Errorf("unable to read index file: %w", err)
}
ret, err := LoadPkgIndex(bidx)
if err != nil {

View file

@ -6,15 +6,14 @@ import (
"sort"
"strconv"
"github.com/antonmedv/expr"
"github.com/davecgh/go-spew/spew"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/alertcontext"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/davecgh/go-spew/spew"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/antonmedv/expr"
)
// SourceFromEvent extracts and formats a valid models.Source object from an Event
@ -53,7 +52,7 @@ func SourceFromEvent(evt types.Event, leaky *Leaky) (map[string]models.Source, e
if leaky.scopeType.RunTimeFilter != nil {
retValue, err := expr.Run(leaky.scopeType.RunTimeFilter, map[string]interface{}{"evt": &evt})
if err != nil {
return srcs, errors.Wrapf(err, "while running scope filter")
return srcs, fmt.Errorf("while running scope filter: %w", err)
}
value, ok := retValue.(string)
if !ok {
@ -128,7 +127,7 @@ func SourceFromEvent(evt types.Event, leaky *Leaky) (map[string]models.Source, e
if leaky.scopeType.RunTimeFilter != nil {
retValue, err := expr.Run(leaky.scopeType.RunTimeFilter, map[string]interface{}{"evt": &evt})
if err != nil {
return srcs, errors.Wrapf(err, "while running scope filter")
return srcs, fmt.Errorf("while running scope filter: %w", err)
}
value, ok := retValue.(string)
@ -145,7 +144,7 @@ func SourceFromEvent(evt types.Event, leaky *Leaky) (map[string]models.Source, e
}
retValue, err := expr.Run(leaky.scopeType.RunTimeFilter, map[string]interface{}{"evt": &evt})
if err != nil {
return srcs, errors.Wrapf(err, "while running scope filter")
return srcs, fmt.Errorf("while running scope filter: %w", err)
}
value, ok := retValue.(string)
@ -217,7 +216,7 @@ func alertFormatSource(leaky *Leaky, queue *Queue) (map[string]models.Source, st
for _, evt := range queue.Queue {
srcs, err := SourceFromEvent(evt, leaky)
if err != nil {
return nil, "", errors.Wrapf(err, "while extracting scope from bucket %s", leaky.Name)
return nil, "", fmt.Errorf("while extracting scope from bucket %s: %w", leaky.Name, err)
}
for key, src := range srcs {
if source_type == types.Undefined {
@ -276,7 +275,7 @@ func NewAlert(leaky *Leaky, queue *Queue) (types.RuntimeAlert, error) {
//Get the sources from Leaky/Queue
sources, source_scope, err := alertFormatSource(leaky, queue)
if err != nil {
return runtimeAlert, errors.Wrap(err, "unable to collect sources from bucket")
return runtimeAlert, fmt.Errorf("unable to collect sources from bucket: %w", err)
}
runtimeAlert.Sources = sources
//Include source info in format string