func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct {
	ID          graphql.ID
	Description string
	Query       string
	NotifyOwner bool
	NotifySlack bool
	OrgID       *graphql.ID
	UserID      *graphql.ID
}) (*savedSearchResolver, error) {
	id, err := unmarshalSavedSearchID(args.ID)
	if err != nil {
		return nil, err
	}

	old, err := r.db.SavedSearches().GetByID(ctx, id)
	if err != nil {
		return nil, errors.Wrap(err, "fetch old saved search")
	}

	// 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.
	if old.Config.UserID != nil {
		if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, *old.Config.UserID); err != nil {
			return nil, err
		}
	} else if old.Config.OrgID != nil {
		if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, *old.Config.OrgID); err != nil {
			return nil, err
		}
	} else {
		return nil, errors.New("failed to update saved search: no Org ID or User ID associated with saved search")
	}

	if !queryHasPatternType(args.Query) {
		return nil, errMissingPatternType
	}

	ss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{
		ID:          id,
		Description: args.Description,
		Query:       args.Query,
		Notify:      args.NotifyOwner,
		NotifySlack: args.NotifySlack,
		UserID:      old.Config.UserID,
		OrgID:       old.Config.OrgID,
	})
	if err != nil {
		return nil, err
	}

	return r.toSavedSearchResolver(*ss), nil
}

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.


func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
	key := keyPending(evidence)
	if err := evpool.evidenceStore.Delete(key); err != nil {
		evpool.logger.Error("Unable to delete pending evidence", "err", err)
	} else {
		atomic.AddUint32(&evpool.evidenceSize, ^uint32(0))
		evpool.logger.Debug("Deleted pending evidence", "evidence", evidence)
	}
}

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.


func (evpool *Pool) updateState(state sm.State) {
	evpool.mtx.Lock()
	defer evpool.mtx.Unlock()
	evpool.state = state
}


func (EmptyEvidencePool) CheckEvidence(evList types.EvidenceList) error   { return nil }


func safePrefix(req *http.Request) string {
	prefix := req.Header.Get("X-Forwarded-Prefix")
	if prefix == "" {
		return ""
	}

	parse, err := url.Parse(prefix)
	if err != nil {
		return ""
	}

	if parse.Host != "" {
		return ""
	}

	return parse.Path
}

URL Redirection to Untrusted Site ('Open Redirect')

A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.


func (m *MockAccessRequester) GetRequestedAt() time.Time {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetRequestedAt")
	ret0, _ := ret[0].(time.Time)
	return ret0
}

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.


func (mr *MockAccessRequesterMockRecorder) GetID() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetID", reflect.TypeOf((*MockAccessRequester)(nil).GetID))
}


func (mr *MockAccessRequesterMockRecorder) Sanitize(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sanitize", reflect.TypeOf((*MockAccessRequester)(nil).Sanitize), arg0)
}


func (mr *MockAccessResponderMockRecorder) SetScopes(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetScopes", reflect.TypeOf((*MockAccessResponder)(nil).SetScopes), arg0)
}


func (mr *MockAccessResponderMockRecorder) SetAccessToken(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAccessToken", reflect.TypeOf((*MockAccessResponder)(nil).SetAccessToken), arg0)
}


func (m *MockAccessTokenStrategy) GenerateAccessToken(arg0 context.Context, arg1 fosite.Requester) (string, string, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GenerateAccessToken", arg0, arg1)
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(string)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}


func (m *MockAuthorizeRequester) AppendRequestedScope(arg0 string) {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "AppendRequestedScope", arg0)
}


func (mr *MockAuthorizeRequesterMockRecorder) GetRequestForm() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestForm", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetRequestForm))
}


func (mr *MockAuthorizeRequesterMockRecorder) GetGrantedAudience() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGrantedAudience", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetGrantedAudience))
}


func (m *MockClient) GetHashedSecret() []byte {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetHashedSecret")
	ret0, _ := ret[0].([]byte)
	return ret0
}


func (mr *MockClientMockRecorder) GetRedirectURIs() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRedirectURIs", reflect.TypeOf((*MockClient)(nil).GetRedirectURIs))
}


func (m *MockClient) GetScopes() fosite.Arguments {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetScopes")
	ret0, _ := ret[0].(fosite.Arguments)
	return ret0
}


func (mr *MockHasherMockRecorder) Compare(arg0, arg1, arg2 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Compare", reflect.TypeOf((*MockHasher)(nil).Compare), arg0, arg1, arg2)
}


func (m *MockHasher) Hash(arg0 context.Context, arg1 []byte) ([]byte, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Hash", arg0, arg1)
	ret0, _ := ret[0].([]byte)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}


func (mr *MockClientCredentialsGrantStorageMockRecorder) DeleteAccessTokenSession(arg0, arg1 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAccessTokenSession", reflect.TypeOf((*MockClientCredentialsGrantStorage)(nil).DeleteAccessTokenSession), arg0, arg1)
}


func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) Authenticate(arg0, arg1, arg2 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Authenticate", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).Authenticate), arg0, arg1, arg2)
}


func (m *MockResourceOwnerPasswordCredentialsGrantStorage) GetAccessTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Session) (fosite.Requester, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetAccessTokenSession", arg0, arg1, arg2)
	ret0, _ := ret[0].(fosite.Requester)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}


func (mr *MockTokenRevocationStorageMockRecorder) CreateAccessTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAccessTokenSession", reflect.TypeOf((*MockTokenRevocationStorage)(nil).CreateAccessTokenSession), arg0, arg1, arg2)
}


func (m *MockTokenRevocationStorage) RevokeRefreshToken(arg0 context.Context, arg1 string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "RevokeRefreshToken", arg0, arg1)
	ret0, _ := ret[0].(error)
	return ret0
}


func (m *MockCoreStorage) InvalidateAuthorizeCodeSession(arg0 context.Context, arg1 string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "InvalidateAuthorizeCodeSession", arg0, arg1)
	ret0, _ := ret[0].(error)
	return ret0
}


func (m *MockCoreStrategy) RefreshTokenSignature(arg0 string) string {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "RefreshTokenSignature", arg0)
	ret0, _ := ret[0].(string)
	return ret0
}


func (m *MockCoreStrategy) AccessTokenSignature(arg0 string) string {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "AccessTokenSignature", arg0)
	ret0, _ := ret[0].(string)
	return ret0
}


func (mr *MockCoreStrategyMockRecorder) AccessTokenSignature(arg0 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AccessTokenSignature", reflect.TypeOf((*MockCoreStrategy)(nil).AccessTokenSignature), arg0)
}


func (m *MockRequester) GetSession() fosite.Session {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetSession")
	ret0, _ := ret[0].(fosite.Session)
	return ret0
}


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
}

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.


func prepareBindMount(m *configs.Mount, rootfs string) error {
	stat, err := os.Stat(m.Source)
	if err != nil {
		// error out if the source of a bind mount does not exist as we will be
		// unable to bind anything to it.
		return err
	}
	// ensure that the destination of the bind mount is resolved of symlinks at mount time because
	// any previous mounts can invalidate the next mount's destination.
	// this can happen when a user specifies mounts within other mounts to cause breakouts or other
	// evil stuff to try to escape the container's rootfs.
	var dest string
	if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {
		return err
	}
	if err := checkProcMount(rootfs, dest, m.Source); err != nil {
		return err
	}
	// update the mount with the correct dest after symlinks are resolved.
	m.Destination = dest
	if err := createIfNotExists(dest, stat.IsDir()); err != nil {
		return err
	}

	return nil
}

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.


func TestAuth(t *testing.T) {
	a, b, err := netPipe()
	if err != nil {
		t.Fatalf("netPipe: %v", err)
	}

	defer a.Close()
	defer b.Close()

	agent, _, cleanup := startAgent(t)
	defer cleanup()

	if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
		t.Errorf("Add: %v", err)
	}

	serverConf := ssh.ServerConfig{}
	serverConf.AddHostKey(testSigners["rsa"])
	serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
		if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
			return nil, nil
		}

		return nil, errors.New("pubkey rejected")
	}

	go func() {
		conn, _, _, err := ssh.NewServerConn(a, &serverConf)
		if err != nil {
			t.Fatalf("Server: %v", err)
		}
		conn.Close()
	}()

	conf := ssh.ClientConfig{}
	conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
	conn, _, _, err := ssh.NewClientConn(b, "", &conf)
	if err != nil {
		t.Fatalf("NewClientConn: %v", err)
	}
	conn.Close()
}


func ExampleRetryableAuthMethod(t *testing.T) {
	user := "testuser"
	NumberOfPrompts := 3

	// Normally this would be a callback that prompts the user to answer the
	// provided questions
	Cb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
		return []string{"answer1", "answer2"}, nil
	}

	config := &ClientConfig{
		User: user,
		Auth: []AuthMethod{
			RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts),
		},
	}

	if err := tryAuth(t, config); err != nil {
		t.Fatalf("unable to dial remote side: %s", err)
	}
}


func TestCheckValid(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	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()

	initConfigSubsystem(ctx, objLayer)

	globalIAMSys.Init(ctx, objLayer, globalEtcdClient, globalNotificationSys, 2*time.Second)

	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(ctx, 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)
	}
}


func NewReader(src io.Reader, size int64, md5Hex, sha256Hex string) (*Reader, error) {
	if _, ok := src.(*Reader); ok {
		return nil, errNestedReader
	}

	sha256sum, err := hex.DecodeString(sha256Hex)
	if err != nil {
		return nil, SHA256Mismatch{}
	}

	md5sum, err := hex.DecodeString(md5Hex)
	if err != nil {
		return nil, BadDigest{}
	}

	var sha256Hash hash.Hash
	if len(sha256sum) != 0 {
		sha256Hash = sha256.New()
	}

	return &Reader{
		md5sum:     md5sum,
		sha256sum:  sha256sum,
		src:        io.LimitReader(src, size),
		size:       size,
		md5Hash:    md5.New(),
		sha256Hash: sha256Hash,
	}, nil
}

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.


func TestDoesPolicySignatureV2Match(t *testing.T) {
	obj, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)
	if err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {
		t.Fatal(err)
	}

	creds := globalActiveCred
	policy := "policy"
	testCases := []struct {
		accessKey string
		policy    string
		signature string
		errCode   APIErrorCode
	}{
		{"invalidAccessKey", policy, calculateSignatureV2(policy, creds.SecretKey), ErrInvalidAccessKeyID},
		{creds.AccessKey, policy, calculateSignatureV2("random", creds.SecretKey), ErrSignatureDoesNotMatch},
		{creds.AccessKey, policy, calculateSignatureV2(policy, creds.SecretKey), ErrNone},
	}
	for i, test := range testCases {
		formValues := make(http.Header)
		formValues.Set("Awsaccesskeyid", test.accessKey)
		formValues.Set("Signature", test.signature)
		formValues.Set("Policy", test.policy)
		errCode := doesPolicySignatureV2Match(formValues)
		if errCode != test.errCode {
			t.Fatalf("(%d) expected to get %s, instead got %s", i+1, niceError(test.errCode), niceError(errCode))
		}
	}
}

The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.


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
		}

		if header.IsDir {
			err = mkdir(filepath.Join(destination, header.Name))
			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(filepath.Join(destination, header.Name)))
		if err != nil {
			return err
		}

		err = writeNewFile(filepath.Join(destination, header.Name), rr, header.Mode())
		if err != nil {
			return err
		}
	}

	return nil
}

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.


		s := strings.Map(func(c rune) rune {
			switch c {
			case ' ', '\t', '\n', '\f', '\r':
				return c
			}
			return -1
		}, p.tok.Data)
		if s != "" {
			p.addText(s)
		}
	case StartTagToken:
		switch p.tok.DataAtom {
		case a.Html:
			return inBodyIM(p)
		case a.Frameset:
			p.addElement()
		case a.Frame:
			p.addElement()
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
		case a.Noframes:
			return inHeadIM(p)
		case a.Template:
			// TODO: remove this divergence from the HTML5 spec.
			//
			// See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
			return inTemplateIM(p)
		}
	case EndTagToken:
		switch p.tok.DataAtom {
		case a.Frameset:
			if p.oe.top().DataAtom != a.Html {
				p.oe.pop()
				if p.oe.top().DataAtom != a.Frameset {
					p.im = afterFramesetIM
					return true
				}
			}
		}
	default:
		// Ignore the token.
	}

A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.


func TestIsLocalHostname(t *testing.T) {
	tests := []struct {
		hostname  string
		allowlist []string
		want      bool
	}{
		{hostname: "localhost", want: true},       // #00
		{hostname: "127.0.0.1", want: true},       // #01
		{hostname: "::1", want: true},             // #02
		{hostname: "0:0:0:0:0:0:0:1", want: true}, // #03
		{hostname: "fuf.me", want: true},          // #04
		{hostname: "127.0.0.95", want: true},      // #05
		{hostname: "0.0.0.0", want: true},         // #06
		{hostname: "192.168.123.45", want: true},  // #07

		{hostname: "gogs.io", want: false},         // #08
		{hostname: "google.com", want: false},      // #09
		{hostname: "165.232.140.255", want: false}, // #10

		{hostname: "192.168.123.45", allowlist: []string{"10.0.0.17"}, want: true}, // #11
		{hostname: "gogs.local", allowlist: []string{"gogs.local"}, want: false},   // #12
	}
	for _, test := range tests {
		t.Run("", func(t *testing.T) {
			assert.Equal(t, test.want, IsLocalHostname(test.hostname, test.allowlist))
		})
	}
}

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.


func isRepositoryGitPath(path string) bool {
	return strings.HasSuffix(path, ".git") ||
		strings.Contains(path, ".git"+string(os.PathSeparator)) ||
		// Windows treats ".git." the same as ".git"
		strings.HasSuffix(path, ".git.") ||
		strings.Contains(path, ".git."+string(os.PathSeparator))
}

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.


func SetProcessPrivileges(target *user.User) error {
	euid := util.AtoiOrPanic(target.Uid)
	egid := util.AtoiOrPanic(target.Gid)
	if os.Geteuid() == euid {
		log.Printf("Privileges already set to %q", target.Username)
		return nil
	}
	log.Printf("Setting privileges to %q", target.Username)

	// If setting privs to root, we want to set the uid first, so we will
	// then have the necessary permissions to perform the other actions.
	if euid == 0 {
		if err := setUids(-1, euid); err != nil {
			return err
		}
	}
	if err := setGids(-1, egid); err != nil {
		return err
	}
	if err := setGroups(target); err != nil {
		return err
	}
	// If not setting privs to root, we want to avoid dropping the uid
	// util the very end.
	if euid != 0 {
		if err := setUids(-1, euid); err != nil {
			return err
		}
	}
	return nil
}


func setGids(rgid, egid int) error {
	res, err := C.my_setregid(C.gid_t(rgid), C.gid_t(egid))
	log.Printf("setregid(%d, %d) = %d (errno %v)", rgid, egid, res, err)
	if res == 0 {
		return nil
	}
	return errors.Wrapf(err.(syscall.Errno), "setting gids")
}


func userKeyringIDLookup(uid int) (int, error) {
	cacheLock.Lock()
	defer cacheLock.Unlock()
	if keyringID, ok := keyringIDCache[uid]; ok {
		return keyringID, nil
	}

	ruid, euid := os.Getuid(), os.Geteuid()
	// If all the ids do not agree, we will have to change them
	needSetUids := uid != ruid || uid != euid

	// The value of KEY_SPEC_USER_KEYRING is determined by the real uid, so
	// we must set the ruid appropriately. Note that this will also trigger
	// the creation of the uid keyring if it does not yet exist.
	if needSetUids {
		defer setUids(ruid, euid) // Always reset privileges
		if err := setUids(uid, 0); err != nil {
			return 0, err
		}
	}
	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 key after our privileges are reset. If we
	// link the key into the process keyring, we will possess it and still
	// be able to use it. However, the permissions to link are based on the
	// effective uid, so we must set the euid appropriately.
	if needSetUids {
		if err := setUids(0, uid); err != nil {
			return 0, err
		}
	}
	if err := keyringLink(keyringID, unix.KEY_SPEC_PROCESS_KEYRING); err != nil {
		return 0, err
	}

	keyringIDCache[uid] = keyringID
	return keyringID, nil
}


func (p *BinaryProtocol) readStringBody(size int32) (value string, err error) {
	if size < 0 {
		return "", nil
	}
	if uint64(size) > p.trans.RemainingBytes() {
		return "", invalidDataLength
	}
	var buf []byte
	if int(size) <= len(p.buffer) {
		buf = p.buffer[0:size]
	} else {
		buf = make([]byte, size)
	}
	_, e := io.ReadFull(p.trans, buf)
	return string(buf), NewProtocolException(e)
}

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.


func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string)) error {
	clusterInfo, err := c.getSyncedCluster(server)
	if err != nil {
		return err
	}
	clusterInfo.IterateHierarchy(key, func(resource *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {
		action(asResourceNode(resource), getApp(resource, namespaceResources))
	})
	return nil
}

The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.


func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct {
	ID          graphql.ID
	Description string
	Query       string
	NotifyOwner bool
	NotifySlack bool
	OrgID       *graphql.ID
	UserID      *graphql.ID
}) (*savedSearchResolver, error) {
	var userID, orgID *int32
	// 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.
	if args.UserID != nil {
		u, err := unmarshalSavedSearchID(*args.UserID)
		if err != nil {
			return nil, err
		}
		userID = &u
		if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, u); err != nil {
			return nil, err
		}
	} else if args.OrgID != nil {
		o, err := unmarshalSavedSearchID(*args.OrgID)
		if err != nil {
			return nil, err
		}
		orgID = &o
		if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, o); err != nil {
			return nil, err
		}
	} else {
		return nil, errors.New("failed to update saved search: no Org ID or User ID associated with saved search")
	}

	id, err := unmarshalSavedSearchID(args.ID)
	if err != nil {
		return nil, err
	}

	if !queryHasPatternType(args.Query) {
		return nil, errMissingPatternType
	}

	ss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{
		ID:          id,
		Description: args.Description,
		Query:       args.Query,
		Notify:      args.NotifyOwner,
		NotifySlack: args.NotifySlack,
		UserID:      userID,
		OrgID:       orgID,
	})
	if err != nil {
		return nil, err
	}

	return r.toSavedSearchResolver(*ss), nil
}


func (voteSet *VoteSet) MakeCommit() *Commit {
	if voteSet.signedMsgType != tmproto.PrecommitType {
		panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType")
	}
	voteSet.mtx.Lock()
	defer voteSet.mtx.Unlock()

	// Make sure we have a 2/3 majority
	if voteSet.maj23 == nil {
		panic("Cannot MakeCommit() unless a blockhash has +2/3")
	}

	// For every validator, get the precommit
	commitSigs := make([]CommitSig, len(voteSet.votes))
	for i, v := range voteSet.votes {
		commitSigs[i] = v.CommitSig()
	}

	return NewCommit(voteSet.GetHeight(), voteSet.GetRound(), *voteSet.maj23, commitSigs)
}

Improper Verification of Cryptographic Signature

The software does not verify, or incorrectly verifies, the cryptographic signature for data.


func (evpool *Pool) flushConsensusBuffer() {
	for _, ev := range evpool.consensusBuffer {
		if err := evpool.addPendingEvidence(ev); err != nil {
			evpool.logger.Error("failed to flush evidence from consensus buffer to pending list: %w", err)
			continue
		}

		evpool.evidenceList.PushBack(ev)
	}
	// reset consensus buffer
	evpool.consensusBuffer = make([]types.Evidence, 0)
}


func TestAddDebug(t *testing.T) {
	err := ErrRevocationClientMismatch.WithDebug("debug")
	assert.NotEqual(t, err, ErrRevocationClientMismatch)
	assert.Empty(t, ErrRevocationClientMismatch.Debug)
	assert.NotEmpty(t, err.Debug)
}

Improper Handling of Exceptional Conditions

The software does not handle or incorrectly handles an exceptional condition.


func (p *Profile) write() (pth string, err error) {
	rootDir, err := utils.GetTempDir()
	if err != nil {
		return
	}

	pth = filepath.Join(rootDir, p.Id)

	_ = os.Remove(pth)
	err = ioutil.WriteFile(pth, []byte(p.Data), os.FileMode(0600))
	if err != nil {
		err = &WriteError{
			errors.Wrap(err, "profile: Failed to write profile"),
		}
		return
	}

	return
}


func (svc *Service) OSVersions(ctx context.Context, teamID *uint, platform *string) (*fleet.OSVersions, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Host{TeamID: teamID}, fleet.ActionList); err != nil {
		return nil, err
	}

	osVersions, err := svc.ds.OSVersions(ctx, teamID, platform)
	if err != nil {
		return nil, err
	}

	return osVersions, nil

}


func (p *GitLabProvider) PrefixAllowedGroups() (groups []string) {

	for _, val := range p.Groups {
		groups = append(groups, fmt.Sprintf("group:%s", val))
	}

	for _, val := range p.Projects {
		groups = append(groups, fmt.Sprintf("project:%s", val.Name))
	}

	return groups
}


func (m *Wilson) 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 ErrIntOverflowCasttype
			}
			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: Wilson: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Wilson: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 0 {
				return fmt.Errorf("proto: wrong wireType = %d for field Int64", wireType)
			}
			var v int64
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return ErrIntOverflowCasttype
				}
				if iNdEx >= l {
					return io.ErrUnexpectedEOF
				}
				b := dAtA[iNdEx]
				iNdEx++
				v |= int64(b&0x7F) << shift
				if b < 0x80 {
					break
				}
			}
			m.Int64 = &v
		default:
			iNdEx = preIndex
			skippy, err := skipCasttype(dAtA[iNdEx:])
			if err != nil {
				return err
			}
			if skippy < 0 {
				return ErrInvalidLengthCasttype
			}
			if (iNdEx + skippy) < 0 {
				return ErrInvalidLengthCasttype
			}
			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
}

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.


func (m *Wilson) 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 ErrIntOverflowCastvalue
			}
			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: Wilson: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Wilson: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 0 {
				return fmt.Errorf("proto: wrong wireType = %d for field Int64", wireType)
			}
			var v int64
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return ErrIntOverflowCastvalue
				}
				if iNdEx >= l {
					return io.ErrUnexpectedEOF
				}
				b := dAtA[iNdEx]
				iNdEx++
				v |= int64(b&0x7F) << shift
				if b < 0x80 {
					break
				}
			}
			m.Int64 = &v
		default:
			iNdEx = preIndex
			skippy, err := skipCastvalue(dAtA[iNdEx:])
			if err != nil {
				return err
			}
			if skippy < 0 {
				return ErrInvalidLengthCastvalue
			}
			if (iNdEx + skippy) < 0 {
				return ErrInvalidLengthCastvalue
			}
			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
}


func (m *Nil) 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: Nil: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Nil: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		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
}


func (m *NonByteCustomType) 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: NonByteCustomType: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: NonByteCustomType: 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
			}
			if m.Field1 == nil {
				m.Field1 = &T{}
			}
			if err := m.Field1.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
}


func (m *E) 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: E: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: E: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		default:
			if (fieldNum >= 1) && (fieldNum < 536870912) {
				var sizeOfWire int
				for {
					sizeOfWire++
					wire >>= 7
					if wire == 0 {
						break
					}
				}
				iNdEx -= sizeOfWire
				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
				}
				github_com_gogo_protobuf_proto.AppendExtension(m, int32(fieldNum), dAtA[iNdEx:iNdEx+skippy])
				iNdEx += skippy
			} else {
				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
}


func (m *C) 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 ErrIntOverflowC
			}
			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: C: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: C: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 2 {
				return fmt.Errorf("proto: wrong wireType = %d for field F2", wireType)
			}
			var msglen int
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return ErrIntOverflowC
				}
				if iNdEx >= l {
					return io.ErrUnexpectedEOF
				}
				b := dAtA[iNdEx]
				iNdEx++
				msglen |= int(b&0x7F) << shift
				if b < 0x80 {
					break
				}
			}
			if msglen < 0 {
				return ErrInvalidLengthC
			}
			postIndex := iNdEx + msglen
			if postIndex < 0 {
				return ErrInvalidLengthC
			}
			if postIndex > l {
				return io.ErrUnexpectedEOF
			}
			if m.F2 == nil {
				m.F2 = &github_com_gogo_protobuf_test_importcustom_issue389_imported.B{}
			}
			if err := m.F2.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
				return err
			}
			iNdEx = postIndex
		default:
			iNdEx = preIndex
			skippy, err := skipC(dAtA[iNdEx:])
			if err != nil {
				return err
			}
			if skippy < 0 {
				return ErrInvalidLengthC
			}
			if (iNdEx + skippy) < 0 {
				return ErrInvalidLengthC
			}
			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
}


