code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
func (p *CompactProtocol) ReadBinary() (value []byte, err error) { length, e := p.readVarint32() if e != nil { return nil, NewProtocolException(e) } if length == 0 { return []byte{}, nil } if length < 0 { return nil, invalidDataLength } if uint64(length) > p.trans.RemainingBytes() || p.trans.RemainingBytes() == UnknownRemaining { return nil, invalidDataLength } buf := make([]byte, length) _, e = io.ReadFull(p.trans, buf) return buf, NewProtocolException(e) }
1
Go
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
func ExamplePublicKeys() { var hostKey ssh.PublicKey // A public key may be used to authenticate against the remote // server by using an unencrypted PEM-encoded private key file. // // If you have an encrypted private key, the crypto/x509 package // can be used to decrypt it. key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa") if err != nil { log.Fatalf("unable to read private key: %v", err) } // Create the Signer for this private key. signer, err := ssh.ParsePrivateKey(key) if err != nil { log.Fatalf("unable to parse private key: %v", err) } config := &ssh.ClientConfig{ User: "user", Auth: []ssh.AuthMethod{ // Use the PublicKeys method for remote authentication. ssh.PublicKeys(signer), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Connect to the remote server and perform the SSH handshake. client, err := ssh.Dial("tcp", "host.com:22", config) if err != nil { log.Fatalf("unable to connect: %v", err) } defer client.Close() }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (x *WriteStorageObjectRequest) Reset() { *x = WriteStorageObjectRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (mr *MockAccessRequesterMockRecorder) Merge(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Merge", reflect.TypeOf((*MockAccessRequester)(nil).Merge), arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockCoreStrategyMockRecorder) ValidateAccessToken(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateAccessToken", reflect.TypeOf((*MockCoreStrategy)(nil).ValidateAccessToken), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func consoleInterceptorFunc(logger *zap.Logger, config Config) func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error) {
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func doesPolicySignatureV2Match(formValues http.Header) (auth.Credentials, APIErrorCode) { accessKey := formValues.Get(xhttp.AmzAccessKeyID) cred, _, s3Err := checkKeyValid(accessKey) if s3Err != ErrNone { return cred, s3Err } policy := formValues.Get("Policy") signature := formValues.Get(xhttp.AmzSignatureV2) if !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) { return cred, ErrSignatureDoesNotMatch } return cred, ErrNone }
1
Go
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
safe
func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { result, err := kex.Client(t.conn, t.config.Rand, magics) if err != nil { return nil, err } hostKey, err := ParsePublicKey(result.HostKey) if err != nil { return nil, err } if err := verifyHostKeySignature(hostKey, result); err != nil { return nil, err } if t.hostKeyCallback != nil { err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) if err != nil { return nil, err } } return result, nil }
0
Go
NVD-CWE-noinfo
null
null
null
vulnerable
func (x *DeleteStorageObjectRequest) Reset() { *x = DeleteStorageObjectRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (svc *Service) MacadminsData(ctx context.Context, id uint) (*fleet.MacadminsData, error) { if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) { if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return nil, err } host, err := svc.ds.HostLite(ctx, id) if err != nil { return nil, ctxerr.Wrap(ctx, err, "find host for macadmins") } if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } var munkiInfo *fleet.HostMunkiInfo switch version, err := svc.ds.GetMunkiVersion(ctx, id); { case err != nil && !fleet.IsNotFound(err): return nil, err case err == nil: munkiInfo = &fleet.HostMunkiInfo{Version: version} } var mdm *fleet.HostMDM switch enrolled, serverURL, installedFromDep, err := svc.ds.GetMDM(ctx, id); { case err != nil && !fleet.IsNotFound(err): return nil, err case err == nil: enrollmentStatus := "Unenrolled" if enrolled && !installedFromDep { enrollmentStatus = "Enrolled (manual)" } else if enrolled && installedFromDep { enrollmentStatus = "Enrolled (automated)" } mdm = &fleet.HostMDM{ EnrollmentStatus: enrollmentStatus, ServerURL: serverURL, } } if munkiInfo == nil && mdm == nil { return nil, nil } data := &fleet.MacadminsData{ Munki: munkiInfo, MDM: mdm, } return data, nil }
0
Go
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
func (m *MockRequester) GetClient() fosite.Client { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetClient") ret0, _ := ret[0].(fosite.Client) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func mountCgroupV1(m *configs.Mount, c *mountConfig) error { binds, err := getCgroupMounts(m) if err != nil { return err } var merged []string for _, b := range binds { ss := filepath.Base(b.Destination) if strings.Contains(ss, ",") { merged = append(merged, ss) } } tmpfs := &configs.Mount{ Source: "tmpfs", Device: "tmpfs", Destination: m.Destination, Flags: defaultMountFlags, Data: "mode=755", PropagationFlags: m.PropagationFlags, } if err := mountToRootfs(tmpfs, c); err != nil { return err } for _, b := range binds { if c.cgroupns { subsystemPath := filepath.Join(c.root, b.Destination) if err := os.MkdirAll(subsystemPath, 0755); err != nil { return err } flags := defaultMountFlags if m.Flags&unix.MS_RDONLY != 0 { flags = flags | unix.MS_RDONLY } cgroupmount := &configs.Mount{ Source: "cgroup", Device: "cgroup", // this is actually fstype Destination: subsystemPath, Flags: flags, Data: filepath.Base(subsystemPath), } if err := mountNewCgroup(cgroupmount); err != nil { return err } } else { if err := mountToRootfs(b, c); err != nil { return err } } } for _, mc := range merged { for _, ss := range strings.Split(mc, ",") { // symlink(2) is very dumb, it will just shove the path into // the link and doesn't do any checks or relative path // conversion. Also, don't error out if the cgroup already exists. if err := os.Symlink(mc, filepath.Join(c.root, m.Destination, ss)); err != nil && !os.IsExist(err) { return err } } } return nil }
0
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
vulnerable
func (mr *MockRequesterMockRecorder) GetRequestedScopes() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedScopes", reflect.TypeOf((*MockRequester)(nil).GetRequestedScopes)) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func doTmpfsCopyUp(m *configs.Mount, rootfs, mountLabel string) (Err error) { // Set up a scratch dir for the tmpfs on the host. tmpdir, err := prepareTmp("/tmp") if err != nil { return fmt.Errorf("tmpcopyup: failed to setup tmpdir: %w", err) } defer cleanupTmp(tmpdir) tmpDir, err := ioutil.TempDir(tmpdir, "runctmpdir") if err != nil { return fmt.Errorf("tmpcopyup: failed to create tmpdir: %w", err) } defer os.RemoveAll(tmpDir) // Configure the *host* tmpdir as if it's the container mount. We change // m.Destination since we are going to mount *on the host*. oldDest := m.Destination m.Destination = tmpDir err = mountPropagate(m, "/", mountLabel, nil) m.Destination = oldDest if err != nil { return err } defer func() { if Err != nil { if err := unmount(tmpDir, unix.MNT_DETACH); err != nil { logrus.Warnf("tmpcopyup: %v", err) } } }() return utils.WithProcfd(rootfs, m.Destination, func(procfd string) (Err error) { // Copy the container data to the host tmpdir. We append "/" to force // CopyDirectory to resolve the symlink rather than trying to copy the // symlink itself. if err := fileutils.CopyDirectory(procfd+"/", tmpDir); err != nil { return fmt.Errorf("tmpcopyup: failed to copy %s to %s (%s): %w", m.Destination, procfd, tmpDir, err) } // Now move the mount into the container. if err := mount(tmpDir, m.Destination, procfd, "", unix.MS_MOVE, ""); err != nil { return fmt.Errorf("tmpcopyup: failed to move mount: %w", err) } return nil }) }
1
Go
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
func ignoreTheRemainingTokens(p *parser) bool { return true }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (evpool *Pool) AddEvidence(ev types.Evidence) error { evpool.logger.Debug("Attempting to add evidence", "ev", ev) // We have already verified this piece of evidence - no need to do it again if evpool.isPending(ev) { evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev) return nil } // check that the evidence isn't already committed if evpool.isCommitted(ev) { // this can happen if the peer that sent us the evidence is behind so we shouldn't // punish the peer. evpool.logger.Debug("Evidence was already committed, ignoring this one", "ev", ev) return nil } // 1) Verify against state. err := evpool.verify(ev) if err != nil { return types.NewErrInvalidEvidence(ev, err) } // 2) Save to store. if err := evpool.addPendingEvidence(ev); err != nil { return fmt.Errorf("can't add evidence to pending list: %w", err) } // 3) Add evidence to clist. evpool.evidenceList.PushBack(ev) evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev) return nil }
0
Go
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
func (m *MockAccessRequester) GetRequestedAudience() fosite.Arguments { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetRequestedAudience") ret0, _ := ret[0].(fosite.Arguments) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (m *MockOpenIDConnectTokenStrategy) GenerateIDToken(arg0 context.Context, arg1 fosite.Requester) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GenerateIDToken", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func NewGrant(a Authorization, expiration time.Time) (Grant, error) { g := Grant{ Expiration: expiration, } msg, ok := a.(proto.Message) if !ok { return Grant{}, sdkerrors.Wrapf(sdkerrors.ErrPackAny, "cannot proto marshal %T", a) } any, err := cdctypes.NewAnyWithValue(msg) if err != nil { return Grant{}, err } g.Authorization = any return g, nil }
0
Go
CWE-754
Improper Check for Unusual or Exceptional Conditions
The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.
https://cwe.mitre.org/data/definitions/754.html
vulnerable
func (f *flight4TestMockFlightConn) writePackets(context.Context, []*packet) error { return nil }
1
Go
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
safe
func (mr *MockAccessTokenStorageMockRecorder) DeleteAccessTokenSession(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAccessTokenSession", reflect.TypeOf((*MockAccessTokenStorage)(nil).DeleteAccessTokenSession), arg0, arg1) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func isRepositoryGitPath(path string) bool { return strings.HasSuffix(path, ".git") || strings.Contains(path, ".git/") || strings.Contains(path, `.git\`) || // Windows treats ".git." the same as ".git" strings.HasSuffix(path, ".git.") || strings.Contains(path, ".git./") || strings.Contains(path, `.git.\`) }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (m *MockTokenIntrospector) IntrospectToken(arg0 context.Context, arg1 string, arg2 fosite.TokenType, arg3 fosite.AccessRequester, arg4 []string) (fosite.TokenType, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IntrospectToken", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(fosite.TokenType) ret1, _ := ret[1].(error) return ret0, ret1 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (x *ListSubscriptionsRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (p *BinaryProtocol) readStringBody(size int32) (value string, err error) { if size < 0 { return "", nil } if uint64(size) > p.trans.RemainingBytes() || p.trans.RemainingBytes() == UnknownRemaining { return "", invalidDataLength } var buf []byte if int(size) <= len(p.buffer) { buf = p.buffer[0:size] } else { buf = make([]byte, size) } _, e := io.ReadFull(p.trans, buf) return string(buf), NewProtocolException(e) }
1
Go
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
func (m *MockAuthorizeRequester) IsRedirectURIValid() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsRedirectURIValid") ret0, _ := ret[0].(bool) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func SetJWTSecret() { currentSecret, jwtErr := FetchJWTSecret() if jwtErr != nil { jwtSecretKey = []byte(RandomString(64)) // 512 bit random password if err := StoreJWTSecret(string(jwtSecretKey)); err != nil { logger.FatalLog("something went wrong when configuring JWT authentication") } } else { jwtSecretKey = []byte(currentSecret) } }
0
Go
CWE-321
Use of Hard-coded Cryptographic Key
The use of a hard-coded cryptographic key significantly increases the possibility that encrypted data may be recovered.
https://cwe.mitre.org/data/definitions/321.html
vulnerable
func (t *transferWriter) shouldSendContentLength() bool { if chunked(t.TransferEncoding) { return false } if t.ContentLength > 0 { return true } if t.ContentLength < 0 { return false } // Many servers expect a Content-Length for these methods if t.Method == "POST" || t.Method == "PUT" { return true } if t.ContentLength == 0 && isIdentity(t.TransferEncoding) { if t.Method == "GET" || t.Method == "HEAD" { return false } return true } return false }
1
Go
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
func (mr *MockAuthorizeRequesterMockRecorder) Merge(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Merge", reflect.TypeOf((*MockAuthorizeRequester)(nil).Merge), arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (*ConsoleSession) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{15} }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (mr *MockClientMockRecorder) GetID() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetID", reflect.TypeOf((*MockClient)(nil).GetID)) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (p *HTTPClient) Read(buf []byte) (int, error) { if p.response == nil { return 0, NewTransportException(NOT_OPEN, "Response buffer is empty, no request.") } n, err := p.response.Body.Read(buf) if n > 0 && (err == nil || err == io.EOF) { return n, nil } return n, NewTransportExceptionFromError(err) }
0
Go
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
vulnerable
func (x *Leaderboard) Reset() { *x = Leaderboard{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (s *Server) CheckDeletionToken(deletionToken, token, filename string) error { s.Lock(token, filename) defer s.Unlock(token, filename) var metadata Metadata r, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename)) if s.storage.IsNotExist(err) { return nil } else if err != nil { return err } defer r.Close() if err := json.NewDecoder(r).Decode(&metadata); err != nil { return err } else if metadata.DeletionToken != deletionToken { return errors.New("Deletion token doesn't match.") } return nil }
0
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
func (b *Backend) rxPacketHandler(c paho.Client, msg paho.Message) { b.wg.Add(1) defer b.wg.Done() var uplinkFrame gw.UplinkFrame t, err := marshaler.UnmarshalUplinkFrame(msg.Payload(), &uplinkFrame) if err != nil { log.WithFields(log.Fields{ "data_base64": base64.StdEncoding.EncodeToString(msg.Payload()), }).WithError(err).Error("gateway/mqtt: unmarshal uplink frame error") return } if uplinkFrame.TxInfo == nil { log.WithFields(log.Fields{ "data_base64": base64.StdEncoding.EncodeToString(msg.Payload()), }).Error("gateway/mqtt: tx_info must not be nil") return } if uplinkFrame.RxInfo == nil { log.WithFields(log.Fields{ "data_base64": base64.StdEncoding.EncodeToString(msg.Payload()), }).Error("gateway/mqtt: rx_info must not be nil") return } gatewayID := helpers.GetGatewayID(uplinkFrame.RxInfo) b.setGatewayMarshaler(gatewayID, t) uplinkID := helpers.GetUplinkID(uplinkFrame.RxInfo) log.WithFields(log.Fields{ "uplink_id": uplinkID, "gateway_id": gatewayID, }).Info("gateway/mqtt: uplink frame received") // Since with MQTT all subscribers will receive the uplink messages sent // by all the gateways, the first instance receiving the message must lock it, // so that other instances can ignore the same message (from the same gw). key := fmt.Sprintf("lora:ns:uplink:lock:%s:%d:%d:%d:%s", gatewayID, uplinkFrame.TxInfo.Frequency, uplinkFrame.RxInfo.Board, uplinkFrame.RxInfo.Antenna, hex.EncodeToString(uplinkFrame.PhyPayload)) if locked, err := b.isLocked(key); err != nil || locked { if err != nil { log.WithError(err).WithFields(log.Fields{ "uplink_id": uplinkID, "key": key, }).Error("gateway/mqtt: acquire lock error") } return } b.rxPacketChan <- uplinkFrame }
0
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error { convert := func(path string, fi os.FileInfo, err error) (e error) { uid, gid, err := GetOwner(path) if err != nil { return err } var newuid, newgid int switch how { case "in": newuid, newgid = set.ShiftIntoNs(uid, gid) case "out": newuid, newgid = set.ShiftFromNs(uid, gid) } if testmode { fmt.Printf("I would shift %q to %d %d\n", path, newuid, newgid) } else { err = os.Lchown(path, int(newuid), int(newgid)) if err == nil { m := fi.Mode() if m&os.ModeSymlink == 0 { err = os.Chmod(path, m) if err != nil { fmt.Printf("Error resetting mode on %q, continuing\n", path) } } } } return nil } if !PathExists(dir) { return fmt.Errorf("No such file or directory: %q", dir) } return filepath.Walk(dir, convert) }
0
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
vulnerable
func TimestampFileMetaEqual(actual data.TimestampFileMeta, expected data.TimestampFileMeta) error { // As opposed to snapshots, the length and hashes are still required in // TUF-1.0. See: // https://github.com/theupdateframework/specification/issues/38 if err := FileMetaEqual(actual.FileMeta, expected.FileMeta); err != nil { return err } if err := versionEqual(actual.Version, expected.Version); err != nil { return err } return nil }
0
Go
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
vulnerable
func (s *FositeMemoryStore) getClientAssertionJWT(_ context.Context, jti string) (*blacklistedJTI, error) { s.RLock() defer s.RUnlock() if exp, exists := s.BlacklistedJTIs[jti]; exists { return newBlacklistedJTI(jti, exp), nil } return nil, errors.WithStack(sqlcon.ErrNoRows) }
1
Go
CWE-294
Authentication Bypass by Capture-replay
A capture-replay flaw exists when the design of the software makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).
https://cwe.mitre.org/data/definitions/294.html
safe
func (m *MockAccessTokenStrategy) ValidateAccessToken(arg0 context.Context, arg1 fosite.Requester, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateAccessToken", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockCoreStrategyMockRecorder) GenerateAuthorizeCode(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateAuthorizeCode", reflect.TypeOf((*MockCoreStrategy)(nil).GenerateAuthorizeCode), arg0, arg1) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func TestParser(t *testing.T) { for _, testDataDir := range testDataDirs { testFiles, err := filepath.Glob(testDataDir + "*.dat") if err != nil { t.Fatal(err) } for _, tf := range testFiles { f, err := os.Open(tf) if err != nil { t.Fatal(err) } defer f.Close() r := bufio.NewReader(f) for i := 0; ; i++ { ta, err := readParseTest(r) if err == io.EOF { break } if err != nil { t.Fatal(err) } if parseTestBlacklist[ta.text] { continue } err = testParseCase(ta.text, ta.want, ta.context, ParseOptionEnableScripting(ta.scripting)) if err != nil { t.Errorf("%s test #%d %q, %s", tf, i, ta.text, err) } } } } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (mgr *MetricsManager) updateServer(cfg *Config) { if cfg.Options.MetricsAddr == mgr.addr && cfg.Options.MetricsBasicAuth == mgr.basicAuth && cfg.Options.InstallationID == mgr.installationID { return } mgr.addr = cfg.Options.MetricsAddr mgr.basicAuth = cfg.Options.MetricsBasicAuth mgr.installationID = cfg.Options.InstallationID mgr.handler = nil if mgr.addr == "" { log.Info(context.TODO()).Msg("metrics: http server disabled") return } handler, err := metrics.PrometheusHandler(EnvoyAdminURL, mgr.installationID) if err != nil { log.Error(context.TODO()).Err(err).Msg("metrics: failed to create prometheus handler") return } if username, password, ok := cfg.Options.GetMetricsBasicAuth(); ok { handler = middleware.RequireBasicAuth(username, password)(handler) } mgr.handler = handler }
0
Go
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
func IsLatestSnapshot(err error) bool { _, ok := err.(ErrLatestSnapshot) return ok }
0
Go
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
vulnerable
func validateAndUpdateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) { c.Data["Webhook"] = w if c.HasError() { c.Success(orCtx.TmplNew) return } field, msg, ok := validateWebhook(c.User, c.Locale, w) if !ok { c.FormErr(field) c.RenderWithErr(msg, orCtx.TmplNew, nil) return } if err := w.UpdateEvent(); err != nil { c.Error(err, "update event") return } else if err := db.UpdateWebhook(w); err != nil { c.Error(err, "update webhook") return } c.Flash.Success(c.Tr("repo.settings.update_hook_success")) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) }
0
Go
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
func (m *MockAuthorizeRequester) GetState() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetState") ret0, _ := ret[0].(string) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockCoreStrategyMockRecorder) ValidateRefreshToken(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateRefreshToken", reflect.TypeOf((*MockCoreStrategy)(nil).ValidateRefreshToken), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func doesPolicySignatureMatch(formValues http.Header) APIErrorCode { // For SignV2 - Signature field will be valid if _, ok := formValues["Signature"]; ok { return doesPolicySignatureV2Match(formValues) } return doesPolicySignatureV4Match(formValues) }
0
Go
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
vulnerable
func (mr *MockPKCERequestStorageMockRecorder) CreatePKCERequestSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreatePKCERequestSession", reflect.TypeOf((*MockPKCERequestStorage)(nil).CreatePKCERequestSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (p *GitLabProvider) addProjectsToSession(ctx context.Context, s *sessions.SessionState) { // Iterate over projects, check if oauth2-proxy can get project information on behalf of the user for _, project := range p.Projects { projectInfo, err := p.getProjectInfo(ctx, s, project.Name) if err != nil { logger.Errorf("Warning: project info request failed: %v", err) continue } if !projectInfo.Archived { perms := projectInfo.Permissions.ProjectAccess if perms == nil { // use group project access as fallback perms = projectInfo.Permissions.GroupAccess // group project access is not set for this user then we give up if perms == nil { logger.Errorf("Warning: user %q has no project level access to %s", s.Email, project.Name) continue } } if perms != nil && perms.AccessLevel >= project.AccessLevel { s.Groups = append(s.Groups, fmt.Sprintf("project:%s", project.Name)) } else { logger.Errorf("Warning: user %q does not have the minimum required access level for project %q", s.Email, project.Name) } } else { logger.Errorf("Warning: project %s is archived", project.Name) } } }
0
Go
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
func UnpackTar(filename string, destination string, verbosityLevel int) (err error) { Verbose = verbosityLevel f, err := os.Stat(destination) if os.IsNotExist(err) { return fmt.Errorf("destination directory '%s' does not exist", destination) } filemode := f.Mode() if !filemode.IsDir() { return fmt.Errorf("destination '%s' is not a directory", destination) } if !validSuffix(filename) { return fmt.Errorf("unrecognized archive suffix") } var file *os.File // #nosec G304 if file, err = os.Open(filename); err != nil { return err } defer file.Close() err = os.Chdir(destination) if err != nil { return errors.Wrapf(err, "error changing directory to %s", destination) } var fileReader io.Reader = file var decompressor *gzip.Reader if strings.HasSuffix(filename, globals.GzExt) { if decompressor, err = gzip.NewReader(file); err != nil { return err } defer decompressor.Close() } var reader *tar.Reader if decompressor != nil { reader = tar.NewReader(decompressor) } else { reader = tar.NewReader(fileReader) } return unpackTarFiles(reader) }
0
Go
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
func (mr *MockClientMockRecorder) GetHashedSecret() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHashedSecret", reflect.TypeOf((*MockClient)(nil).GetHashedSecret)) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (*MatchStateRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{32} }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (m *MockAuthorizeRequester) SetRequestedAudience(arg0 fosite.Arguments) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetRequestedAudience", arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (m *MockCoreStorage) GetAccessTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Session) (fosite.Requester, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccessTokenSession", arg0, arg1, arg2) ret0, _ := ret[0].(fosite.Requester) ret1, _ := ret[1].(error) return ret0, ret1 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) { sess := x.Limit(20, (page-1)*20) if rid > 0 { sess.Where("repo_id=?", rid).And("is_closed=?", isClosed) } else { sess.Where("is_closed=?", isClosed) } if uid > 0 { sess.And("assignee_id=?", uid) } else if pid > 0 { sess.And("poster_id=?", pid) } if mid > 0 { sess.And("milestone_id=?", mid) } if len(labelIds) > 0 { for _, label := range strings.Split(labelIds, ",") { // Prevent SQL inject. if com.StrTo(label).MustInt() > 0 { sess.And("label_ids like '%$" + label + "|%'") } } } switch sortType { case "oldest": sess.Asc("created") case "recentupdate": sess.Desc("updated") case "leastupdate": sess.Asc("updated") case "mostcomment": sess.Desc("num_comments") case "leastcomment": sess.Asc("num_comments") case "priority": sess.Desc("priority") default: sess.Desc("created") } var issues []Issue err := sess.Find(&issues) return issues, err }
1
Go
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
func (mr *MockPKCERequestStorageMockRecorder) DeletePKCERequestSession(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePKCERequestSession", reflect.TypeOf((*MockPKCERequestStorage)(nil).DeletePKCERequestSession), arg0, arg1) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockTokenRevocationStorageMockRecorder) DeleteAccessTokenSession(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAccessTokenSession", reflect.TypeOf((*MockTokenRevocationStorage)(nil).DeleteAccessTokenSession), arg0, arg1) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error { f.lock.Lock() defer f.lock.Unlock() if !f.valid { return errBadFilter } if len(conds) == 0 { if err := f.addRuleWrapper(call, action, exact, 0, nil); err != nil { return err } } else { // We don't support conditional filtering in library version v2.1 if !checkVersionAbove(2, 2, 1) { return VersionError{ message: "conditional filtering is not supported", minimum: "2.2.1", } } argsArr := C.make_arg_cmp_array(C.uint(len(conds))) if argsArr == nil { return fmt.Errorf("error allocating memory for conditions") } defer C.free(argsArr) for i, cond := range conds { C.add_struct_arg_cmp(C.scmp_cast_t(argsArr), C.uint(i), C.uint(cond.Argument), cond.Op.toNative(), C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2)) } if err := f.addRuleWrapper(call, action, exact, C.uint(len(conds)), C.scmp_cast_t(argsArr)); err != nil { return err } } return nil }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (mr *MockTokenRevocationStorageMockRecorder) GetRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRefreshTokenSession", reflect.TypeOf((*MockTokenRevocationStorage)(nil).GetRefreshTokenSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (t *transferWriter) shouldSendContentLength() bool { if chunked(t.TransferEncoding) { return false } if t.ContentLength > 0 { return true } if t.ContentLength < 0 { return false } // Many servers expect a Content-Length for these methods if t.Method == "POST" || t.Method == "PUT" { return true } if t.ContentLength == 0 && isIdentity(t.TransferEncoding) { if t.Method == "GET" || t.Method == "HEAD" { return false } return true } return false }
1
Go
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) { // Logic based on response type or status if noBodyExpected(requestMethod) { return 0, nil } if status/100 == 1 { return 0, nil } switch status { case 204, 304: return 0, nil } // Logic based on Transfer-Encoding if chunked(te) { return -1, nil } // Logic based on Content-Length cl := strings.TrimSpace(header.get("Content-Length")) if cl != "" { n, err := parseContentLength(cl) if err != nil { return -1, err } return n, nil } else { header.Del("Content-Length") } if !isResponse && requestMethod == "GET" { // RFC 2616 doesn't explicitly permit nor forbid an // entity-body on a GET request so we permit one if // declared, but we default to 0 here (not -1 below) // if there's no mention of a body. return 0, nil } // Body-EOF logic based on other methods (like closing, or chunked coding) return -1, nil }
0
Go
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
func isMatchingRedirectURI(uri string, haystack []string) bool { requested, err := url.Parse(uri) if err != nil { return false } for _, b := range haystack { if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) { return true } } return false }
0
Go
CWE-178
Improper Handling of Case Sensitivity
The software does not properly account for differences in case sensitivity when accessing or determining the properties of a resource, leading to inconsistent results.
https://cwe.mitre.org/data/definitions/178.html
vulnerable
func TestService_ListSoftware(t *testing.T) { ds := new(mock.Store) var calledWithTeamID *uint var calledWithOpt fleet.SoftwareListOptions ds.ListSoftwareFunc = func(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) { calledWithTeamID = opt.TeamID calledWithOpt = opt return []fleet.Software{}, nil } user := &fleet.User{ID: 3, Email: "[email protected]", GlobalRole: ptr.String(fleet.RoleObserver)} svc := newTestService(t, ds, nil, nil) ctx := context.Background() ctx = viewer.NewContext(ctx, viewer.Viewer{User: user}) _, err := svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: ptr.Uint(42), ListOptions: fleet.ListOptions{PerPage: 77, Page: 4}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Equal(t, ptr.Uint(42), calledWithTeamID) // sort order defaults to hosts_count descending, automatically, if not explicitly provided assert.Equal(t, fleet.ListOptions{PerPage: 77, Page: 4, OrderKey: "hosts_count", OrderDirection: fleet.OrderDescending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) // call again, this time with an explicit sort ds.ListSoftwareFuncInvoked = false _, err = svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: nil, ListOptions: fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Nil(t, calledWithTeamID) assert.Equal(t, fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) }
0
Go
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
func (mr *MockRequesterMockRecorder) GetSession() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSession", reflect.TypeOf((*MockRequester)(nil).GetSession)) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func doTmpfsCopyUp(m *configs.Mount, rootfs, mountLabel string) (Err error) { // Set up a scratch dir for the tmpfs on the host. tmpdir, err := prepareTmp("/tmp") if err != nil { return newSystemErrorWithCause(err, "tmpcopyup: failed to setup tmpdir") } defer cleanupTmp(tmpdir) tmpDir, err := ioutil.TempDir(tmpdir, "runctmpdir") if err != nil { return newSystemErrorWithCause(err, "tmpcopyup: failed to create tmpdir") } defer os.RemoveAll(tmpDir) // Configure the *host* tmpdir as if it's the container mount. We change // m.Destination since we are going to mount *on the host*. oldDest := m.Destination m.Destination = tmpDir err = mountPropagate(m, "/", mountLabel) m.Destination = oldDest if err != nil { return err } defer func() { if Err != nil { if err := unix.Unmount(tmpDir, unix.MNT_DETACH); err != nil { logrus.Warnf("tmpcopyup: failed to unmount tmpdir on error: %v", err) } } }() return utils.WithProcfd(rootfs, m.Destination, func(procfd string) (Err error) { // Copy the container data to the host tmpdir. We append "/" to force // CopyDirectory to resolve the symlink rather than trying to copy the // symlink itself. if err := fileutils.CopyDirectory(procfd+"/", tmpDir); err != nil { return fmt.Errorf("tmpcopyup: failed to copy %s to %s (%s): %w", m.Destination, procfd, tmpDir, err) } // Now move the mount into the container. if err := unix.Mount(tmpDir, procfd, "", unix.MS_MOVE, ""); err != nil { return fmt.Errorf("tmpcopyup: failed to move mount %s to %s (%s): %w", tmpDir, procfd, m.Destination, err) } return nil }) }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (m *Subby) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Subby: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthOne } if postIndex > l { return io.ErrUnexpectedEOF } m.Sub = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOne(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { h.L.Warnln("A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.") fmt.Fprintf(w, ` <html> <head> <title>An OAuth 2.0 Error Occurred</title> </head> <body> <h1> The OAuth2 request resulted in an error. </h1> <ul> <li>Error: %s</li> <li>Description: %s</li> <li>Hint: %s</li> <li>Debug: %s</li> </ul> <p> You are seeing this default error page because the administrator has not set a dedicated error URL (environment variable <code>OAUTH2_ERROR_URL</code> is not set). If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you need to do. If you are a user, please contact the administrator. </p> </body> </html> `, r.URL.Query().Get("error"), r.URL.Query().Get("error_description"), r.URL.Query().Get("error_hint"), r.URL.Query().Get("error_debug")) }
0
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
func (s *Shm) MarkDestroyed() { s.mu.Lock() defer s.mu.Unlock() // Prevent the segment from being found in the registry. s.key = linux.IPC_PRIVATE s.pendingDestruction = true s.DecRef() }
0
Go
NVD-CWE-noinfo
null
null
null
vulnerable
func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int, coupled bool) { msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)}) a, b := memPipe() defer a.Close() defer b.Close() key := testSigners["ecdsa"] serverConf := Config{RekeyThreshold: minRekeyThreshold} serverConf.SetDefaults() serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'}) serverConn.hostKeys = []Signer{key} go serverConn.readLoop() go serverConn.kexLoop() clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold} clientConf.SetDefaults() clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'}) clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()} clientConn.hostKeyCallback = InsecureIgnoreHostKey() go clientConn.readLoop() go clientConn.kexLoop() var wg sync.WaitGroup for _, hs := range []packetConn{serverConn, clientConn} { if !coupled { wg.Add(2) go func(c packetConn) { for i := 0; ; i++ { str := fmt.Sprintf("%08x", i) + strings.Repeat("x", int(minRekeyThreshold)/4-8) err := c.writePacket(Marshal(&serviceRequestMsg{str})) if err != nil { break } } wg.Done() c.Close() }(hs) go func(c packetConn) { for { _, err := c.readPacket() if err != nil { break } } wg.Done() }(hs) } else { wg.Add(1) go func(c packetConn) { for { _, err := c.readPacket() if err != nil { break } if err := c.writePacket(msg); err != nil { break } } wg.Done() }(hs) } } wg.Wait() }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func validatePluginData(plug *Plugin, filepath string) error { if !validPluginName.MatchString(plug.Metadata.Name) { return fmt.Errorf("invalid plugin name at %q", filepath) } // We could also validate SemVer, executable, and other fields should we so choose. return nil }
1
Go
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) GetRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRefreshTokenSession", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).GetRefreshTokenSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func testExternalNameServiceInsecure(namespace string) { Specify("external name services work over http", func() { t := f.T() f.Fixtures.Echo.Deploy(namespace, "ingress-conformance-echo") externalNameService := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: "external-name-service", }, Spec: corev1.ServiceSpec{ Type: corev1.ServiceTypeExternalName, ExternalName: "ingress-conformance-echo." + namespace, Ports: []corev1.ServicePort{ { Name: "http", Port: 80, }, }, }, } require.NoError(t, f.Client.Create(context.TODO(), externalNameService)) p := &contourv1.HTTPProxy{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: "external-name-proxy", }, Spec: contourv1.HTTPProxySpec{ VirtualHost: &contourv1.VirtualHost{ Fqdn: "externalnameservice.projectcontour.io", }, Routes: []contourv1.Route{ { Services: []contourv1.Service{ { Name: externalNameService.Name, Port: 80, }, }, RequestHeadersPolicy: &contourv1.HeadersPolicy{ Set: []contourv1.HeaderValue{ { Name: "Host", Value: externalNameService.Spec.ExternalName, }, }, }, }, }, }, } f.CreateHTTPProxyAndWaitFor(p, httpProxyValid) res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{ Host: p.Spec.VirtualHost.Fqdn, Condition: e2e.HasStatusCode(200), }) require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode) }) }
0
Go
CWE-610
Externally Controlled Reference to a Resource in Another Sphere
The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere.
https://cwe.mitre.org/data/definitions/610.html
vulnerable
func Shmctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) { id := args[0].Int() cmd := args[1].Int() buf := args[2].Pointer() r := t.IPCNamespace().ShmRegistry() switch cmd { case linux.SHM_STAT: // Technically, we should be treating id as "an index into the kernel's // internal array that maintains information about all shared memory // segments on the system". Since we don't track segments in an array, // we'll just pretend the shmid is the index and do the same thing as // IPC_STAT. Linux also uses the index as the shmid. fallthrough case linux.IPC_STAT: segment, err := findSegment(t, id) if err != nil { return 0, nil, syserror.EINVAL } stat, err := segment.IPCStat(t) if err == nil { _, err = t.CopyOut(buf, stat) } return 0, nil, err case linux.IPC_INFO: params := r.IPCInfo() _, err := t.CopyOut(buf, params) return 0, nil, err case linux.SHM_INFO: info := r.ShmInfo() _, err := t.CopyOut(buf, info) return 0, nil, err } // Remaining commands refer to a specific segment. segment, err := findSegment(t, id) if err != nil { return 0, nil, syserror.EINVAL } switch cmd { case linux.IPC_SET: var ds linux.ShmidDS _, err = t.CopyIn(buf, &ds) if err != nil { return 0, nil, err } err = segment.Set(t, &ds) return 0, nil, err case linux.IPC_RMID: segment.MarkDestroyed() return 0, nil, nil case linux.SHM_LOCK, linux.SHM_UNLOCK: // We currently do not support memory locking anywhere. // mlock(2)/munlock(2) are currently stubbed out as no-ops so do the // same here. t.Kernel().EmitUnimplementedEvent(t) return 0, nil, nil default: return 0, nil, syserror.EINVAL } }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (m *TimeFail) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTimefail } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TimeFail: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TimeFail: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TimeTest", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTimefail } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTimefail } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTimefail } if postIndex > l { return io.ErrUnexpectedEOF } if m.TimeTest == nil { m.TimeTest = new(time.Time) } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(m.TimeTest, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTimefail(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthTimefail } if (iNdEx + skippy) < 0 { return ErrInvalidLengthTimefail } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func (mr *MockCoreStorageMockRecorder) CreateRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRefreshTokenSession", reflect.TypeOf((*MockCoreStorage)(nil).CreateRefreshTokenSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func mountCgroupV2(m *configs.Mount, c *mountConfig) error { dest, err := securejoin.SecureJoin(c.root, m.Destination) if err != nil { return err } if err := os.MkdirAll(dest, 0755); err != nil { return err } if err := unix.Mount(m.Source, dest, "cgroup2", uintptr(m.Flags), m.Data); err != nil { // when we are in UserNS but CgroupNS is not unshared, we cannot mount cgroup2 (#2158) if err == unix.EPERM || err == unix.EBUSY { src := fs2.UnifiedMountpoint if c.cgroupns && c.cgroup2Path != "" { // Emulate cgroupns by bind-mounting // the container cgroup path rather than // the whole /sys/fs/cgroup. src = c.cgroup2Path } err = unix.Mount(src, dest, "", uintptr(m.Flags)|unix.MS_BIND, "") if err == unix.ENOENT && c.rootlessCgroups { err = nil } return err } return err } return nil }
0
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
vulnerable
func (*MatchState) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{31} }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (s *Service) loadCsvFile(fileName string) (*data.Frame, error) { validFileName := regexp.MustCompile(`([\w_]+)\.csv`) if !validFileName.MatchString(fileName) { return nil, fmt.Errorf("invalid csv file name: %q", fileName) } filePath := filepath.Join(s.cfg.StaticRootPath, "testdata", fileName) // Can ignore gosec G304 here, because we check the file pattern above // nolint:gosec fileReader, err := os.Open(filePath) if err != nil { return nil, fmt.Errorf("failed open file: %v", err) } defer func() { if err := fileReader.Close(); err != nil { s.logger.Warn("Failed to close file", "err", err, "path", fileName) } }() return LoadCsvContent(fileReader, fileName) }
0
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
func (svc Service) ListSoftware(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) { if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil { return nil, err } // default sort order to hosts_count descending if opt.OrderKey == "" { opt.OrderKey = "hosts_count" opt.OrderDirection = fleet.OrderDescending } opt.WithHostCounts = true return svc.ds.ListSoftware(ctx, opt) }
0
Go
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error { dir = strings.TrimRight(dir, "/") convert := func(path string, fi os.FileInfo, err error) (e error) { uid, gid, err := GetOwner(path) if err != nil { return err } var newuid, newgid int switch how { case "in": newuid, newgid = set.ShiftIntoNs(uid, gid) case "out": newuid, newgid = set.ShiftFromNs(uid, gid) } if testmode { fmt.Printf("I would shift %q to %d %d\n", path, newuid, newgid) } else { err = ShiftOwner(dir, path, int(newuid), int(newgid)) if err != nil { return err } } return nil } if !PathExists(dir) { return fmt.Errorf("No such file or directory: %q", dir) } return filepath.Walk(dir, convert) }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, length C.uint, cond C.scmp_cast_t) error { if length != 0 && cond == nil { return fmt.Errorf("null conditions list, but length is nonzero") } var retCode C.int if exact { retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } else { retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } if syscall.Errno(-1*retCode) == syscall.EFAULT { return fmt.Errorf("unrecognized syscall") } else if syscall.Errno(-1*retCode) == syscall.EPERM { return fmt.Errorf("requested action matches default action of filter") } else if syscall.Errno(-1*retCode) == syscall.EINVAL { return fmt.Errorf("two checks on same syscall argument") } else if retCode != 0 { return syscall.Errno(-1 * retCode) } return nil }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func TestBuilder_BuildBootstrapStatsConfig(t *testing.T) { b := New("local-grpc", "local-http", filemgr.NewManager(), nil) t.Run("valid", func(t *testing.T) { statsCfg, err := b.BuildBootstrapStatsConfig(&config.Config{ Options: &config.Options{ Services: "all", }, }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "statsTags": [{ "tagName": "service", "fixedValue": "pomerium" }] } `, statsCfg) }) }
0
Go
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
func (m *MockAccessTokenStorage) DeleteAccessTokenSession(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteAccessTokenSession", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (m *MockAccessRequester) Merge(arg0 fosite.Requester) { m.ctrl.T.Helper() m.ctrl.Call(m, "Merge", arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (*RuntimeInfo_ModuleInfo) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{41, 0} }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func isLoopbackURI(requested *url.URL, registeredURI string) bool { registered, err := url.Parse(registeredURI) if err != nil { return false } if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) { return false } if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path { return true } return false }
0
Go
CWE-178
Improper Handling of Case Sensitivity
The software does not properly account for differences in case sensitivity when accessing or determining the properties of a resource, leading to inconsistent results.
https://cwe.mitre.org/data/definitions/178.html
vulnerable
func (x *CallApiEndpointResponse) Reset() { *x = CallApiEndpointResponse{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func LoadDir(dirname string) (*Plugin, error) { data, err := ioutil.ReadFile(filepath.Join(dirname, PluginFileName)) if err != nil { return nil, err } plug := &Plugin{Dir: dirname} if err := yaml.Unmarshal(data, &plug.Metadata); err != nil { return nil, err } return plug, nil }
0
Go
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*initProcess, error) { cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard)) nsMaps := make(map[configs.NamespaceType]string) for _, ns := range c.config.Namespaces { if ns.Path != "" { nsMaps[ns.Type] = ns.Path } } _, sharePidns := nsMaps[configs.NEWPID] data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps, initStandard) if err != nil { return nil, err } if c.shouldSendMountSources() { // Elements on this slice will be paired with mounts (see StartInitialization() and // prepareRootfs()). This slice MUST have the same size as c.config.Mounts. mountFds := make([]int, len(c.config.Mounts)) for i, m := range c.config.Mounts { if !m.IsBind() { // Non bind-mounts do not use an fd. mountFds[i] = -1 continue } // The fd passed here will not be used: nsexec.c will overwrite it with dup3(). We just need // to allocate a fd so that we know the number to pass in the environment variable. The fd // must not be closed before cmd.Start(), so we reuse messageSockPair.child because the // lifecycle of that fd is already taken care of. cmd.ExtraFiles = append(cmd.ExtraFiles, messageSockPair.child) mountFds[i] = stdioFdCount + len(cmd.ExtraFiles) - 1 } mountFdsJson, err := json.Marshal(mountFds) if err != nil { return nil, fmt.Errorf("Error creating _LIBCONTAINER_MOUNT_FDS: %w", err) } cmd.Env = append(cmd.Env, "_LIBCONTAINER_MOUNT_FDS="+string(mountFdsJson), ) } init := &initProcess{ cmd: cmd, messageSockPair: messageSockPair, logFilePair: logFilePair, manager: c.cgroupManager, intelRdtManager: c.intelRdtManager, config: c.newInitConfig(p), container: c, process: p, bootstrapData: data, sharePidns: sharePidns, } c.initProcess = init return init, nil }
1
Go
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
func (m *Bar4) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Bar4: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Bar4: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Str", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthIssue530 } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthIssue530 } if postIndex > l { return io.ErrUnexpectedEOF } m.Str = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipIssue530(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func (*DeleteGroupUserRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{18} }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func TestClean(t *testing.T) { tests := []struct { path string wantVal string }{ { path: "../../../readme.txt", wantVal: "readme.txt", }, { path: "a/../../../readme.txt", wantVal: "readme.txt", }, { path: "/../a/b/../c/../readme.txt", wantVal: "a/readme.txt", }, { path: "../../objects/info/..", wantVal: "objects", }, { path: "/a/readme.txt", wantVal: "a/readme.txt", }, { path: "/", wantVal: "", }, { path: "/a/b/c/readme.txt", wantVal: "a/b/c/readme.txt", }, // Windows-specific { path: `..\..\..\readme.txt`, wantVal: "readme.txt", }, { path: `a\..\..\..\readme.txt`, wantVal: "readme.txt", }, { path: `\..\a\b\..\c\..\readme.txt`, wantVal: "a/readme.txt", }, { path: `\a\readme.txt`, wantVal: "a/readme.txt", }, { path: `..\..\..\../README.md`, wantVal: "README.md", }, { path: `\`, wantVal: "", }, { path: `\a\b\c\readme.txt`, wantVal: `a/b/c/readme.txt`, }, } for _, test := range tests { t.Run(test.path, func(t *testing.T) { assert.Equal(t, test.wantVal, Clean(test.path)) }) } }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (m *DroppedWithoutGetters) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypedeclall } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: DroppedWithoutGetters: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: DroppedWithoutGetters: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } m.Height = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypedeclall } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Height |= int64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Width", wireType) } m.Width = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypedeclall } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Width |= int64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipTypedeclall(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthTypedeclall } if (iNdEx + skippy) < 0 { return ErrInvalidLengthTypedeclall } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func (m *Nested) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTheproto3 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Nested: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Nested: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Bunny", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTheproto3 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTheproto3 } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTheproto3 } if postIndex > l { return io.ErrUnexpectedEOF } m.Bunny = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTheproto3(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthTheproto3 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthTheproto3 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func extractTarDirectory(root, prefix string, r io.Reader) error { tr := tar.NewReader(r) for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } // Name check name := header.Name path, err := filepath.Rel(prefix, name) if err != nil { return err } if strings.HasPrefix(path, "../") { return fmt.Errorf("%q does not have prefix %q", name, prefix) } path = filepath.Join(root, path) // Create content switch header.Typeflag { case tar.TypeReg: err = writeFile(path, tr, header.FileInfo().Mode()) case tar.TypeDir: err = os.MkdirAll(path, header.FileInfo().Mode()) case tar.TypeLink: err = os.Link(header.Linkname, path) case tar.TypeSymlink: err = os.Symlink(header.Linkname, path) default: continue // Non-regular files are skipped } if err != nil { return err } // Change access time and modification time if possible (error ignored) os.Chtimes(path, header.AccessTime, header.ModTime) } }
0
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
func handleCollectedUplink(ctx context.Context, uplinkFrame gw.UplinkFrame, rxPacket models.RXPacket) error { var uplinkIDs []uuid.UUID for _, p := range rxPacket.RXInfoSet { uplinkIDs = append(uplinkIDs, helpers.GetUplinkID(p)) } log.WithFields(log.Fields{ "uplink_ids": uplinkIDs, "mtype": rxPacket.PHYPayload.MHDR.MType, "ctx_id": ctx.Value(logging.ContextIDKey), }).Info("uplink: frame(s) collected") // update the gateway meta-data if err := gateway.UpdateMetaDataInRxInfoSet(ctx, storage.DB(), rxPacket.RXInfoSet); err != nil { log.WithError(err).Error("uplink: update gateway meta-data in rx-info set error") } // log the frame for each receiving gateway. if err := framelog.LogUplinkFrameForGateways(ctx, ns.UplinkFrameLog{ PhyPayload: uplinkFrame.PhyPayload, TxInfo: rxPacket.TXInfo, RxInfo: rxPacket.RXInfoSet, }); err != nil { log.WithFields(log.Fields{ "ctx_id": ctx.Value(logging.ContextIDKey), }).WithError(err).Error("uplink: log uplink frames for gateways error") } // handle the frame based on message-type switch rxPacket.PHYPayload.MHDR.MType { case lorawan.JoinRequest: return join.Handle(ctx, rxPacket) case lorawan.RejoinRequest: return rejoin.Handle(ctx, rxPacket) case lorawan.UnconfirmedDataUp, lorawan.ConfirmedDataUp: return data.Handle(ctx, rxPacket) case lorawan.Proprietary: return proprietary.Handle(ctx, rxPacket) default: return nil } }
0
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
func (m *MockAccessRequester) SetID(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetID", arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, cond C.scmp_cast_t) error { var length C.uint if cond != nil { length = 1 } else { length = 0 } var retCode C.int if exact { retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } else { retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond) } if syscall.Errno(-1*retCode) == syscall.EFAULT { return fmt.Errorf("unrecognized syscall") } else if syscall.Errno(-1*retCode) == syscall.EPERM { return fmt.Errorf("requested action matches default action of filter") } else if retCode != 0 { return syscall.Errno(-1 * retCode) } return nil }
0
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
func Test_buildControlPlanePathRoute(t *testing.T) { b := &Builder{filemgr: filemgr.NewManager()} route, err := b.buildControlPlanePathRoute("/hello/world", false) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "name": "pomerium-path-/hello/world", "match": { "path": "/hello/world" }, "route": { "cluster": "pomerium-control-plane-http" }, "typedPerFilterConfig": { "envoy.filters.http.ext_authz": { "@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute", "disabled": true } } } `, route) }
0
Go
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
func (m *MockResourceOwnerPasswordCredentialsGrantStorage) CreateAccessTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Requester) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateAccessTokenSession", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe