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 TestTruncatedCiphertext(t *testing.T) { key := make([]byte, 32) nonce := make([]byte, 16) data := make([]byte, 32) io.ReadFull(rand.Reader, key) io.ReadFull(rand.Reader, nonce) aead, err := NewCBCHMAC(key, aes.NewCipher) if err != nil { panic(err) } ctx := aead.(*cbcAEAD) ct := aead.Seal(nil, nonce, data, nil) // Truncated ciphertext, but with correct auth tag truncated, tail := resize(ct[:len(ct)-ctx.authtagBytes-2], len(ct)-2) copy(tail, ctx.computeAuthTag(nil, nonce, truncated[:len(truncated)-ctx.authtagBytes])) // Open should fail _, err = aead.Open(nil, nonce, truncated, nil) if err == nil { t.Error("open on truncated ciphertext should fail") } }
0
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
vulnerable
func (o *casaService) GetServerList(index, size, tp, categoryId, key string) (recommend, list, community []model.ServerAppList) { keyName := fmt.Sprintf("list_%s_%s_%s_%s", index, size, tp, categoryId) if result, ok := Cache.Get(keyName); ok { res, ok := result.(string) if ok { json2.Unmarshal([]byte(gjson.Get(res, "data.list").String()), &list) json2.Unmarshal([]byte(gjson.Get(res, "data.recommend").String()), &recommend) json2.Unmarshal([]byte(gjson.Get(res, "data.community").String()), &community) return } } head := make(map[string]string) head["Authorization"] = GetToken() listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/newlist?index="+index+"&size="+size+"&rank="+tp+"&category_id="+categoryId+"&key="+key, head) json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &list) json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommend) json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &community) if len(list) > 0 { Cache.SetDefault(keyName, listS) } return }
0
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
vulnerable
func (s *Service) handleMessage(stream StepStream, addr string, exp *certificateExpirationCheck) error { request, err := stream.Recv() if err == io.EOF { return err } if err != nil { s.Logger.Warningf("Stream read from %s failed: %v", addr, err) return err } exp.checkExpiration(time.Now(), extractChannel(request)) if s.StepLogger.IsEnabledFor(zap.DebugLevel) { nodeName := commonNameFromContext(stream.Context()) s.StepLogger.Debugf("Received message from %s(%s): %v", nodeName, addr, requestAsString(request)) } if submitReq := request.GetSubmitRequest(); submitReq != nil { nodeName := commonNameFromContext(stream.Context()) s.Logger.Debugf("Received message from %s(%s): %v", nodeName, addr, requestAsString(request)) return s.handleSubmit(submitReq, stream, addr) } // Else, it's a consensus message. return s.Dispatcher.DispatchConsensus(stream.Context(), request.GetConsensusRequest()) }
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 (mr *MockAccessResponderMockRecorder) GetAccessToken() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccessToken", reflect.TypeOf((*MockAccessResponder)(nil).GetAccessToken)) }
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 *MockAuthorizeCodeStorage) CreateAuthorizeCodeSession(arg0 context.Context, arg1 string, arg2 fosite.Requester) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateAuthorizeCodeSession", 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 (m *Int64Value) 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 ErrIntOverflowWrappers } 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: Int64Value: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Int64Value: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } m.Value = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowWrappers } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Value |= int64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipWrappers(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) < 0 { return ErrInvalidLengthWrappers } 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 (*StatusList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{40} }
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 *ProtoType) 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 ErrIntOverflowThetest } 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: ProtoType: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ProtoType: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } 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 ErrInvalidLengthThetest } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) m.Field2 = &s iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } 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 WithProcfd(root, unsafePath string, fn func(procfd string) error) error { // Remove the root then forcefully resolve inside the root. unsafePath = stripRoot(root, unsafePath) path, err := securejoin.SecureJoin(root, unsafePath) if err != nil { return fmt.Errorf("resolving path inside rootfs failed: %v", err) } // Open the target path. fh, err := os.OpenFile(path, unix.O_PATH|unix.O_CLOEXEC, 0) if err != nil { return fmt.Errorf("open o_path procfd: %w", err) } defer fh.Close() // Double-check the path is the one we expected. procfd := "/proc/self/fd/" + strconv.Itoa(int(fh.Fd())) if realpath, err := os.Readlink(procfd); err != nil { return fmt.Errorf("procfd verification failed: %w", err) } else if realpath != path { return fmt.Errorf("possibly malicious path detected -- refusing to operate on %s", realpath) } // Run the closure. return fn(procfd) }
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 (*ListAccountsRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{26} }
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 (evpool *Pool) CheckEvidence(evList types.EvidenceList) error { hashes := make([][]byte, len(evList)) for idx, ev := range evList { ok := evpool.fastCheck(ev) if !ok { // check that the evidence isn't already committed if evpool.isCommitted(ev) { return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")} } err := evpool.verify(ev) if err != nil { return err } if err := evpool.addPendingEvidence(ev); err != nil { // Something went wrong with adding the evidence but we already know it is valid // hence we log an error and continue evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev) } evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev) } // check for duplicate evidence. We cache hashes so we don't have to work them out again. hashes[idx] = ev.Hash() for i := idx - 1; i >= 0; i-- { if bytes.Equal(hashes[i], hashes[idx]) { return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")} } } } return nil }
1
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
safe
func (rarFormat) Read(input io.Reader, destination string) error { rr, err := rardecode.NewReader(input, "") if err != nil { return fmt.Errorf("read: failed to create reader: %v", err) } for { header, err := rr.Next() if err == io.EOF { break } else if err != nil { return err } err = sanitizeExtractPath(header.Name, destination) if err != nil { return err } destpath := filepath.Join(destination, header.Name) if header.IsDir { err = mkdir(destpath) if err != nil { return err } continue } // if files come before their containing folders, then we must // create their folders before writing the file err = mkdir(filepath.Dir(destpath)) if err != nil { return err } err = writeNewFile(destpath, rr, header.Mode()) if err != nil { return err } } return nil }
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 *MockRefreshTokenStrategy) GenerateRefreshToken(arg0 context.Context, arg1 fosite.Requester) (string, string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GenerateRefreshToken", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
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 isReqAuthenticated(r *http.Request, region string) (s3Error APIErrorCode) { if errCode := reqSignatureV4Verify(r, region); errCode != ErrNone { return errCode } var ( err error contentMD5, contentSHA256 []byte ) // Extract 'Content-Md5' if present. if _, ok := r.Header["Content-Md5"]; ok { contentMD5, err = base64.StdEncoding.Strict().DecodeString(r.Header.Get("Content-Md5")) if err != nil || len(contentMD5) == 0 { return ErrInvalidDigest } } // Extract either 'X-Amz-Content-Sha256' header or 'X-Amz-Content-Sha256' query parameter (if V4 presigned) // Do not verify 'X-Amz-Content-Sha256' if skipSHA256. if skipSHA256 := skipContentSha256Cksum(r); !skipSHA256 && isRequestPresignedSignatureV4(r) { if sha256Sum, ok := r.URL.Query()["X-Amz-Content-Sha256"]; ok && len(sha256Sum) > 0 { contentSHA256, err = hex.DecodeString(sha256Sum[0]) if err != nil { return ErrContentSHA256Mismatch } } } else if _, ok := r.Header["X-Amz-Content-Sha256"]; !skipSHA256 && ok { contentSHA256, err = hex.DecodeString(r.Header.Get("X-Amz-Content-Sha256")) if err != nil || len(contentSHA256) == 0 { return ErrContentSHA256Mismatch } } // Verify 'Content-Md5' and/or 'X-Amz-Content-Sha256' if present. // The verification happens implicit during reading. reader, err := hash.NewReader(r.Body, -1, hex.EncodeToString(contentMD5), hex.EncodeToString(contentSHA256)) if err != nil { return toAPIErrorCode(err) } r.Body = ioutil.NopCloser(reader) return ErrNone }
1
Go
CWE-774
Allocation of File Descriptors or Handles Without Limits or Throttling
The software allocates file descriptors or handles on behalf of an actor without imposing any restrictions on how many descriptors can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/774.html
safe
func fixTransferEncoding(requestMethod string, header Header) ([]string, error) { raw, present := header["Transfer-Encoding"] if !present { return nil, nil } delete(header, "Transfer-Encoding") encodings := strings.Split(raw[0], ",") te := make([]string, 0, len(encodings)) // TODO: Even though we only support "identity" and "chunked" // encodings, the loop below is designed with foresight. One // invariant that must be maintained is that, if present, // chunked encoding must always come first. for _, encoding := range encodings { encoding = strings.ToLower(strings.TrimSpace(encoding)) // "identity" encoding is not recorded if encoding == "identity" { break } if encoding != "chunked" { return nil, &badStringError{"unsupported transfer encoding", encoding} } te = te[0 : len(te)+1] te[len(te)-1] = encoding } if len(te) > 1 { return nil, &badStringError{"too many transfer encodings", strings.Join(te, ",")} } if len(te) > 0 { // Chunked encoding trumps Content-Length. See RFC 2616 // Section 4.4. Currently len(te) > 0 implies chunked // encoding. delete(header, "Content-Length") return te, nil } return nil, 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
users, err := ParsePasswdFilter(passwd, func(u User) bool { if userArg == "" { return u.Uid == user.Uid } if uidErr == nil { // If the userArg is numeric, always treat it as a UID. return uidArg == u.Uid } return u.Name == userArg })
1
Go
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
func signatureFromJTI(jti string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(jti))) }
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 createDeviceNode(rootfs string, node *devices.Device, bind bool) error { if node.Path == "" { // The node only exists for cgroup reasons, ignore it here. return nil } dest := filepath.Join(rootfs, node.Path) if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } if bind { return bindMountDeviceNode(dest, node) } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } else if os.IsPermission(err) { return bindMountDeviceNode(dest, node) } 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 validateShape(signatureEl *etree.Element) error { children := signatureEl.ChildElements() childCounts := map[string]int{} for _, child := range children { childCounts[child.Tag]++ } validateCount := childCounts[SignedInfoTag] == 1 && childCounts[KeyInfoTag] <= 1 && childCounts[SignatureValueTag] == 1 if !validateCount { return ErrInvalidSignature } return nil }
1
Go
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
safe
func (mr *MockAuthorizeRequesterMockRecorder) GetRequestedAudience() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedAudience", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetRequestedAudience)) }
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 *MockAccessRequesterMockRecorder) GetRequestedAt() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedAt", reflect.TypeOf((*MockAccessRequester)(nil).GetRequestedAt)) }
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 NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader { buffer := make([]byte, len(algID)+len(ptyUInfo)+len(ptyVInfo)+len(supPubInfo)+len(supPrivInfo)) n := 0 n += copy(buffer, algID) n += copy(buffer[n:], ptyUInfo) n += copy(buffer[n:], ptyVInfo) n += copy(buffer[n:], supPubInfo) copy(buffer[n:], supPrivInfo) hasher := hash.New() return &concatKDF{ z: z, info: buffer, hasher: hasher, cache: []byte{}, i: 1, } }
0
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
vulnerable
func ExampleDial() { var hostKey ssh.PublicKey // An SSH client is represented with a ClientConn. // // To authenticate with the remote server you must pass at least one // implementation of AuthMethod via the Auth field in ClientConfig, // and provide a HostKeyCallback. config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("yourpassword"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } client, err := ssh.Dial("tcp", "yourserver.com:22", config) if err != nil { log.Fatal("Failed to dial: ", err) } // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } defer session.Close() // Once a Session is created, you can execute a single command on // the remote side using the Run method. var b bytes.Buffer session.Stdout = &b if err := session.Run("/usr/bin/whoami"); err != nil { log.Fatal("Failed to run: " + err.Error()) } fmt.Println(b.String()) }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func LoadAll(basedir string) ([]*Plugin, error) { plugins := []*Plugin{} // We want basedir/*/plugin.yaml scanpath := filepath.Join(basedir, "*", PluginFileName) matches, err := filepath.Glob(scanpath) if err != nil { return plugins, errors.Wrapf(err, "failed to find plugins in %q", scanpath) } if matches == nil { return plugins, nil } for _, yaml := range matches { dir := filepath.Dir(yaml) p, err := LoadDir(dir) if err != nil { return plugins, err } plugins = append(plugins, p) } return plugins, detectDuplicates(plugins) }
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 TestReadWriteCompactProtocol(t *testing.T) { ReadWriteProtocolTest(t, NewCompactProtocolFactory()) // CompactProtocol is capable of reading and writing in different goroutines. ReadWriteProtocolParallelTest(t, NewCompactProtocolFactory()) transports := []Transport{ NewMemoryBuffer(), NewStreamTransportRW(bytes.NewBuffer(make([]byte, 0, 16384))), NewFramedTransport(NewMemoryBuffer()), } for _, trans := range transports { p := NewCompactProtocol(trans) ReadWriteBool(t, p, trans) p = NewCompactProtocol(trans) ReadWriteByte(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI16(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI32(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI64(t, p, trans) p = NewCompactProtocol(trans) ReadWriteDouble(t, p, trans) p = NewCompactProtocol(trans) ReadWriteFloat(t, p, trans) p = NewCompactProtocol(trans) ReadWriteString(t, p, trans) p = NewCompactProtocol(trans) ReadWriteBinary(t, p, trans) p = NewCompactProtocol(trans) ReadWriteStruct(t, p, trans) trans.Close() } }
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 userKeyringIDLookup(uid int) (keyringID int, err error) { cacheLock.Lock() defer cacheLock.Unlock() var ok bool if keyringID, ok = keyringIDCache[uid]; ok { return } // Our goals here are to: // - Find the user keyring (for the provided uid) // - Link it into the current process keyring (so we can use it) // - Make no permenant changes to the process privileges // Complicating this are the facts that: // - The value of KEY_SPEC_USER_KEYRING is determined by the ruid // - Keyring linking permissions use the euid // So we have to change both the ruid and euid to make this work, // setting the suid to 0 so that we can later switch back. ruid, euid, suid := getUids() if ruid != uid || euid != uid { if err = setUids(uid, uid, 0); err != nil { return } defer func() { resetErr := setUids(ruid, euid, suid) if resetErr != nil { err = resetErr } }() } // We get the value of KEY_SPEC_USER_KEYRING. Note that this will also // trigger the creation of the uid keyring if it does not yet exist. keyringID, err = unix.KeyctlGetKeyringID(unix.KEY_SPEC_USER_KEYRING, true) log.Printf("keyringID(_uid.%d) = %d, %v", uid, keyringID, err) if err != nil { return 0, err } // We still want to use this keyring after our privileges are reset. So // we link it into the process keyring, preventing a loss of access. if err = keyringLink(keyringID, unix.KEY_SPEC_PROCESS_KEYRING); err != nil { return 0, err } keyringIDCache[uid] = keyringID return keyringID, nil }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (m *MockRequester) GrantAudience(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "GrantAudience", 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 checkKeyValid(r *http.Request, accessKey string) (auth.Credentials, bool, APIErrorCode) { if !globalIAMSys.Initialized() && !globalIsGateway { // Check if server has initialized, then only proceed // to check for IAM users otherwise its okay for clients // to retry with 503 errors when server is coming up. return auth.Credentials{}, false, ErrServerNotInitialized } cred := globalActiveCred if cred.AccessKey != accessKey { // Check if the access key is part of users credentials. ucred, ok := globalIAMSys.GetUser(accessKey) if !ok { return cred, false, ErrInvalidAccessKeyID } cred = ucred } claims, s3Err := checkClaimsFromToken(r, cred) if s3Err != ErrNone { return cred, false, s3Err } cred.Claims = claims owner := cred.AccessKey == globalActiveCred.AccessKey return cred, owner, ErrNone }
1
Go
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
func TestFragmentBuffer_Overflow(t *testing.T) { fragmentBuffer := newFragmentBuffer() // Push a buffer that doesn't exceed size limits if _, err := fragmentBuffer.push([]byte{0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0x00}); err != nil { t.Fatal(err) } // Allocate a buffer that exceeds cache size largeBuffer := make([]byte, fragmentBufferMaxSize) if _, err := fragmentBuffer.push(largeBuffer); !errors.Is(err, errFragmentBufferOverflow) { t.Fatalf("Pushing a large buffer returned (%s) expected(%s)", err, errFragmentBufferOverflow) } }
1
Go
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
safe
func (d *partialArray) add(key string, val *lazyNode) error { if key == "-" { *d = append(*d, val) return nil } idx, err := strconv.Atoi(key) if err != nil { return err } ary := make([]*lazyNode, len(*d)+1) cur := *d if idx < 0 { idx *= -1 if idx > len(ary) { return fmt.Errorf("Unable to access invalid index: %d", idx) } idx = len(ary) - idx } if idx < 0 || idx >= len(ary) || idx > len(cur) { return fmt.Errorf("Unable to access invalid index: %d", idx) } copy(ary[0:idx], cur[0:idx]) ary[idx] = val copy(ary[idx+1:], cur[idx:]) *d = ary return nil }
1
Go
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
func (cs chunkState) String() string { stateString := "" switch cs { case readChunkHeader: stateString = "readChunkHeader" case readChunkTrailer: stateString = "readChunkTrailer" case readChunk: stateString = "readChunk" case verifyChunk: stateString = "verifyChunk" case eofChunk: stateString = "eofChunk" } return stateString }
0
Go
CWE-924
Improper Enforcement of Message Integrity During Transmission in a Communication Channel
The software establishes a communication channel with an endpoint and receives a message from that endpoint, but it does not sufficiently ensure that the message was not modified during transmission.
https://cwe.mitre.org/data/definitions/924.html
vulnerable
func (mr *MockAccessRequesterMockRecorder) SetSession(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSession", reflect.TypeOf((*MockAccessRequester)(nil).SetSession), 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 *MockTokenRevocationStorageMockRecorder) CreateRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRefreshTokenSession", reflect.TypeOf((*MockTokenRevocationStorage)(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 (p *Parser) parseSome() *Expr { decl := &SomeDecl{} decl.SetLoc(p.s.Loc()) // Attempt to parse "some x in xs", which will end up in // SomeDecl{Symbols: ["member(x, xs)"]} s := p.save() p.scan() if term := p.parseTermInfixCall(); term != nil { if call, ok := term.Value.(Call); ok { switch call[0].String() { case Member.Name, MemberWithKey.Name: // OK default: p.illegal("expected `x in xs` or `x, y in xs` expression") return nil } decl.Symbols = []*Term{term} expr := NewExpr(decl).SetLocation(decl.Location) if p.s.tok == tokens.With { if expr.With = p.parseWith(); expr.With == nil { return nil } } return expr } } p.restore(s) s = p.save() // new copy for later var hint bool p.scan() if term := p.futureParser().parseTermInfixCall(); term != nil { if call, ok := term.Value.(Call); ok { switch call[0].String() { case Member.Name, MemberWithKey.Name: hint = true } } } // go on as before, it's `some x[...]` or illegal p.restore(s) if hint { p.hint("`import future.keywords.in` for `some x in xs` expressions") } for { // collecting var args p.scan() if p.s.tok != tokens.Ident { p.illegal("expected var") return nil } decl.Symbols = append(decl.Symbols, p.parseVar()) p.scan() if p.s.tok != tokens.Comma { break } } return NewExpr(decl).SetLocation(decl.Location) }
0
Go
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
func (a *APIs) PostLogin(v *PostLoginReq) *kongchuanhujiao.Response { if v.Code != account.GetCode(v.ID) || v.Code == "" { // FIXME datahub 鉴权 return kongchuanhujiao.GenerateErrResp(1, "验证码有误") } now := time.Now() t, err := jwt.NewTokenWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ "iss": config.GetJWTConf().Iss, "sub": v.ID, "exp": now.AddDate(0, 1, 0).Unix(), "nbf": now.Unix(), "iat": now.Unix(), }).SignedString(config.GetJWTConf().Key) if err != nil { logger.Error("生成 JWT Token 失败", zap.Error(err)) return kongchuanhujiao.DefaultErrResp } return &kongchuanhujiao.Response{Message: t} }
0
Go
CWE-305
Authentication Bypass by Primary Weakness
The authentication algorithm is sound, but the implemented mechanism can be bypassed as the result of a separate weakness that is primary to the authentication error.
https://cwe.mitre.org/data/definitions/305.html
vulnerable
func (x *DeleteLeaderboardRecordRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[20] 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 (x *LeaderboardRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[25] 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 (m *MockCoreStrategy) GenerateAuthorizeCode(arg0 context.Context, arg1 fosite.Requester) (string, string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GenerateAuthorizeCode", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
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 SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) { // Prevent SQL inject. opt.Keyword = FilterSQLInject(opt.Keyword) if len(opt.Keyword) == 0 { return repos, nil } opt.Keyword = strings.ToLower(opt.Keyword) repos = make([]*Repository, 0, opt.Limit) // Append conditions. sess := x.Limit(opt.Limit) if opt.Uid > 0 { sess.Where("owner_id=?", opt.Uid) } if !opt.Private { sess.And("is_private=false") } sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos) return repos, 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 TestAuthMethodRSAandDSA(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["dsa"], testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("client could not authenticate with rsa key: %v", err) } }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func SettingsEmailPost(c *context.Context, f form.AddEmail) { c.Title("settings.emails") c.PageIs("SettingsEmails") // Make emailaddress primary. if c.Query("_method") == "PRIMARY" { if err := db.MakeEmailPrimary(c.UserID(), &db.EmailAddress{ID: c.QueryInt64("id")}); err != nil { c.ServerError("MakeEmailPrimary", err) return } c.SubURLRedirect("/user/settings/email") return } // Add Email address. emails, err := db.GetEmailAddresses(c.User.ID) if err != nil { c.ServerError("GetEmailAddresses", err) return } c.Data["Emails"] = emails if c.HasError() { c.Success(SETTINGS_EMAILS) return } emailAddr := &db.EmailAddress{ UID: c.User.ID, Email: f.Email, IsActivated: !conf.Auth.RequireEmailConfirmation, } if err := db.AddEmailAddress(emailAddr); err != nil { if db.IsErrEmailAlreadyUsed(err) { c.RenderWithErr(c.Tr("form.email_been_used"), SETTINGS_EMAILS, &f) } else { c.ServerError("AddEmailAddress", err) } return } // Send confirmation email if conf.Auth.RequireEmailConfirmation { email.SendActivateEmailMail(c.Context, db.NewMailerUser(c.User), emailAddr.Email) if err := c.Cache.Put("MailResendLimit_"+c.User.LowerName, c.User.LowerName, 180); err != nil { log.Error("Set cache 'MailResendLimit' failed: %v", err) } c.Flash.Info(c.Tr("settings.add_email_confirmation_sent", emailAddr.Email, conf.Auth.ActivateCodeLives/60)) } else { c.Flash.Success(c.Tr("settings.add_email_success")) } c.SubURLRedirect("/user/settings/email") }
1
Go
CWE-281
Improper Preservation of Permissions
The software does not preserve permissions or incorrectly preserves permissions when copying, restoring, or sharing objects, which can cause them to have less restrictive permissions than intended.
https://cwe.mitre.org/data/definitions/281.html
safe
func sendCode(id string) (err error) { a, err := account.SelectAccount(id, 0) if err != nil { logger.Error("发送验证码失败", zap.Error(err)) return } if len(a) == 0 { return errors.New("账号不存在") } rand.Seed(time.Now().UnixNano()) c := strconv.FormatFloat(rand.Float64(), 'f', -1, 64)[2:6] client.GetClient().SendMessage( message.NewTextMessage("您的验证码是:" + c + ",请勿泄露给他人。有效期5分钟"). SetTarget(&message.Target{ID: a[0].QQ}), ) account.WriteCode(id, c) go func() { timer := time.NewTimer(5 * time.Minute) defer timer.Stop() <-timer.C account.DeleteCode(id) }() return }
0
Go
CWE-305
Authentication Bypass by Primary Weakness
The authentication algorithm is sound, but the implemented mechanism can be bypassed as the result of a separate weakness that is primary to the authentication error.
https://cwe.mitre.org/data/definitions/305.html
vulnerable
func TestValidateAdminSignature(t *testing.T) { ctx := context.Background() objLayer, fsDir, err := prepareFS() if err != nil { t.Fatal(err) } defer os.RemoveAll(fsDir) if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil { t.Fatalf("unable initialize config file, %s", err) } creds, err := auth.CreateCredentials("admin", "mypassword") if err != nil { t.Fatalf("unable create credential, %s", err) } globalActiveCred = creds testCases := []struct { AccessKey string SecretKey string ErrCode APIErrorCode }{ {"", "", ErrInvalidAccessKeyID}, {"admin", "", ErrSignatureDoesNotMatch}, {"admin", "wrongpassword", ErrSignatureDoesNotMatch}, {"wronguser", "mypassword", ErrInvalidAccessKeyID}, {"", "mypassword", ErrInvalidAccessKeyID}, {"admin", "mypassword", ErrNone}, } for i, testCase := range testCases { req := mustNewRequest("GET", "http://localhost:9000/", 0, nil, t) if err := signRequestV4(req, testCase.AccessKey, testCase.SecretKey); err != nil { t.Fatalf("Unable to inititalized new signed http request %s", err) } _, _, _, s3Error := validateAdminSignature(ctx, req, globalMinioDefaultRegion) if s3Error != testCase.ErrCode { t.Errorf("Test %d: Unexpected s3error returned wanted %d, got %d", i+1, testCase.ErrCode, s3Error) } } }
1
Go
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
safe
func TestLoadIndex_Duplicates(t *testing.T) { if _, err := loadIndex([]byte(indexWithDuplicates)); err == nil { t.Errorf("Expected an error when duplicate entries are present") } }
1
Go
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
func (f *Fosite) writeJsonError(rw http.ResponseWriter, err error) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") rfcerr := ErrorToRFC6749Error(err) if !f.SendDebugMessagesToClients { rfcerr = rfcerr.Sanitize() } js, err := json.Marshal(rfcerr) if err != nil { if f.SendDebugMessagesToClients { errorMessage := EscapeJSONString(err.Error()) http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError) } else { http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError) } return } rw.WriteHeader(rfcerr.Code) rw.Write(js) }
0
Go
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
vulnerable
action := args[2].(func(child argoappv1.ResourceNode, appName string)) appName := "" if res, ok := data.namespacedResources[key]; ok { appName = res.AppName } action(argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: key.Kind, Group: key.Group, Namespace: key.Namespace, Name: key.Name}}, appName) }).Return(nil)
0
Go
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
func (m *MockTokenRevocationStorage) DeleteRefreshTokenSession(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteRefreshTokenSession", 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 (f *fragmentBuffer) size() int { size := 0 for i := range f.cache { for j := range f.cache[i] { size += len(f.cache[i][j].data) } } return size }
1
Go
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
safe
func TestReadMIMEHeaderNonCompliant(t *testing.T) { // Invalid HTTP response header as sent by an Axis security // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) r := reader("Foo: bar\r\n" + "Content-Language: en\r\n" + "SID : 0\r\n" + "Audio Mode : None\r\n" + "Privilege : 127\r\n\r\n") m, err := r.ReadMIMEHeader() want := MIMEHeader{ "Foo": {"bar"}, "Content-Language": {"en"}, "Sid": {"0"}, "Audio Mode": {"None"}, "Privilege": {"127"}, } if !reflect.DeepEqual(m, want) || err != nil { t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) } }
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 (mbox *Mailbox) newClient() (*client.Client, error) { var imapClient *client.Client var err error if mbox.TLS { config := new(tls.Config) config.InsecureSkipVerify = mbox.IgnoreCertErrors imapClient, err = client.DialTLS(mbox.Host, config) } else { imapClient, err = client.Dial(mbox.Host) } if err != nil { return imapClient, err } err = imapClient.Login(mbox.User, mbox.Pwd) if err != nil { return imapClient, err } _, err = imapClient.Select(mbox.Folder, mbox.ReadOnly) if err != nil { return imapClient, err } return imapClient, nil }
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 *MockAccessRequester) SetSession(arg0 fosite.Session) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetSession", 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 *TestRequest) 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 ErrIntOverflowEmpty } 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: TestRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TestRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipEmpty(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthEmpty } if (iNdEx + skippy) < 0 { return ErrInvalidLengthEmpty } 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
function validateLockfile (virtualTree, idealTree) { const errors = [] // loops through the inventory of packages resulted by ideal tree, // for each package compares the versions with the version stored in the // package-lock and adds an error to the list in case of mismatches for (const [key, entry] of idealTree.entries()) { const lock = virtualTree.get(key) if (!lock) { errors.push(`Missing: ${entry.name}@${entry.version} from lock file`) continue } if (entry.version !== lock.version) { errors.push(`Invalid: lock file's ${lock.name}@${lock.version} does ` + `not satisfy ${entry.name}@${entry.version}`) } } return errors }
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 loadIndex(data []byte) (*IndexFile, error) { i := &IndexFile{} if err := yaml.UnmarshalStrict(data, i); err != nil { return i, err } i.SortEntries() if i.APIVersion == "" { return i, ErrNoAPIVersion } return i, nil }
1
Go
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
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 } err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) if err != nil { return nil, err } return result, nil }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (mr *MockAuthorizeResponderMockRecorder) GetFragment() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFragment", reflect.TypeOf((*MockAuthorizeResponder)(nil).GetFragment)) }
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 migrationsSqlCockroach11SqlBytes() ([]byte, error) { return bindataRead( _migrationsSqlCockroach11Sql, "migrations/sql/cockroach/11.sql", ) }
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 (x *DeleteFriendRequest) Reset() { *x = DeleteFriendRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[16] 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 (h *Handle) StopAsPamUser() error { err := security.SetProcessPrivileges(h.origPrivs) if err != nil { log.Print(err) } return err }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (mr *MockTokenIntrospectorMockRecorder) IntrospectToken(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IntrospectToken", reflect.TypeOf((*MockTokenIntrospector)(nil).IntrospectToken), arg0, arg1, arg2, arg3, arg4) }
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
if rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string) bool) error); ok { r0 = rf(server, key, action) } else { r0 = ret.Error(0) } return r0 }
1
Go
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
func (m *MockAuthorizeRequester) 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 (mr *MockAccessRequesterMockRecorder) GrantAudience(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GrantAudience", reflect.TypeOf((*MockAccessRequester)(nil).GrantAudience), 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 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 memmory 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 } }
0
Go
NVD-CWE-noinfo
null
null
null
vulnerable
appendMessage = func(targetOffset uint32) bool { for _, f := range frags { if f.handshakeHeader.FragmentOffset == targetOffset { fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength) if fragmentEnd != f.handshakeHeader.Length { if !appendMessage(fragmentEnd) { return false } } rawMessage = append(f.data, rawMessage...) return true } } return false }
0
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
vulnerable
func (p *Profile) writeConfWgQuick(data *WgConf) (pth string, err error) { allowedIps := []string{} if data.Routes != nil { for _, route := range data.Routes { allowedIps = append(allowedIps, route.Network) } } if data.Routes6 != nil { for _, route := range data.Routes6 { allowedIps = append(allowedIps, route.Network) } } addr := data.Address if data.Address6 != "" { addr += "," + data.Address6 } templData := WgConfData{ Address: addr, PrivateKey: p.PrivateKeyWg, PublicKey: data.PublicKey, AllowedIps: strings.Join(allowedIps, ","), Endpoint: fmt.Sprintf("%s:%d", data.Hostname, data.Port), } if data.DnsServers != nil && len(data.DnsServers) > 0 { templData.HasDns = true templData.DnsServers = strings.Join(data.DnsServers, ",") } output := &bytes.Buffer{} err = WgConfTempl.Execute(output, templData) if err != nil { err = &errortypes.ParseError{ errors.Wrap(err, "profile: Failed to exec wg template"), } return } rootDir := "" switch runtime.GOOS { case "linux": rootDir = WgLinuxConfPath err = os.MkdirAll(WgLinuxConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } case "darwin": rootDir = WgMacConfPath err = os.MkdirAll(WgMacConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } default: rootDir, err = utils.GetTempDir() if err != nil { return } } pth = filepath.Join(rootDir, p.Iface+".conf") os.Remove(pth) err = ioutil.WriteFile( pth, []byte(output.String()), os.FileMode(0600), ) if err != nil { err = &WriteError{ errors.Wrap(err, "profile: Failed to write wg conf"), } return } return }
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 (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { // Retrieve user info userInfo, err := p.getUserInfo(ctx, s) if err != nil { return fmt.Errorf("failed to retrieve user info: %v", err) } // Check if email is verified if !p.AllowUnverifiedEmail && !userInfo.EmailVerified { return fmt.Errorf("user email is not verified") } s.User = userInfo.Username s.Email = userInfo.Email p.addGroupsToSession(ctx, s) p.addProjectsToSession(ctx, s) return 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 *Aproto3) 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 ErrIntOverflowProto3 } 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: Aproto3: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Aproto3: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field B", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowProto3 } 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 ErrInvalidLengthProto3 } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthProto3 } if postIndex > l { return io.ErrUnexpectedEOF } m.B = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipProto3(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthProto3 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthProto3 } 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 (f *Fosite) WriteAuthorizeError(rw http.ResponseWriter, ar AuthorizeRequester, err error) { rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") rfcerr := ErrorToRFC6749Error(err) if !f.SendDebugMessagesToClients { rfcerr = rfcerr.Sanitize() } if !ar.IsRedirectURIValid() { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(rfcerr) if err != nil { if f.SendDebugMessagesToClients { errorMessage := EscapeJSONString(err.Error()) http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError) } else { http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError) } return } rw.WriteHeader(rfcerr.Code) rw.Write(js) return } redirectURI := ar.GetRedirectURI() // The endpoint URI MUST NOT include a fragment component. redirectURI.Fragment = "" query := rfcerr.ToValues() query.Add("state", ar.GetState()) var redirectURIString string if !(len(ar.GetResponseTypes()) == 0 || ar.GetResponseTypes().ExactOne("code")) && !errors.Is(err, ErrUnsupportedResponseType) { redirectURIString = redirectURI.String() + "#" + query.Encode() } else { for key, values := range redirectURI.Query() { for _, value := range values { query.Add(key, value) } } redirectURI.RawQuery = query.Encode() redirectURIString = redirectURI.String() } rw.Header().Add("Location", redirectURIString) rw.WriteHeader(http.StatusFound) }
0
Go
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
vulnerable
func (m *NidRepNonByteCustomType) 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 ErrIntOverflowThetest } 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: NidRepNonByteCustomType: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: NidRepNonByteCustomType: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } m.Field1 = append(m.Field1, T{}) if err := m.Field1[len(m.Field1)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } 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 (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) { added, err := cs.addVote(vote, peerID) if err != nil { // If the vote height is off, we'll just ignore it, // But if it's a conflicting sig, add it to the cs.evpool. // If it's otherwise invalid, punish peer. // nolint: gocritic if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { if cs.privValidatorPubKey == nil { return false, errPubKeyIsNotSet } if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) { cs.Logger.Error( "Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) return added, err } var timestamp time.Time if voteErr.VoteA.Height == cs.state.InitialHeight { timestamp = cs.state.LastBlockTime // genesis time } else { timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators) } ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators) evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev) if evidenceErr != nil { cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr) } return added, err } else if err == types.ErrVoteNonDeterministicSignature { cs.Logger.Debug("Vote has non-deterministic signature", "err", err) } else { // Either // 1) bad peer OR // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR // 3) tmkms use with multiple validators connecting to a single tmkms instance // (https://github.com/tendermint/tendermint/issues/3839). cs.Logger.Info("Error attempting to add vote", "err", err) return added, ErrAddingVote } } return added, 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 *DoubleValue) 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 ErrIntOverflowWrappers } 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: DoubleValue: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: DoubleValue: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) iNdEx += 8 m.Value = float64(math.Float64frombits(v)) default: iNdEx = preIndex skippy, err := skipWrappers(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) < 0 { return ErrInvalidLengthWrappers } 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 (evpool *Pool) Update(state sm.State, ev types.EvidenceList) { // sanity check if state.LastBlockHeight <= evpool.state.LastBlockHeight { panic(fmt.Sprintf( "Failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d", state.LastBlockHeight, evpool.state.LastBlockHeight, )) } evpool.logger.Info("Updating evidence pool", "last_block_height", state.LastBlockHeight, "last_block_time", state.LastBlockTime) evpool.logger.Info( "updating evidence pool", "last_block_height", state.LastBlockHeight, "last_block_time", state.LastBlockTime, ) evpool.mtx.Lock() // flush awaiting evidence from consensus into pool evpool.flushConsensusBuffer() // update state evpool.state = state evpool.mtx.Unlock() // move committed evidence out from the pending pool and into the committed pool evpool.markEvidenceAsCommitted(ev) // prune pending evidence when it has expired. This also updates when the next evidence will expire if evpool.Size() > 0 && state.LastBlockHeight > evpool.pruningHeight && state.LastBlockTime.After(evpool.pruningTime) { evpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence() } }
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 *MockCoreStorage) 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
func (mr *MockRefreshTokenStrategyMockRecorder) GenerateRefreshToken(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateRefreshToken", reflect.TypeOf((*MockRefreshTokenStrategy)(nil).GenerateRefreshToken), 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 TestCheckValid(t *testing.T) { objLayer, fsDir, err := prepareFS() if err != nil { t.Fatal(err) } defer os.RemoveAll(fsDir) if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil { t.Fatalf("unable initialize config file, %s", err) } newAllSubsystems() initAllSubsystems(context.Background(), objLayer) globalIAMSys.InitStore(objLayer) req, err := newTestRequest(http.MethodGet, "http://example.com:9000/bucket/object", 0, nil) if err != nil { t.Fatal(err) } if err = signRequestV4(req, globalActiveCred.AccessKey, globalActiveCred.SecretKey); err != nil { t.Fatal(err) } _, owner, s3Err := checkKeyValid(req, globalActiveCred.AccessKey) if s3Err != ErrNone { t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err)) } if !owner { t.Fatalf("Expected owner to be 'true', found %t", owner) } _, _, s3Err = checkKeyValid(req, "does-not-exist") if s3Err != ErrInvalidAccessKeyID { t.Fatalf("Expected error 'ErrInvalidAccessKeyID', found %v", s3Err) } ucreds, err := auth.CreateCredentials("myuser1", "mypassword1") if err != nil { t.Fatalf("unable create credential, %s", err) } globalIAMSys.CreateUser(ucreds.AccessKey, madmin.UserInfo{ SecretKey: ucreds.SecretKey, Status: madmin.AccountEnabled, }) _, owner, s3Err = checkKeyValid(req, ucreds.AccessKey) if s3Err != ErrNone { t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err)) } if owner { t.Fatalf("Expected owner to be 'false', found %t", owner) } }
1
Go
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
func (service *Service) Send(message string, params *types.Params) error { if service.config.JSON { postURL := CreateAPIURLFromConfig(service.config) return doSend([]byte(message), postURL) } items, omitted := CreateItemsFromPlain(message, service.config.SplitLines) return service.sendItems(items, params, omitted) }
0
Go
NVD-CWE-noinfo
null
null
null
vulnerable
func (m *Timestamp) 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 ErrIntOverflowTimestamp } 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: Timestamp: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Timestamp: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Seconds", wireType) } m.Seconds = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTimestamp } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Seconds |= int64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Nanos", wireType) } m.Nanos = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTimestamp } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Nanos |= int32(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipTimestamp(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthTimestamp } if (iNdEx + skippy) < 0 { return ErrInvalidLengthTimestamp } 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 (x *MatchStateRequest) Reset() { *x = MatchStateRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[32] 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) ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) { if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil { return nil, err } gp, err := svc.ds.EnsureTeamPack(ctx, teamID) if err != nil { return nil, err } query.PackID = ptr.Uint(gp.ID) return svc.unauthorizedModifyScheduledQuery(ctx, scheduledQueryID, query) }
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 (dag *DAG) EnsureService(meta types.NamespacedName, port intstr.IntOrString, cache *KubernetesCache) (*Service, error) { svc, svcPort, err := cache.LookupService(meta, port) if err != nil { return nil, err } if dagSvc := dag.GetService(k8s.NamespacedNameOf(svc), svcPort.Port); dagSvc != nil { return dagSvc, nil } dagSvc := &Service{ Weighted: WeightedService{ ServiceName: svc.Name, ServiceNamespace: svc.Namespace, ServicePort: svcPort, Weight: 1, }, Protocol: upstreamProtocol(svc, svcPort), MaxConnections: annotation.MaxConnections(svc), MaxPendingRequests: annotation.MaxPendingRequests(svc), MaxRequests: annotation.MaxRequests(svc), MaxRetries: annotation.MaxRetries(svc), ExternalName: externalName(svc), } return dagSvc, nil }
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 (mr *MockAccessResponderMockRecorder) SetExtra(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetExtra", reflect.TypeOf((*MockAccessResponder)(nil).SetExtra), 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 (svc *Service) ListHostDeviceMapping(ctx context.Context, id uint) ([]*fleet.HostDeviceMapping, 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, "get host") } // Authorize again with team loaded now that we have team_id if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } return svc.ds.ListHostDeviceMapping(ctx, id) }
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 (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) if err != nil { return nil, err } 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 }
0
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
vulnerable
func (EmptyEvidencePool) Update(State, types.EvidenceList) {}
1
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
safe
func (f *flight4TestMockFlightConn) notify(ctx context.Context, level alert.Level, desc alert.Description) 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 (x *StorageList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[33] 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 (x *Leaderboard) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[23] 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 (x *StatusList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[40] 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 (m *CastType) 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 ErrIntOverflowExample } 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: CastType: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CastType: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Int32", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowExample } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int32(b&0x7F) << shift if b < 0x80 { break } } m.Int32 = &v default: iNdEx = preIndex skippy, err := skipExample(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthExample } if (iNdEx + skippy) < 0 { return ErrInvalidLengthExample } 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 (m *Bar9) 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: Bar9: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Bar9: 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 (err ErrInvalidCloneAddr) Error() string { return fmt.Sprintf("invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v, is_blocked_local_address: %v]", err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied, err.IsBlockedLocalAddress) }
1
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
safe
func TestAuthMethodKeyboardInteractive(t *testing.T) { answers := keyboardInteractive(map[string]string{ "question1": "answer1", "question2": "answer2", }) config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ KeyboardInteractive(answers.Challenge), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func canonicalMIMEHeaderKey(a []byte) string { upper := true for i, c := range a { // Canonicalize: first letter upper case // and upper case after each dash. // (Host, User-Agent, If-Modified-Since). // MIME headers are ASCII only, so no Unicode issues. if c == ' ' { c = '-' } else if upper && 'a' <= c && c <= 'z' { c -= toLower } else if !upper && 'A' <= c && c <= 'Z' { c += toLower } a[i] = c upper = c == '-' // for next time } // The compiler recognizes m[string(byteSlice)] as a special // case, so a copy of a's bytes into a new string does not // happen in this map lookup: if v := commonHeader[string(a)]; v != "" { return v } return string(a) }
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 (r *TokenRevocationHandler) RevokeToken(ctx context.Context, token string, tokenType fosite.TokenType, client fosite.Client) error { discoveryFuncs := []func() (request fosite.Requester, err error){ func() (request fosite.Requester, err error) { // Refresh token signature := r.RefreshTokenStrategy.RefreshTokenSignature(token) return r.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil) }, func() (request fosite.Requester, err error) { // Access token signature := r.AccessTokenStrategy.AccessTokenSignature(token) return r.TokenRevocationStorage.GetAccessTokenSession(ctx, signature, nil) }, } // Token type hinting if tokenType == fosite.AccessToken { discoveryFuncs[0], discoveryFuncs[1] = discoveryFuncs[1], discoveryFuncs[0] } var ar fosite.Requester var err error if ar, err = discoveryFuncs[0](); err != nil { ar, err = discoveryFuncs[1]() } if err != nil { return err } if ar.GetClient().GetID() != client.GetID() { return errors.WithStack(fosite.ErrRevocationClientMismatch) } requestID := ar.GetID() r.TokenRevocationStorage.RevokeRefreshToken(ctx, requestID) r.TokenRevocationStorage.RevokeAccessToken(ctx, requestID) return nil }
0
Go
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
vulnerable
func doesPolicySignatureV2Match(formValues http.Header) APIErrorCode { cred := globalActiveCred accessKey := formValues.Get(xhttp.AmzAccessKeyID) cred, _, s3Err := checkKeyValid(accessKey) if s3Err != ErrNone { return s3Err } policy := formValues.Get("Policy") signature := formValues.Get(xhttp.AmzSignatureV2) if !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) { return ErrSignatureDoesNotMatch } return ErrNone }
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 (x *DeleteWalletLedgerRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[22] 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 parseConsoleToken(hmacSecretByte []byte, tokenString string) (username, email string, role console.UserRole, exp int64, ok bool) { token, err := jwt.ParseWithClaims(tokenString, &ConsoleTokenClaims{}, func(token *jwt.Token) (interface{}, error) { if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return hmacSecretByte, nil }) if err != nil { return } claims, ok := token.Claims.(*ConsoleTokenClaims) if !ok || !token.Valid { return } return claims.Username, claims.Email, claims.Role, claims.ExpiresAt, true }
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 *Sub) 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 ErrIntOverflowUnmarshalmerge } 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: Sub: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Sub: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field SubNumber", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowUnmarshalmerge } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int64(b&0x7F) << shift if b < 0x80 { break } } m.SubNumber = &v default: iNdEx = preIndex skippy, err := skipUnmarshalmerge(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthUnmarshalmerge } if (iNdEx + skippy) < 0 { return ErrInvalidLengthUnmarshalmerge } 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 (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 } s := string(dAtA[iNdEx:postIndex]) m.Sub = &s 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