func (m *Bar2) 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: Bar2: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Bar2: 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
			}
			s := string(dAtA[iNdEx:postIndex])
			m.Str = &s
			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
}


func (m *FloatingPoint) Unmarshal(dAtA []byte) error {
	l := len(dAtA)
	iNdEx := 0
	for iNdEx < l {
		preIndex := iNdEx
		var wire uint64
		for shift := uint(0); ; shift += 7 {
			if shift >= 64 {
				return ErrIntOverflowTheproto3
			}
			if iNdEx >= l {
				return io.ErrUnexpectedEOF
			}
			b := dAtA[iNdEx]
			iNdEx++
			wire |= uint64(b&0x7F) << shift
			if b < 0x80 {
				break
			}
		}
		fieldNum := int32(wire >> 3)
		wireType := int(wire & 0x7)
		if wireType == 4 {
			return fmt.Errorf("proto: FloatingPoint: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: FloatingPoint: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 1 {
				return fmt.Errorf("proto: wrong wireType = %d for field F", wireType)
			}
			var v uint64
			if (iNdEx + 8) > l {
				return io.ErrUnexpectedEOF
			}
			v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
			iNdEx += 8
			m.F = float64(math.Float64frombits(v))
		default:
			iNdEx = preIndex
			skippy, err := skipTheproto3(dAtA[iNdEx:])
			if err != nil {
				return err
			}
			if skippy < 0 {
				return ErrInvalidLengthTheproto3
			}
			if (iNdEx + skippy) < 0 {
				return ErrInvalidLengthTheproto3
			}
			if (iNdEx + skippy) > l {
				return io.ErrUnexpectedEOF
			}
			m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
			iNdEx += skippy
		}
	}

	if iNdEx > l {
		return io.ErrUnexpectedEOF
	}
	return nil
}


func (m *Int32Value) 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: Int32Value: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Int32Value: 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 |= int32(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
}


func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {
	if !config.Cache.Enabled {
		return nil, false
	}

	item, found := a.tokenCache.Get(token)
	if !found {
		return nil, false
	}

	i := item.(*AuthenticatorOAuth2IntrospectionResult)
	expires := time.Unix(i.Expires, 0)
	if expires.Before(time.Now()) {
		a.tokenCache.Del(token)
		return nil, false
	}

	return i, true
}

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.


func httpProxyValid(proxy *contourv1.HTTPProxy) bool {
	return proxy != nil && proxy.Status.CurrentStatus == "valid"
}

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.


func TestMsgGrantAuthorization(t *testing.T) {
	tests := []struct {
		title            string
		granter, grantee sdk.AccAddress
		authorization    authz.Authorization
		expiration       time.Time
		expectErr        bool
		expectPass       bool
	}{
		{"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil authorization", granter, grantee, nil, time.Now(), true, false},
		{"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true},
		{"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false},
	}
	for i, tc := range tests {
		msg, err := authz.NewMsgGrant(
			tc.granter, tc.grantee, tc.authorization, tc.expiration,
		)
		if !tc.expectErr {
			require.NoError(t, err)
		} else {
			continue
		}
		if tc.expectPass {
			require.NoError(t, msg.ValidateBasic(), "test: %v", i)
		} else {
			require.Error(t, msg.ValidateBasic(), "test: %v", i)
		}
	}
}

Improper Check for Unusual or Exceptional Conditions

The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.


func (x *ConsoleSession) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[15]
	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)
}

According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."


func (*DeleteFriendRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{16}
}


func (x *ListPurchasesRequest) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[28]
	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)
}


func (x *MatchState) ProtoReflect() protoreflect.Message {
	mi := &file_console_proto_msgTypes[31]
	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)
}


func (x *RuntimeInfo_ModuleInfo) Reset() {
	*x = RuntimeInfo_ModuleInfo{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[50]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*UpdateGroupRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{37}
}


func (x *UnlinkDeviceRequest) Reset() {
	*x = UnlinkDeviceRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[35]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *StatusList_Status) Reset() {
	*x = StatusList_Status{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[49]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*DeleteStorageObjectRequest) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{21}
}


func (x *StorageList) Reset() {
	*x = StorageList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[33]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *StatusList) Reset() {
	*x = StatusList{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[40]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (x *WalletLedger) Reset() {
	*x = WalletLedger{}
	if protoimpl.UnsafeEnabled {
		mi := &file_console_proto_msgTypes[42]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}


func (*CallApiEndpointResponse) Descriptor() ([]byte, []int) {
	return file_console_proto_rawDescGZIP(), []int{13}
}


func main() {
	hostPtr := flag.String("host", "localhost:9159", "the hostname that the server should listen on.")
	tokenPtr := flag.String("token", "", "the Proxy Access Token used to restrict access to the server.")
	allowedOriginsPtr := flag.String("allowed-origins", "*", "a comma separated list of allowed origins.")
	bannedOutputsPtr := flag.String("banned-outputs", "", "a comma separated list of banned outputs.")
	flag.Parse()

	finished := make(chan bool)
	libproxy.Initialize(*tokenPtr, *hostPtr, *allowedOriginsPtr, *bannedOutputsPtr, onProxyStateChangeServer, false, finished)

	<-finished
}


func PartitionMessage(input string, limits t.MessageLimit, distance int) (items []t.MessageItem, omitted int) {
	runes := []rune(input)
	chunkOffset := 0
	maxTotal := Min(len(runes), limits.TotalChunkSize)
	maxCount := limits.ChunkCount - 1

	for i := 0; i < maxCount; i++ {
		// If no suitable split point is found, use the chunkSize
		chunkEnd := chunkOffset + limits.ChunkSize
		// ... and start next chunk directly after this one
		nextChunkStart := chunkEnd
		if chunkEnd > maxTotal {
			// The chunk is smaller than the limit, no need to search
			chunkEnd = maxTotal
			nextChunkStart = maxTotal
		} else {
			for r := 0; r < distance; r++ {
				rp := chunkEnd - r
				if runes[rp] == '\n' || runes[rp] == ' ' {
					// Suitable split point found
					chunkEnd = rp
					// Since the split is on a whitespace, skip it in the next chunk
					nextChunkStart = chunkEnd + 1
					break
				}
			}
		}

		items = append(items, t.MessageItem{
			Text: string(runes[chunkOffset:chunkEnd]),
		})

		chunkOffset = nextChunkStart
		if chunkOffset >= maxTotal {
			break
		}
	}

	return items, len(runes) - chunkOffset
}


func (e ErrLatestSnapshot) Error() string {
	return fmt.Sprintf("tuf: the local snapshot version (%d) is the latest", e.Version)
}

Improper Validation of Integrity Check Value

The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.


func handleConnect(config *Config, pctx *goproxy.ProxyCtx) error {
	sctx := pctx.UserData.(*smokescreenContext)

	// Check if requesting role is allowed to talk to remote
	sctx.decision, sctx.lookupTime, pctx.Error = checkIfRequestShouldBeProxied(config, pctx.Req, pctx.Req.Host)
	if pctx.Error != nil {
		return pctx.Error
	}
	if !sctx.decision.allow {
		return denyError{errors.New(sctx.decision.reason)}
	}

	return nil
}


func (u *SessionUtil) changeModeOfSudoersFile(log log.T) error {
	fileMode := os.FileMode(sudoersFileMode)
	if err := os.Chmod(sudoersFile, fileMode); err != nil {
		log.Errorf("Failed to change mode of %s to %d: %v", sudoersFile, sudoersFileMode, err)
		return err
	}
	log.Infof("Successfully changed mode of %s to %d", sudoersFile, sudoersFileMode)
	return nil
}


func newMockResourceServer(t testing.TB) ResourceServer {
	ctx := context.Background()
	dummy := ""
	serverURL := &dummy
	hf := func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/.well-known/oauth-authorization-server" {
			w.Header().Set("Content-Type", "application/json")
			_, err := io.WriteString(w, strings.ReplaceAll(`{
				"issuer": "https://dev-14186422.okta.com",
				"authorization_endpoint": "https://example.com/auth",
				"token_endpoint": "https://example.com/token",
				"jwks_uri": "URL/keys",
				"id_token_signing_alg_values_supported": ["RS256"]
			}`, "URL", *serverURL))

			if !assert.NoError(t, err) {
				t.FailNow()
			}

			return
		} else if r.URL.Path == "/keys" {
			keys := jwk.NewSet()
			raw, err := json.Marshal(keys)
			if err != nil {
				http.Error(w, err.Error(), 400)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_, err = io.WriteString(w, string(raw))

			if !assert.NoError(t, err) {
				t.FailNow()
			}
		}

		http.NotFound(w, r)
	}

	s := httptest.NewServer(http.HandlerFunc(hf))
	defer s.Close()

	*serverURL = s.URL

	http.DefaultClient = s.Client()

	r, err := NewOAuth2ResourceServer(ctx, authConfig.ExternalAuthorizationServer{
		BaseURL: stdlibConfig.URL{URL: *config.MustParseURL(s.URL)},
	}, stdlibConfig.URL{})
	if !assert.NoError(t, err) {
		t.FailNow()
	}

	return r
}


    function copyAndExtractDriver(buf)
    {
        var file = fs.openSync( INSTALLER_FILE, 'w');
        var len = fs.writeSync( file, buf, 0, buf.length, 0 );
        if( len != buf.length )
        {
            console.log( "Error writing IBM ODBC and CLI Driver to a file" );
            process.exit(1);
        }
        fs.closeSync( file );
        if(platform == 'win32')
        {
            readStream = fs.createReadStream(INSTALLER_FILE);
            writeStream = fstream.Writer(DOWNLOAD_DIR);

            readStream.pipe(unzip.Parse()).pipe(writeStream);
            console.log('Download and extraction of DB2 ODBC ' +
                        'CLI Driver completed successfully ...');
            console.log(license_agreement);
        }
        else
        {
            var targz = require('targz');
            var compress = targz.decompress({src: INSTALLER_FILE, dest: DOWNLOAD_DIR}, function(err){
              if(err) {
                console.log(err);
                process.exit(1);
              }
              else {
                console.log('Download and extraction of DB2 ODBC ' +
                            'CLI Driver completed successfully ...');
                console.log(license_agreement);
                IBM_DB_HOME = path.resolve(DOWNLOAD_DIR, 'clidriver');
                process.env.IBM_DB_HOME = IBM_DB_HOME.replace(/\s/g,'\\ ');
                buildBinary(true);
                removeWinBuildArchive();
              }
	        });
        }
    }

Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.


scroll_to_bottom_key_html: common.has_mac_keyboard()
                ? "Fn + →"
                : "End",
        }),
    );
    $(`.enter_sends_${user_settings.enter_sends}`).show();
    common.adjust_mac_shortcuts(".enter_sends kbd");
}

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


    from: { name: globalDb.getServerTitle(), address: db.getReturnAddress() },
    subject: subject,
    text: text,
  };

  sendEmail(sendOptions);
};

When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.


  message() {
    const instance = Template.instance();
    return instance.formState.get().message;
  },


  restoreDisabled() {
    const instance = Template.instance();
    return instance.ipBlacklist.get() === DEFAULT_IP_BLACKLIST;
  },


  hasError() {
    const instance = Template.instance();
    return instance.formState.get().state === "error";
  },


  "submit .admin-networking"(evt) {
    evt.preventDefault();
    evt.stopPropagation();
  },


function parseCidr(cidr) {
  // Given a CIDR-format network specification, return a function which, given an address string,
  // returns true if the address is in this network.

  // The "ip" NPM module's CIDR handling unfortunately is very broken for IPv6. Many bugs have been
  // filed but it remains broken.

  try {
    cidr = cidr.trim();
    if (cidr === "") return null;

    const parts = cidr.split('/');
    if (parts.length === 1) {
      // Bare address.
      return addr => Ip.isEqual(cidr, addr);
    } else if (parts.length === 2) {
      const bits = parseInt(parts[1], 10);
      if (bits !== bits) throw new Error("value after slash must be an integer");
      const network = getNetwork(parts[0], bits);
      return addr => {
        return network.equals(getNetwork(addr, bits));
      };
    } else {
      throw new Error("too many slashes");
    }
  } catch (err) {
    console.error("invalid network specification in IP blacklist:", cidr, err);
    return null;
  }
}


        session: new Capnp.Capability(new ExternalWebSession(this.url, options, globalDb),
                                      ApiSession)
      };


              servername: safe.host.split(":")[0],
            });

      request.on("response", this.wrapCallback((response) => {
        if ("content-length" in response.headers) {
          bytesExpected = parseInt(response.headers["content-length"]);
        }
      }));

      request.on("data", this.wrapCallback((chunk) => {
        hasher.update(chunk);
        out.write(chunk);
        bytesReceived += chunk.length;
        updateDownloadProgress();
      }));

      request.on("end", this.wrapCallback(() => {
        out.done();

        if (hasher.digest("hex").slice(0, 32) !== this.packageId) {
          throw new Error("Package hash did not match.");
        }

        done = true;
        delete this.downloadRequest;

        this.updateProgress("unpack");
        out.saveAs(this.packageId).then(this.wrapCallback((info) => {
          this.appId = info.appId;
          this.authorPgpKeyFingerprint = info.authorPgpKeyFingerprint;
          this.done(info.manifest);
        }), this.wrapCallback((err) => {
          throw err;
        }));
      }));

      request.on("error", this.wrapCallback((err) => { throw err; }));

      this.downloadRequest = request;
    }));


export async function formParse(req: any): Promise<FormParseResult> {
	// It's not clear how to get mocked requests to be parsed successfully by
	// formidable so we use this small hack. If it's mocked, we are running test
	// units and the request body is already an object and can be returned.
	if (req.__isMocked) {
		const output: any = {};
		if (req.files) output.files = req.files;
		output.fields = req.body || {};
		return output;
	}

	if (req.__parsed) return req.__parsed;

	// Note that for Formidable to work, the content-type must be set in the
	// headers
	return new Promise((resolve: Function, reject: Function) => {
		const form = formidable({ multiples: true });
		form.parse(req, (error: any, fields: any, files: any) => {
			if (error) {
				reject(error);
				return;
			}

			// Formidable seems to be doing some black magic and once a request
			// has been parsed it cannot be parsed again. Doing so will do
			// nothing, the code will just end there, or maybe wait
			// indefinitely. So we cache the result on success and return it if
			// some code somewhere tries again to parse the form.
			req.__parsed = { fields, files };
			resolve(req.__parsed);
		});
	});
}

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.


func cssGogsMinCss() (*asset, error) {
	bytes, err := cssGogsMinCssBytes()
	if err != nil {
		return nil, err
	}

	info := bindataFileInfo{name: "css/gogs.min.css", size: 64378, mode: os.FileMode(0644), modTime: time.Unix(1584215361, 0)}
	a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xd9, 0x49, 0xa9, 0x99, 0x79, 0x58, 0x26, 0xec, 0xaa, 0x9, 0x5a, 0x24, 0x6, 0x69, 0x2e, 0xe0, 0x3a, 0xb1, 0x53, 0xc4, 0x42, 0x72, 0x4d, 0xe0, 0x67, 0x6d, 0xae, 0x6c, 0x8f, 0xc4, 0x27, 0x27}}
	return a, nil
}

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.


TEST_F(AsStringGraphTest, Int8) {
  TF_ASSERT_OK(Init(DT_INT8));

  AddInputFromArray<int8>(TensorShape({3}), {-42, 0, 42});
  TF_ASSERT_OK(RunOpKernel());
  Tensor expected(allocator(), DT_STRING, TensorShape({3}));
  test::FillValues<tstring>(&expected, {"-42", "0", "42"});
  test::ExpectTensorEqual<tstring>(expected, *GetOutput(0));
}

Use of Externally-Controlled Format String

The software uses a function that accepts a format string as an argument, but the format string originates from an external source.


TEST_F(AsStringGraphTest, NoPrecisionForNonFloat) {
  Status s = Init(DT_INT32, /*fill=*/"", /*width=*/-1, /*precision=*/5);
  ASSERT_EQ(error::INVALID_ARGUMENT, s.code());
  ASSERT_TRUE(absl::StrContains(s.error_message(),
                                "precision not supported for datatype"));
}


TEST_F(AsStringGraphTest, FloatPrecisionOnly) {
  TF_ASSERT_OK(Init(DT_FLOAT, /*fill=*/"", /*width=*/-1, /*precision=*/2));

  AddInputFromArray<float>(TensorShape({4}), {-42, 0, 3.14159, 42});
  TF_ASSERT_OK(RunOpKernel());
  Tensor expected(allocator(), DT_STRING, TensorShape({4}));
  test::FillValues<tstring>(&expected, {"-42.00", "0.00", "3.14", "42.00"});
  test::ExpectTensorEqual<tstring>(expected, *GetOutput(0));
}


TEST_F(AsStringGraphTest, NoShortestForNonFloat) {
  Status s = Init(DT_INT32, /*fill=*/"", /*width=*/-1, /*precision=*/-1,
                  /*scientific=*/false, /*shortest=*/true);
  ASSERT_EQ(error::INVALID_ARGUMENT, s.code());
  ASSERT_TRUE(absl::StrContains(
      s.error_message(),
      "scientific and shortest format not supported for datatype"));
}


TEST_F(AsStringGraphTest, FillWithSpace) {
  TF_ASSERT_OK(Init(DT_INT64, /*fill=*/" ", /*width=*/4));

  AddInputFromArray<int64>(TensorShape({3}), {-42, 0, 42});
  TF_ASSERT_OK(RunOpKernel());
  Tensor expected(allocator(), DT_STRING, TensorShape({3}));
  test::FillValues<tstring>(&expected, {" -42", "   0", "  42"});
  test::ExpectTensorEqual<tstring>(expected, *GetOutput(0));
}


    public static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {
        // # Parse data as unsigned-big-endian encoded integer.
        // # For empty data different possibilities may occur:
        // #      minByteLen <= 0 : return 0
        // #      raise_on_Null == False and minByteLen > 0: return None
        // #      raise_on_Null == True and minByteLen > 0:  raise SlpInvalidOutputMessage
        if (intBytes.length >= minByteLen && intBytes.length <= maxByteLen) {
            return intBytes.readUIntBE(0, intBytes.length)
        }
        if (intBytes.length === 0 && !raise_on_Null) {
            return null;
        }
        throw Error("Field has wrong length");
    }

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.


    public static buildGenesisOpReturn(config: configBuildGenesisOpReturn, type = 0x01) {
        let hash;
        try {
            hash = config.hash!.toString("hex");
        } catch (_) { hash = null; }

        return SlpTokenType1.buildGenesisOpReturn(
            config.ticker,
            config.name,
            config.documentUri,
            hash,
            config.decimals,
            config.batonVout,
            config.initialQuantity,
            type,
        );
    }


  verifyEmail(req) {
    const { username, token: rawToken } = req.query;
    const token =
      rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken;

    const appId = req.params.appId;
    const config = Config.get(appId);

    if (!config) {
      this.invalidRequest();
    }

    if (!config.publicServerURL) {
      return this.missingPublicServerURL();
    }

    if (!token || !username) {
      return this.invalidLink(req);
    }

    const userController = config.userController;
    return userController.verifyEmail(username, token).then(
      () => {
        const params = qs.stringify({ username });
        return Promise.resolve({
          status: 302,
          location: `${config.verifyEmailSuccessURL}?${params}`,
        });
      },
      () => {
        return this.invalidVerificationLink(req);
      }
    );
  }


                      'X-Parse-Session-Token': user1.getSessionToken(),
                    },
                  },
                });

                let foundGraphQLClassReadPreference = false;
                let foundUserClassReadPreference = false;
                databaseAdapter.database.serverConfig.cursor.calls
                  .all()
                  .forEach(call => {
                    if (
                      call.args[0].ns.collection.indexOf('GraphQLClass') >= 0
                    ) {
                      foundGraphQLClassReadPreference = true;
                      expect(call.args[0].options.readPreference.mode).toBe(
                        ReadPreference.PRIMARY
                      );
                    } else if (
                      call.args[0].ns.collection.indexOf('_User') >= 0
                    ) {
                      foundUserClassReadPreference = true;
                      expect(call.args[0].options.readPreference.mode).toBe(
                        ReadPreference.PRIMARY
                      );
                    }
                  });

                expect(foundGraphQLClassReadPreference).toBe(true);
                expect(foundUserClassReadPreference).toBe(true);
              } catch (e) {
                handleError(e);
              }
            });


function main() {
  try {
    let tag = process.env.GITHUB_REF;
    if (core.getInput('tag')) {
      tag = `refs/tags/${core.getInput('tag')}`;
    }

    exec(
      `git for-each-ref --format='%(contents)' '${escapeShellArg(tag)}'`,
      (err, stdout) => {
        if (err) {
          core.setFailed(err);
        } else {
          core.setOutput('git-tag-annotation', stdout);
        }
      },
    );
  } catch (error) {
    core.setFailed(error.message);
  }
}

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.


function timingSafeEquals(a, b) {
  if (a.length !== b.length) {
    timingSafeEqual(a, a);
    return false;
  }
  return timingSafeEqual(a, b);
}


  function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) {
    return {
      sslName,
      blockLen,
      keyLen,
      ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM)
              ? ivLen
              : blockLen),
      authLen,
      discardLen,
      stream: !!(flags & CIPHER_STREAM),
    };
  }


function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) {
  this.type = type;
  this.comment = comment;
  this[SYM_PRIV_PEM] = null;
  this[SYM_PUB_PEM] = pubPEM;
  this[SYM_PUB_SSH] = pubSSH;
  this[SYM_HASH_ALGO] = algo;
  this[SYM_DECRYPTED] = false;
}


  getPublicSSH: function getPublicSSH() {
    return this[SYM_PUB_SSH];
  },


  finalize(packet, force) {
    return packet;
  }


  finalize(payload, force) {
    if (this._protocol._kexinit === undefined || force) {
      const output = this._zlib.writeSync(payload, true);
      const packet = this._protocol._cipher.allocPacket(output.totalLen);
      if (output.push === undefined) {
        packet.set(output, 5);
      } else {
        for (let i = 0, p = 5; i < output.length; ++i) {
          const chunk = output[i];
          packet.set(chunk, p);
          p += chunk.length;
        }
      }
      return packet;
    }
    return payload;
  }


function processCallback() {
  throw new Error('Should not get here');
}


      function reinit() {
        if (testConfig.cipher === null) {
          cipher = new NullCipher(1, onCipherData);
          decipher = new NullDecipher(1, onDecipherPayload);
        } else {
          cipher = createCipher(config);
          decipher = createDecipher(config);
        }
      }


function generate(target, hierarchies, forceOverride) {
    let current = target;
    hierarchies.forEach(info => {
        const descriptor = normalizeDescriptor(info);
        const { value, type, create, override, created, skipped, got } = descriptor;
        const name = getNonEmptyPropName(current, descriptor);
        if (forceOverride ||
            override ||
            !current[name] ||
            typeof current[name] !== 'object' ||
            (name === propProto && current[name] === Object.prototype)) {
            const obj = value ? value :
                type ? new type() :
                    create ? create.call(current, current, name) :
                        {};
            current[name] = obj;
            if (created) {
                created.call(current, current, name, obj);
            }
        }
        else {
            if (skipped) {
                skipped.call(current, current, name, current[name]);
            }
        }
        const parent = current;
        current = current[name];
        if (got) {
            got.call(parent, parent, name, current);
        }
    });
    return current;
}

Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')

The software receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.


function add(obj, str, val) {
    "use strict";
    try {
        if (typeof str !== "string") {
            return;
        }
        if (str.indexOf('__proto__') != -1) {
            throw "cannot modify prototype property";
        }
        if (typeof obj !== "object") {
            return;
        }
        if (!val) {
            return;
        }
        var items = str.split('.');
        console.log(str);
        var initial = items.slice(0, items.length - 1);
        var last = items.slice(items.length - 1);
        var test = initial.reduce(indexTrue, obj);
        test[last] = val;

    } catch (ex) {
        console.error(ex);
        return;
    }
}

Improperly Controlled Modification of Dynamically-Determined Object Attributes

The software receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.


function reduce(obj, str) {
    "use strict";
    try {
        if (typeof str !== "string") {
            return;
        }
        if (typeof obj !== "object") {
            return;
        }
        return str.split('.').reduce(indexFalse, obj);

    } catch (ex) {
        console.error(ex);
        return;
    }

}


function methodByPath(target, path) {
  path = pathToArray(path);

  const values = breadcrumbs(target, path);

  if (values.length < path.length) {
    return noop;
  }

  if (typeof values[values.length - 1] !== 'function') {
    return noop;
  }

  if (values.length > 1) {
    return values[values.length - 1].bind(values[values.length - 2]);
  }
  else {
    return values[0].bind(null);
  }
}


const getHomeDir = (): string => {
  const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep}` } = process.env;

  if (HOME) return HOME;
  if (USERPROFILE) return USERPROFILE;
  if (HOMEPATH) return `${HOMEDRIVE}${HOMEPATH}`;

  return homedir();
};


		([ key, value ]) => ({ [key]: spawn.bind(null, value) }),
	),


module.exports = async function(path) {
	if (!path || typeof path !== 'string') {
		throw new TypeError(`string was expected, instead got ${path}`);
	}

	const absolute = resolve(path);

	if (!(await exist(absolute))) {
		throw new Error(`Could not find file at path "${absolute}"`);
	}

	const ts = await spawn(`log -1 --format="%at" -- ${path}`);

	return new Date(Number(ts) * 1000);
};


export declare function applyCommandArgs(configuration: any, argv: string[]): void;
export declare function setDeepProperty(obj: {


function setDeepProperty(obj, propertyPath, value) {
    if (!obj) {
        throw new Error("Invalid object");
    }
    if (!propertyPath) {
        throw new Error("Invalid property path");
    }
    const pathParts = splitPath(propertyPath);
    const pathPartsLen = pathParts.length;
    for (let i = 0; i < pathPartsLen - 1; i++) {
        const pathPart = pathParts[i];
        if (!(pathPart in obj)) {
            setProp(obj, pathPart, {});
        }
        obj = getProp(obj, pathPart);
    }
    setProp(obj, pathParts[pathPartsLen - 1], value);
    return;
}


    constructor(env) {
        this.section1 = new Section1Config();
        this.webServer = new WebServerConfig();
        if (!env) {
            env = process.env;
        }
        // Enable config file
        if (env.config) {
            const configFile = path.resolve(process.cwd(), env.config);
            confinit.applyConfigFile(this, configFile);
        }
        // Enable environment variables
        confinit.applyEnvVariables(this, process.env, "cfg_");
        // Enable command arguments
        confinit.applyCommandArgs(this, process.argv);
        confinit.validate(this);
    }


const set = (obj, path, val, options = {}) => {
	let internalPath = path,
		objPart;

	options = {
		"transformRead": returnWhatWasGiven,
		"transformKey": returnWhatWasGiven,
		"transformWrite": returnWhatWasGiven,
		...options
	};

	// No object data
	if (obj === undefined || obj === null) {
		return;
	}

	// No path string
	if (!internalPath) {
		return;
	}

	internalPath = clean(internalPath);

	// Path is not a string, throw error
	if (typeof internalPath !== "string") {
		throw new Error("Path argument must be a string");
	}

	if (typeof obj !== "object") {
		return;
	}

	// Path has no dot-notation, set key/value
	if (isNonCompositePath(internalPath)) {
		// Do not allow prototype pollution
		if (internalPath === "__proto__") return obj;

		obj = decouple(obj, options);
		obj[options.transformKey(unEscape(internalPath))] = val;
		return obj;
	}

	const newObj = decouple(obj, options);
	const pathParts = split(internalPath);
	const pathPart = pathParts.shift();
	const transformedPathPart = options.transformKey(pathPart);

	// Do not allow prototype pollution
	if (transformedPathPart === "__proto__") return obj;

	let childPart = newObj[transformedPathPart];

	if (typeof childPart !== "object") {
		// Create an object or array on the path
		if (String(parseInt(transformedPathPart, 10)) === transformedPathPart) {
			// This is an array index
			newObj[transformedPathPart] = [];
		} else {
			newObj[transformedPathPart] = {};
		}

		objPart = newObj[transformedPathPart];
	} else {
		objPart = childPart;
	}

	return set(newObj, transformedPathPart, set(objPart, pathParts.join('.'), val, options), options);
};


export function deepExtend(target: unknown, source: unknown): unknown {
  if (!(source instanceof Object)) {
    return source;
  }

  switch (source.constructor) {
    case Date:
      // Treat Dates like scalars; if the target date object had any child
      // properties - they will be lost!
      const dateValue = source as Date;
      return new Date(dateValue.getTime());

    case Object:
      if (target === undefined) {
        target = {};
      }
      break;
    case Array:
      // Always copy the array source and overwrite the target.
      target = [];
      break;

    default:
      // Not a plain Object - treat it as a scalar.
      return source;
  }

  for (const prop in source) {
    // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
    if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
      continue;
    }
    (target as Record<string, unknown>)[prop] = deepExtend(
      (target as Record<string, unknown>)[prop],
      (source as Record<string, unknown>)[prop]
    );
  }

  return target;
}


async function processRequest (t, frontendURL, path, expected) {
  const url = new URL(path, frontendURL)
  t.comment('ws connecting to ' + url.toString())
  const ws = new WebSocket(url)
  let wsResult, gotResult

  try {
    await once(ws, 'open')
    t.pass('socket connected')

    const [buf] = await Promise.race([once(ws, 'message'), once(ws, 'close')])
    if (buf instanceof Buffer) {
      wsResult = buf.toString()
    } else {
      t.comment('websocket closed')
      wsResult = 'error'
    }
  } catch (e) {
    wsResult = 'error'
    ws.terminate()
  }

  try {
    const result = await got(url)
    gotResult = result.body
  } catch (e) {
    gotResult = 'error'
  }

  t.is(wsResult, expected)
  t.is(gotResult, expected)
}


return { session: new Capnp.Capability(new ExternalWebSession(this.url, options), ApiSession) };

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.


  void addPathParam(String name, String value, boolean encoded) {
    if (relativeUrl == null) {
      // The relative URL is cleared when the first query parameter is set.
      throw new AssertionError();
    }
    relativeUrl = relativeUrl.replace("{" + name + "}", canonicalizeForPath(value, encoded));
  }

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.


search.stats = function(files) {
												if(files.length) {
													var file = files.shift();
													fs.stat(relativePath + '/' + file, function(err, stats) {
														if(err) { writeError(err); }
														else {
															stats.name = file;
															stats.isFile = stats.isFile();
															stats.isDirectory = stats.isDirectory();
															stats.isBlockDevice = stats.isBlockDevice();
															stats.isFIFO = stats.isFIFO();
															stats.isSocket = stats.isSocket();
															results.push(stats);
															search.stats(files);
														}
													});
												} else {
													if(query.type == 'json' || query.dir == 'json') {
														res.setHeader('Content-Type', 'application/json');
														res.write(JSON.stringify(results));
														res.end();
													} else {
														res.setHeader('Content-Type', 'text/html');
														res.write('');
														for(var f = 0; f < results.length; f++) {
															var name = results[f].name;
															var normalized = url + '/' + name;
															while(normalized[0] == '/') { normalized = normalized.slice(1, normalized.length); }
															res.write('\r\n
' + name + '
');
														}
														res.end('\r\n');
													}
												}
											};


          get: (path) => {
            useCount++;
            expect(path).toEqual('somepath');
          },
        })
      ).not.toThrow();
      expect(useCount).toBeGreaterThan(0);
    });

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.


) => {
  if (!info || !info.sessionToken) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  }
  const sessionToken = info.sessionToken;
  const selectedFields = getFieldNames(queryInfo)
    .filter(field => field.startsWith(keysPrefix))
    .map(field => field.replace(keysPrefix, ''));

  const keysAndInclude = extractKeysAndInclude(selectedFields);
  const { keys } = keysAndInclude;
  let { include } = keysAndInclude;

  if (validatedToken && !keys && !include) {
    return {
      sessionToken,
    };
  } else if (keys && !include) {
    include = 'user';
  }

  const options = {};
  if (keys) {
    options.keys = keys
      .split(',')
      .map(key => `user.${key}`)
      .join(',');
  }
  if (include) {
    options.include = include
      .split(',')
      .map(included => `user.${included}`)
      .join(',');
  }

  const response = await rest.find(
    config,
    Auth.master(config),
    '_Session',
    { sessionToken },
    options,
    info.clientVersion,
    info.context,
  );
  if (
    !response.results ||
    response.results.length == 0 ||
    !response.results[0].user
  ) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  } else {
    const user = response.results[0].user;
    return {
      sessionToken,
      user,
    };
  }
};


function generate(target, hierarchies, forceOverride) {
    let current = target;
    hierarchies.forEach(info => {
        const descriptor = normalizeDescriptor(info);
        const { value, type, create, override, created, skipped, got } = descriptor;
        const name = getNonEmptyPropName(current, descriptor);
        if (forceOverride || override || !current[name] || typeof current[name] !== 'object') {
            const obj = value ? value :
                type ? new type() :
                    create ? create.call(current, current, name) :
                        {};
            current[name] = obj;
            if (created) {
                created.call(current, current, name, obj);
            }
        }
        else {
            if (skipped) {
                skipped.call(current, current, name, current[name]);
            }
        }
        const parent = current;
        current = current[name];
        if (got) {
            got.call(parent, parent, name, current);
        }
    });
    return current;
}


function add(obj, str, val) {
    "use strict";
    try {
        if ( typeof str !== "string") {
            return;
        }
        if ( typeof obj !== "object") {
            return;
        }
        if (!val) {
            return;
        }
        var items = str.split('.');
        var initial = items.slice(0, items.length - 1);
        var last = items.slice(items.length - 1);
        var test = initial.reduce(indexTrue, obj);
        test[last] = val;
    } catch(ex) {
        console.error(ex);
        return;
    }
}


function callByPath(target, path, args) {
  var fn = methodByPath(target, path);
  if (! fn) {
    return;
  }

  return fn.apply(null, args);
}


                message: new MockBuilder(
                    {
                        from: 'test@valid.sender',
                        to: 'test@valid.recipient'
                    },
                    'message\r\nline 2'
                )
            },
            function(err, data) {
                expect(err).to.not.exist;
                expect(data.messageId).to.equal('<test>');
                expect(output).to.equal('message\nline 2');
                client._spawn.restore();
                done();
            }
        );
    });

Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')

The software constructs a string for a command to executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string.


export function loadEmailAddressesAndLoginMethods(userId: UserId, success: UserAcctRespHandler) {
  get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
    success(response);
  });
}


export function store_isFeatFlagOn(store: Store, featureFlag: St): Bo {
  return _.includes(store.siteFeatureFlags, featureFlag) ||
         _.includes(store.serverFeatureFlags, featureFlag);
}


async function logPlatform(logger: Logger): Promise<void> {
	const os = require('os');
    let platform = os.platform();
    logger.log(`OS is ${platform}`);
	if (platform === 'darwin' || platform === 'win32') {
		return;
	}

    const osInfo = require('linux-os-info');
    const result = await osInfo();
    const dist = result.id;
    logger.log(`dist: ${dist}`);
}


			.then((promiseResult) => {
				// This promise resolver simply swallows the result of Promise.all.
				// When we decide we want to expose this level of detail
				// to other extensions then we will design that return type and implement it here.
			}),


module.exports = (yargs) => {
    yargs.command('exec <container name> [commands...]', 'Execute command in docker container', () => {}, async (argv) => {
        const containers = docker.getContainers();
        const services = Object.keys(containers);

        if (services.includes(argv.containername) || services.some((service) => service.includes(argv.containername))) {
            const container = containers[argv.containername]
                ? containers[argv.containername]
                : Object.entries(containers).find(([key]) => key.includes(argv.containername))[1];

            if (argv.commands.length === 0) {
                // if we have default connect command then use it
                if (container.connectCommand) {
                    // eslint-disable-next-line no-param-reassign
                    argv.commands = container.connectCommand;
                } else {
                    // otherwise fall back to bash (if it exists inside container)
                    argv.commands.push('bash');
                }
            }
            await executeInContainer({
                containerName: container.name,
                commands: argv.commands
            });

            return;
        }

        logger.error(`No container found "${argv.containername}"`);
    });
};

Always-Incorrect Control Flow Implementation

The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.


export default function handleLoginFactory(handler: BaseHandleLogin, nextConfig: NextConfig): HandleLogin {
  return async (req, res, options = {}): Promise<void> => {
    try {
      assertReqRes(req, res);
      if (req.query.returnTo) {
        const returnTo = Array.isArray(req.query.returnTo) ? req.query.returnTo[0] : req.query.returnTo;

        if (!isSafeRedirect(returnTo)) {
          throw new Error('Invalid value provided for returnTo, must be a relative url');
        }

        options = { ...options, returnTo };
      }
      if (nextConfig.organization) {
        options = {
          ...options,
          authorizationParams: { organization: nextConfig.organization, ...options.authorizationParams }
        };
      }

      return await handler(req, res, options);
    } catch (e) {
      throw new HandlerError(e);
    }
  };
}

URL Redirection to Untrusted Site ('Open Redirect')

A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.


    return `[${renderType(type.ofType)}]`;
  }
  return `<a class="typeName">${type.name}</a>`;
}


  ): void => {
    const name = createElement('h2', CLASS_CATEGORY_NAME);
    name.innerHTML =
      this.i18n.categories[category] || defaultI18n.categories[category];
    this.emojis.appendChild(name);
    this.headers.push(name);

    this.emojis.appendChild(
      new EmojiContainer(
        emojis,
        true,
        this.events,
        this.options,
        category !== 'recents'
      ).render()
    );
  };


function detailedDataTableMapper(entry) {
  const project = Projects.findOne({ _id: entry.projectId })
  const mapping = [project ? project.name : '',
    dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
    entry.task,
    projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : '']
  if (getGlobalSetting('showCustomFieldsInDetails')) {
    if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
        mapping.push(entry[customfield[customFieldType]])
      }
    }
    if (CustomFields.find({ classname: 'project' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
        mapping.push(project[customfield[customFieldType]])
      }
    }
  }
  if (getGlobalSetting('showCustomerInDetails')) {
    mapping.push(project ? project.customer : '')
  }
  if (getGlobalSetting('useState')) {
    mapping.push(entry.state)
  }
  mapping.push(Number(timeInUserUnit(entry.hours)))
  mapping.push(entry._id)
  return mapping
}


        const errorHandler = (err: Error) => {
            this._cancel_wait_for_open_secure_channel_request_timeout();

            this.messageBuilder.removeListener("message", messageHandler);
            this.close(() => {
                callback(new Error("/Expecting OpenSecureChannelRequest to be valid " + err.message));
            });
        };

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.


    constructor() {
        super();

        this.name = this.constructor.name + counter;
        counter += 1;

        this._timerId = null;
        this._timeout = 30000; // 30 seconds timeout
        this._socket = null;
        this.headerSize = 8;
        this.protocolVersion = 0;

        this._disconnecting = false;
        this._pendingBuffer = undefined;

        this.bytesWritten = 0;
        this.bytesRead = 0;

        this._theCallback = undefined;
        this.chunkWrittenCount = 0;
        this.chunkReadCount = 0;

        this._onSocketClosedHasBeenCalled = false;
        this._onSocketEndedHasBeenCalled = false;
        TCP_transport.registry.register(this);
    }


function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
    const response = new ResponseClass({
        responseHeader: { serviceResult: statusCode }
    });
    return channel.send_response("MSG", response, message);
}


template() {
    const { pfx, model, config } = this;
    const label = model.get('label') || '';

    return `

      ${label}

        ${config.iconTagRemove}

    `;
  }


          Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null
        ])


        servers: servers.map((p) => ({ command: p.command!, host: p.serverHost! })),
      })

Missing Authentication for Critical Function

The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.


          text += `${c.amount(value, a.currency)}<br>`;
        });

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


tooltipText: (c: FormatterContext, d: BarChartDatum, e: string) => string;


async function validateSystemTransfer(
    message: Message,
    meta: ConfirmedTransactionMeta,
    recipient: Recipient
): Promise<[BigNumber, BigNumber]> {
    const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipient));
    if (accountIndex === -1) throw new ValidateTransferError('recipient not found');

    return [
        new BigNumber(meta.preBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),
        new BigNumber(meta.postBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),
    ];
}