code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
func (proj AppProject) IsResourcePermitted(groupKind schema.GroupKind, namespace string, dest ApplicationDestination) bool { if !proj.IsGroupKindPermitted(groupKind, namespace != "") { return false } if namespace != "" { return proj.IsDestinationPermitted(ApplicationDestination{Server: dest.Server, Name: dest.Name, Namespace: namespace}) } return true }
1
Go
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
func (s *FositeMemoryStore) setClientAssertionJWT(_ context.Context, jti *blacklistedJTI) error { s.Lock() defer s.Unlock() s.BlacklistedJTIs[jti.JTI] = jti.Expiry return nil }
1
Go
CWE-294
Authentication Bypass by Capture-replay
A capture-replay flaw exists when the design of the software makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).
https://cwe.mitre.org/data/definitions/294.html
safe
func (db *DB) Verify(s *data.Signed, role string, minVersion int64) error { err := db.VerifyIgnoreExpiredCheck(s, role, minVersion) if err != nil { return err } sm := &signedMeta{} if err := json.Unmarshal(s.Signed, sm); err != nil { return err } if IsExpired(sm.Expires) { return ErrExpired{sm.Expires} } return nil }
0
Go
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
vulnerable
func (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.Info("Deleted pending evidence", "evidence", evidence) } }
0
Go
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
func (mr *MockTokenRevocationStorageMockRecorder) GetAccessTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccessTokenSession", reflect.TypeOf((*MockTokenRevocationStorage)(nil).GetAccessTokenSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockAccessTokenStrategyMockRecorder) GenerateAccessToken(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateAccessToken", reflect.TypeOf((*MockAccessTokenStrategy)(nil).GenerateAccessToken), arg0, arg1) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (mr *MockAccessRequesterMockRecorder) AppendRequestedScope(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppendRequestedScope", reflect.TypeOf((*MockAccessRequester)(nil).AppendRequestedScope), arg0) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func invalidDoPrevoteFunc(t *testing.T, height int64, round int32, cs *State, sw *p2p.Switch, pv types.PrivValidator) { // routine to: // - precommit for a random block // - send precommit to all peers // - disable privValidator (so we don't do normal precommits) go func() { cs.mtx.Lock() cs.privValidator = pv pubKey, err := cs.privValidator.GetPubKey() if err != nil { panic(err) } addr := pubKey.Address() valIndex, _ := cs.Validators.GetByAddress(addr) // precommit a random block blockHash := bytes.HexBytes(tmrand.Bytes(32)) precommit := &types.Vote{ ValidatorAddress: addr, ValidatorIndex: valIndex, Height: cs.Height, Round: cs.Round, Timestamp: cs.voteTime(), Type: tmproto.PrecommitType, BlockID: types.BlockID{ Hash: blockHash, PartSetHeader: types.PartSetHeader{Total: 1, Hash: tmrand.Bytes(32)}}, } p := precommit.ToProto() cs.privValidator.SignVote(cs.state.ChainID, p) precommit.Signature = p.Signature cs.privValidator = nil // disable priv val so we don't do normal votes cs.mtx.Unlock() peers := sw.Peers().List() for _, peer := range peers { cs.Logger.Info("Sending bad vote", "block", blockHash, "peer", peer) peer.Send(VoteChannel, MustEncode(&VoteMessage{precommit})) } }() }
1
Go
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
safe
func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (proj AppProject) IsLiveResourcePermitted(un *unstructured.Unstructured, server string, name string) bool { if !proj.IsGroupKindPermitted(un.GroupVersionKind().GroupKind(), un.GetNamespace() != "") { return false } if un.GetNamespace() != "" { return proj.IsDestinationPermitted(ApplicationDestination{Server: server, Namespace: un.GetNamespace(), Name: name}) } return true }
0
Go
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
func TestMaxDepthValidation(t *testing.T) { s, err := schema.ParseSchema(interfaceSimple, false) if err != nil { t.Fatal(err) } for _, tc := range []struct { name string query string maxDepth int expected bool }{ { name: "off", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 0, }, { name: "fields", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 2, expected: true, }, { name: "fragment", query: `fragment friend on Character { id # depth 6 name friends { name # depth 7 } } query { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 friends { # depth 3 friends { # depth 4 friends { # depth 5 ...friend # depth 6 } } } } } }`, maxDepth: 5, expected: true, }, { name: "inlinefragment", query: `query { # depth 0 characters { # depth 1 ... on Droid { # depth 2 primaryFunction # depth 2 } } }`, maxDepth: 1, expected: true, }, } { t.Run(tc.name, func(t *testing.T) { doc, err := query.Parse(tc.query) if err != nil { t.Fatal(err) } context := newContext(s, doc, tc.maxDepth) op := doc.Operations[0] opc := &opContext{context: context, ops: doc.Operations} actual := validateMaxDepth(opc, op.Selections, 1) if actual != tc.expected { t.Errorf("expected %t, actual %t", tc.expected, actual) } }) } }
0
Go
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
func (m *ADeepBranch) 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: ADeepBranch: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ADeepBranch: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Down", 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 err := m.Down.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
0
Go
CWE-129
Improper Validation of Array Index
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
https://cwe.mitre.org/data/definitions/129.html
vulnerable
func padBuffer(buffer []byte, blockSize int) []byte { missing := blockSize - (len(buffer) % blockSize) ret, out := resize(buffer, len(buffer)+missing) padding := bytes.Repeat([]byte{byte(missing)}, missing) copy(out, padding) return ret }
0
Go
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
func setUids(ruid, euid, suid int) error { log.Printf("Setting ruid=%d euid=%d suid=%d", ruid, euid, suid) // We elevate the all the privs before setting them. This prevents // issues with (ruid=1000,euid=1000,suid=0), where just a single call // to setresuid might fail with permission denied. if res, err := C.setresuid(0, 0, 0); res < 0 { return errors.Wrapf(err.(syscall.Errno), "setting uids") } if res, err := C.setresuid(C.uid_t(ruid), C.uid_t(euid), C.uid_t(suid)); res < 0 { return errors.Wrapf(err.(syscall.Errno), "setting uids") } return nil }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func TestBuilder_BuildBootstrapStaticResources(t *testing.T) { t.Run("valid", func(t *testing.T) { b := New("localhost:1111", "localhost:2222", filemgr.NewManager(), nil) staticCfg, err := b.BuildBootstrapStaticResources() assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "clusters": [ { "name": "pomerium-control-plane-grpc", "type": "STATIC", "connectTimeout": "5s", "http2ProtocolOptions": {}, "loadAssignment": { "clusterName": "pomerium-control-plane-grpc", "endpoints": [{ "lbEndpoints": [{ "endpoint": { "address": { "socketAddress":{ "address": "127.0.0.1", "portValue": 1111 } } } }] }] } } ] } `, staticCfg) }) t.Run("bad gRPC address", func(t *testing.T) { b := New("xyz:zyx", "localhost:2222", filemgr.NewManager(), nil) _, err := b.BuildBootstrapStaticResources() assert.Error(t, err) }) }
0
Go
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
func newSessionService() { SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory", []string{"memory", "file", "redis", "mysql"}) SessionConfig = new(session.Config) SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ") SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits") SessionConfig.CookiePath = AppSubUrl SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE") SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true) SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400) SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400) SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC", "sha1", []string{"sha1", "sha256", "md5"}) SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY", string(com.RandomCreateBytes(16))) if SessionProvider == "file" { os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm) } log.Info("Session Service Enabled") }
0
Go
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
vulnerable
func (mr *MockCoreStorageMockRecorder) GetRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRefreshTokenSession", reflect.TypeOf((*MockCoreStorage)(nil).GetRefreshTokenSession), arg0, arg1, arg2) }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func (x *RuntimeInfo) Reset() { *x = RuntimeInfo{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func mockPlugin(name string) *Plugin { return &Plugin{ Metadata: &Metadata{ Name: name, Version: "v0.1.2", Usage: "Mock plugin", Description: "Mock plugin for testing", Command: "echo mock plugin", }, Dir: "no-such-dir", } }
1
Go
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
func (svc *Service) DeleteUser(ctx context.Context, id uint) error { if err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionWrite); err != nil { return err } return svc.ds.DeleteUser(ctx, id) }
0
Go
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
func (m *MockCoreStrategy) GenerateRefreshToken(arg0 context.Context, arg1 fosite.Requester) (string, string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GenerateRefreshToken", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
1
Go
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
func setUids(ruid, euid int) error { res, err := C.setreuid(C.uid_t(ruid), C.uid_t(euid)) log.Printf("setreuid(%d, %d) = %d (errno %v)", ruid, euid, res, err) if res == 0 { return nil } return errors.Wrapf(err.(syscall.Errno), "setting uids") }
1
Go
NVD-CWE-noinfo
null
null
null
safe
function foo() { var_dump(substr_compare("\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", 0, 65535, false)); }
1
TypeScript
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
from: globalDb.getServerTitle() + " <" + returnAddress + ">", subject: "Testing your Sandstorm's SMTP setting", text: "Success! Your outgoing SMTP is working.", smtpConfig: restConfig, }); } catch (e) { // Attempt to give more accurate error messages for a variety of known failure modes, // and the actual exception data in the event a user hits a new failure mode. if (e.syscall === "getaddrinfo") { if (e.code === "EIO" || e.code === "ENOTFOUND") { throw new Meteor.Error("getaddrinfo " + e.code, "Couldn't resolve \"" + smtpConfig.hostname + "\" - check for typos or broken DNS."); } } else if (e.syscall === "connect") { if (e.code === "ECONNREFUSED") { throw new Meteor.Error("connect ECONNREFUSED", "Server at " + smtpConfig.hostname + ":" + smtpConfig.port + " refused connection. Check your settings, firewall rules, and that your mail server is up."); } } else if (e.name === "AuthError") { throw new Meteor.Error("auth error", "Authentication failed. Check your credentials. Message from " + smtpConfig.hostname + ": " + e.data); } throw new Meteor.Error("other-email-sending-error", "Error while trying to send test email: " + JSON.stringify(e)); } },
0
TypeScript
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
(ou) => ou.organizationId === user.defaultOrganizationId );
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
async function decodeMessage(buffer: Buffer): Promise<any> { /* const offset = 16 * 3 + 6; buffer = buffer.slice(offset); */ const messageBuilder = new MessageBuilder({}); messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None); let objMessage: any = null; messageBuilder.once("full_message_body", (fullMessageBody: Buffer) => { const stream = new BinaryStream(fullMessageBody); const id = decodeExpandedNodeId(stream); objMessage = constructObject(id); objMessage.decode(stream); }); messageBuilder.feed(buffer); return objMessage; }
0
TypeScript
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
async start() { if (this.server) { return } this.app = await this.createApp() if (this.port) { this.server = this.app.listen(this.port) } else { do { try { this.port = await getPort({ port: defaultWatchServerPort }) this.server = this.app.listen(this.port) } catch {} } while (!this.server) } this.log.info("") this.statusLog = this.log.placeholder() }
0
TypeScript
CWE-306
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.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
function genOpenSSHEdPub(pub) { const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); writeUInt32BE(publicKey, 11, 0); publicKey.utf8Write('ssh-ed25519', 4, 11); writeUInt32BE(publicKey, pub.length, 15); publicKey.set(pub, 19); return publicKey; }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
public static IESParameterSpec guessParameterSpec(BufferedBlockCipher iesBlockCipher, byte[] nonce) { if (iesBlockCipher == null) { return new IESParameterSpec(null, null, 128); } else { BlockCipher underlyingCipher = iesBlockCipher.getUnderlyingCipher(); if (underlyingCipher.getAlgorithmName().equals("DES") || underlyingCipher.getAlgorithmName().equals("RC2") || underlyingCipher.getAlgorithmName().equals("RC5-32") || underlyingCipher.getAlgorithmName().equals("RC5-64")) { return new IESParameterSpec(null, null, 64, 64, nonce); } else if (underlyingCipher.getAlgorithmName().equals("SKIPJACK")) { return new IESParameterSpec(null, null, 80, 80, nonce); } else if (underlyingCipher.getAlgorithmName().equals("GOST28147")) { return new IESParameterSpec(null, null, 256, 256, nonce); } return new IESParameterSpec(null, null, 128, 128, nonce); } }
1
TypeScript
CWE-310
Cryptographic Issues
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.
https://cwe.mitre.org/data/definitions/310.html
safe
function RegisterUserName(socket, Data) { var userName = Data.UserName.split('>').join(' ').split('<').join(' ').split('/').join(' '); if (userName.length > 16) userName = userName.slice(0, 16); if (userName.toLowerCase().includes('você')) userName = '~' + userName; ActiveRooms.forEach((element, index) => { if (element.Id === Data.RoomId) { ActiveRooms[index].Players.forEach((element2, index2) => { if (element2.Name.toLowerCase() === userName.toLowerCase()) { console.log('UserName already exists'); return socket.emit('UserNameAlreadyExists'); } else if (element2.Id === Data.UserId) { ActiveRooms[index].Players[index2].Name = userName; } socket.emit('UserNameInformation', JSON.stringify({ RoomId: element.Id, UserId: element2.Id, NickName: element2.Name })); }); } }); }
0
TypeScript
CWE-384
Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
https://cwe.mitre.org/data/definitions/384.html
vulnerable
Languages.get = async function (language, namespace) { const data = await fs.promises.readFile(path.join(languagesPath, language, `${namespace}.json`), 'utf8'); const parsed = JSON.parse(data) || {}; const result = await plugins.hooks.fire('filter:languages.get', { language, namespace, data: parsed, }); return result.data; };
0
TypeScript
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
function onDecipherPayload(payload) { deciphered.push(payload); }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
password: uuidv4(), token: invitationToken, role: 'developer', }); expect(response.statusCode).toBe(201); const updatedUser = await getManager().findOneOrFail(User, { where: { email: user.email } }); expect(updatedUser.firstName).toEqual('signupuser'); expect(updatedUser.lastName).toEqual('user'); expect(updatedUser.defaultOrganizationId).toEqual(organization.id); const organizationUser = await getManager().findOneOrFail(OrganizationUser, { where: { userId: user.id } }); expect(organizationUser.status).toEqual('active'); });
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
module.exports = (env) => { const toReplace = Object.keys(env).filter((envVar) => { // https://github.com/semantic-release/semantic-release/issues/1558 if (envVar === 'GOPRIVATE') { return false; } return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE; }); const regexp = new RegExp( toReplace .map((envVar) => `${escapeRegExp(env[envVar])}|${encodeURI(escapeRegExp(env[envVar]))}`) .join('|'), 'g' ); return (output) => output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output; };
1
TypeScript
CWE-116
Improper Encoding or Escaping of Output
The software prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.
https://cwe.mitre.org/data/definitions/116.html
safe
export default function rtrim(str, chars) { assertString(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping const pattern = chars ? new RegExp(`[${chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}]+$`, 'g') : /(\s)+$/g; return str.replace(pattern, ''); }
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
pos: () => pos, length: () => (buffer ? buffer.length : 0),
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
export function collideUnsafe(arg1: any, arg2: any, modifiers?: ICollideModifiers, startPath: string = '$'): any { if (arg2 === undefined) { return arg1; } if (isMissing(arg1)) { return arg2; } if (isBasicType(arg1)) { return collideBasic(arg1, arg2, startPath, modifiers); } if (isArray(arg1)) { return collideArrays(arg1, arg2, startPath, modifiers); } return collideObjects(arg1, arg2, startPath, modifiers); }
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
function validateExplainValue(explain) { if (explain) { // The list of allowed explain values is from node-mongodb-native/lib/explain.js const explainAllowedValues = [ 'queryPlanner', 'queryPlannerExtended', 'executionStats', 'allPlansExecution', false, true, ]; if (!explainAllowedValues.includes(explain)) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Invalid value for explain'); } } }
1
TypeScript
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
safe
body: JSON.stringify({ ...keys, _method: 'POST', username: '[email protected]', password: 'somepassword', email: '[email protected]', }), }); this.objectId = signUpResponse.data.objectId; this.sessionToken = signUpResponse.data.sessionToken; this.partialSessionToken = this.sessionToken.slice(0, 3); });
1
TypeScript
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
safe
free() { this._dead = true; }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
function zlibOnError(message, errno, code) { const self = this._owner; // There is no way to cleanly recover. // Continuing only obscures problems. const error = new Error(message); error.errno = errno; error.code = code; self._err = error; }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
export function loadFromGitSync(input: Input): string | never { try { return execSync(createCommand(input), { encoding: 'utf-8' }); } catch (error) { throw createLoadError(error); } }
0
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
groupNames: groups.join(", "), }), "warning" ); } });
0
TypeScript
CWE-276
Incorrect Default Permissions
During installation, installed file permissions are set to allow anyone to modify those files.
https://cwe.mitre.org/data/definitions/276.html
vulnerable
PageantSock.prototype.write = function(buf) { if (this.buffer === null) this.buffer = buf; else { this.buffer = Buffer.concat([this.buffer, buf], this.buffer.length + buf.length); } // Wait for at least all length bytes if (this.buffer.length < 4) return; var len = readUInt32BE(this.buffer, 0); // Make sure we have a full message before querying pageant if ((this.buffer.length - 4) < len) return; buf = this.buffer.slice(0, 4 + len); if (this.buffer.length > (4 + len)) this.buffer = this.buffer.slice(4 + len); else this.buffer = null; var self = this; var proc; var hadError = false; proc = this.proc = cp.spawn(EXEPATH, [ buf.length ]); proc.stdout.on('data', function(data) { self.emit('data', data); }); proc.once('error', function(err) { if (!hadError) { hadError = true; self.emit('error', err); } }); proc.once('close', function(code) { self.proc = undefined; if (ERROR[code] && !hadError) { hadError = true; self.emit('error', ERROR[code]); } self.emit('close', hadError); }); proc.stdin.end(buf); };
0
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
const pushVal = (obj, path, val, options = {}) => { if (obj === undefined || obj === null || path === undefined) { return obj; } // Clean the path path = clean(path); const pathParts = split(path); const part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = decouple(obj[part], options) || {}; // Recurse pushVal(obj[part], pathParts.join("."), val, options); } else if (part) { // We have found the target array, push the value obj[part] = decouple(obj[part], options) || []; if (!(obj[part] instanceof Array)) { throw("Cannot push to a path whose leaf node is not an array!"); } obj[part].push(val); } else { // We have found the target array, push the value obj = decouple(obj, options) || []; if (!(obj instanceof Array)) { throw("Cannot push to a path whose leaf node is not an array!"); } obj.push(val); } return decouple(obj, options); };
0
TypeScript
CWE-915
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.
https://cwe.mitre.org/data/definitions/915.html
vulnerable
export default function addStickyControl() { extend(DiscussionListState.prototype, 'requestParams', function(params) { if (app.current.matches(IndexPage) || app.current.matches(DiscussionPage)) { params.include.push('firstPost'); } }); extend(DiscussionListItem.prototype, 'infoItems', function(items) { const discussion = this.attrs.discussion; if (discussion.isSticky() && !this.attrs.params.q && !discussion.lastReadPostNumber()) { const firstPost = discussion.firstPost(); if (firstPost) { const excerpt = truncate(firstPost.contentPlain(), 175); items.add('excerpt', m.trust(excerpt), -100); } } }); }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
readUInt32BE: () => { if (!buffer || pos + 3 >= buffer.length) return; return (buffer[pos++] * 16777216) + (buffer[pos++] * 65536) + (buffer[pos++] * 256) + buffer[pos++]; },
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
0
TypeScript
CWE-1236
Improper Neutralization of Formula Elements in a CSV File
The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.
https://cwe.mitre.org/data/definitions/1236.html
vulnerable
updateProfile: function() { this.cleanErrors(); if (!this.user.username) this.errors.username = "Username required"; if (!this.user.firstname) this.errors.firstname = "Firstname required"; if (!this.user.lastname) this.errors.lastname = "Lastname required"; if (!this.user.currentPassword) this.errors.currentPassword = "Current Password required"; if (this.user.newPassword !== this.user.confirmPassword) this.errors.newPassword = "New Password and Confirm Password are differents"; if (this.errors.username || this.errors.firstname || this.errors.lastname || this.errors.currentPassword || this.errors.newPassword) return; UserService.updateProfile(this.user) .then((data) => { UserService.checkToken() Notify.create({ message: 'Profile updated successfully', color: 'positive', textColor:'white', position: 'top-right' }) }) .catch((err) => { Notify.create({ message: err.response.data.datas, color: 'negative', textColor: 'white', position: 'top-right' }) }) },
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
export function escape<T>(input: T): T extends SafeValue ? T['value'] : T { return typeof input === 'string' ? string.escapeHTML(input) : input instanceof SafeValue ? input.value : input }
0
TypeScript
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
vulnerable
public buildRawNFT1GenesisTx(config: configBuildRawNFT1GenesisTx, type = 0x01) { const config2: configBuildRawGenesisTx = { slpGenesisOpReturn: config.slpNFT1GenesisOpReturn, mintReceiverAddress: config.mintReceiverAddress, mintReceiverSatoshis: config.mintReceiverSatoshis, batonReceiverAddress: null, bchChangeReceiverAddress: config.bchChangeReceiverAddress, input_utxos: config.input_utxos, allowed_token_burning: [ config.parentTokenIdHex ], }; return this.buildRawGenesisTx(config2); }
1
TypeScript
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
function set(target, path, val) { "use strict"; try { return add(target, path, val); } catch (ex) { console.error(ex); return; } }
1
TypeScript
CWE-915
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.
https://cwe.mitre.org/data/definitions/915.html
safe
): Promise<void> => { event.preventDefault(); if (SingleSignOn.isSingleSignOnLoginWindow(frameName)) { return new SingleSignOn(main, event, url, options).init(); } this.logger.log('Opening an external window from a webview.'); return shell.openExternal(url); };
0
TypeScript
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), data.data.key, function () { grid.getStore().removeAt(rowIndex); }.bind(this)); }.bind(this)
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
const addReplyToEvent = (event: any) => { event.reply = (...args: any[]) => { event.sender.sendToFrame(event.frameId, ...args); }; };
0
TypeScript
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
vulnerable
commentSchema.statics.updateCommentsByPageId = function(comment, isMarkdown, commentId) { const Comment = this; return Comment.findOneAndUpdate( { _id: commentId }, { $set: { comment, isMarkdown } }, ); };
0
TypeScript
CWE-639
Authorization Bypass Through User-Controlled Key
The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.
https://cwe.mitre.org/data/definitions/639.html
vulnerable
const unSet = (obj, path, options = {}, tracking = {}) => { let internalPath = path; 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; } const newObj = decouple(obj, options); // Path has no dot-notation, set key/value if (isNonCompositePath(internalPath)) { const unescapedPath = unEscape(internalPath); // Do not allow prototype pollution if (unescapedPath === "__proto__") return obj; if (newObj.hasOwnProperty(unescapedPath)) { delete newObj[options.transformKey(unescapedPath)]; return newObj; } tracking.returnOriginal = true; return obj; } const pathParts = split(internalPath); const pathPart = pathParts.shift(); const transformedPathPart = options.transformKey(unEscape(pathPart)); // Do not allow prototype pollution if (transformedPathPart === "__proto__") return obj; let childPart = newObj[transformedPathPart]; if (!childPart) { // No child part available, nothing to unset! tracking.returnOriginal = true; return obj; } newObj[transformedPathPart] = unSet(childPart, pathParts.join('.'), options, tracking); if (tracking.returnOriginal) { return obj; } return newObj; };
1
TypeScript
CWE-915
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.
https://cwe.mitre.org/data/definitions/915.html
safe
): { destroy: () => void; update: (t: () => string) => void } {
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
async signup(email: string) { const existingUser = await this.usersService.findByEmail(email); if (existingUser?.invitationToken || existingUser?.organizationUsers?.some((ou) => ou.status === 'active')) { throw new NotAcceptableException('Email already exists'); } let organization: Organization; // Check if the configs allows user signups if (this.configService.get<string>('DISABLE_MULTI_WORKSPACE') === 'true') { // Single organization checking if organization exist organization = await this.organizationsService.getSingleOrganization(); if (organization) { throw new NotAcceptableException('Multi organization not supported - organization exist'); } } else { // Multi organization if (this.configService.get<string>('DISABLE_SIGNUPS') === 'true') { throw new NotAcceptableException(); } } // Create default organization organization = await this.organizationsService.create('Untitled workspace'); const user = await this.usersService.create({ email }, organization.id, ['all_users', 'admin'], existingUser, true); await this.organizationUsersService.create(user, organization, true); await this.emailService.sendWelcomeEmail(user.email, user.firstName, user.invitationToken); return {}; }
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
function generate( target: any, hierarchies: SetupPropParam[], forceOverride?: boolean ) { 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; }
1
TypeScript
CWE-1321
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.
https://cwe.mitre.org/data/definitions/1321.html
safe
export function logoutClientSideOnly(ps: { goTo?: St, skipSend?: Bo } = {}) { Server.deleteTempSessId(); ReactDispatcher.handleViewAction({ actionType: actionTypes.Logout }); if (eds.isInEmbeddedCommentsIframe && !ps.skipSend) { // Tell the editor iframe that we've logged out. // And maybe we'll redirect the embedd*ing* window. [sso_redir_par_win] sendToOtherIframes(['logoutClientSideOnly', ps]); // Probaby not needed, since reload() below, but anyway: patchTheStore({ setEditorOpen: false }); const sessWin: MainWin = getMainWin(); delete sessWin.typs.weakSessionId; sessWin.theStore.me = 'TyMLOGDOUT' as any; } // Disconnect WebSocket so we won't receive data, for this user, after we've // logged out: (we reload() below — but the service-worker might stay connected) pubsub.disconnectWebSocket(); if (ps.goTo) { if (eds.isInIframe) { // Then we'll redirect the parent window instead. [sso_redir_par_win] } else { location.assign(ps.goTo); } // If that for some reason won't do anything, then make sure we really forget // all logged in state anyway: setTimeout(function() { logW(`location.assign(${ps.goTo}) had no effect? Reloading anyway...`); location.reload(); }, 2000); } else { // Quick fix that reloads the admin page (if one views it) so login dialog appears. // But don't do in the goTo if branch — apparently location.reload() // cancels location.assign(..) — even if done on the lines after (!). location.reload(); } }
0
TypeScript
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
onAvatarChange (input: HTMLInputElement) { this.avatarfileInput = new ElementRef(input) const avatarfile = this.avatarfileInput.nativeElement.files[0] if (avatarfile.size > this.maxAvatarSize) { this.notifier.error('Error', $localize`This image is too large.`) return } const formData = new FormData() formData.append('avatarfile', avatarfile) this.avatarPopover?.close() this.avatarChange.emit(formData) if (this.previewImage) { this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(avatarfile)) } }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
constructor(bitbox: BITBOX) { if (!bitbox) { throw Error("Must provide BITBOX instance to class constructor.") } this.BITBOX = bitbox; }
1
TypeScript
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
public static IESParameterSpec guessParameterSpec(BufferedBlockCipher iesBlockCipher) { if (iesBlockCipher == null) { return new IESParameterSpec(null, null, 128); } else { BlockCipher underlyingCipher = iesBlockCipher.getUnderlyingCipher(); if (underlyingCipher.getAlgorithmName().equals("DES") || underlyingCipher.getAlgorithmName().equals("RC2") || underlyingCipher.getAlgorithmName().equals("RC5-32") || underlyingCipher.getAlgorithmName().equals("RC5-64")) { return new IESParameterSpec(null, null, 64, 64); } else if (underlyingCipher.getAlgorithmName().equals("SKIPJACK")) { return new IESParameterSpec(null, null, 80, 80); } else if (underlyingCipher.getAlgorithmName().equals("GOST28147")) { return new IESParameterSpec(null, null, 256, 256); } return new IESParameterSpec(null, null, 128, 128); } }
0
TypeScript
CWE-310
Cryptographic Issues
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.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, totalHours, }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
): Promise<{ [line: string]: BlamedLine }> => { const result = await parseStringPromise(buffer); const json: { [line: string]: BlamedLine } = {}; result.blame.target[0].entry.forEach((line: any) => { json[line.$['line-number']] = { author: line.commit[0].author[0], date: line.commit[0].date[0], line: line.$['line-number'], rev: line.commit[0].$.revision }; }); return json; };
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
function check_response(err: Error | null, response: any) { should.not.exist(err); //xx debugLog(response.toString()); response.responseHeader.serviceResult.should.eql(StatusCodes.BadInvalidArgument); }
0
TypeScript
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
vulnerable
use: (path) => { useCount++; expect(path).toEqual('somepath'); },
0
TypeScript
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
function _ondata(data) { bc += data.length; if (state === 'secret') { // The secret we sent is echoed back to us by cygwin, not sure of // the reason for that, but we ignore it nonetheless ... if (bc === 16) { bc = 0; state = 'creds'; sock.write(credsbuf); } } else if (state === 'creds') { // If this is the first attempt, make sure to gather the valid // uid and gid for our next attempt if (!isRetrying) inbuf.push(data); if (bc === 12) { sock.removeListener('connect', _onconnect); sock.removeListener('data', _ondata); sock.removeListener('close', _onclose); if (isRetrying) { addSockListeners(); sock.emit('connect'); } else { isRetrying = true; credsbuf = Buffer.concat(inbuf); writeUInt32LE(credsbuf, process.pid, 0); sock.destroy(); tryConnect(); } } } }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
function getStructure(target, prefix) { if (! isObject(target)) { return [{path: [], value: target}]; } if (! prefix) { prefix = []; } if (Array.isArray(target)) { return target.reduce(function (result, value, i) { return result.concat( getPropStructure(value, prefix.concat(i)) ); }, []); } else { return Object.getOwnPropertyNames(target) .reduce(function(result, key) { const value = target[key]; return result.concat( getPropStructure(value, prefix.concat(key)) ); }, []); } }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
end() { this.buffer = null; if (this.proc) { this.proc.kill(); this.proc = undefined; } }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
function isExternal(url) { let match = url.match( /^([^:/?#]+:)?(?:\/\/([^/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/ ); if ( typeof match[1] === 'string' && match[1].length > 0 && match[1].toLowerCase() !== location.protocol ) { return true; } if ( typeof match[2] === 'string' && match[2].length > 0 && match[2].replace( new RegExp( ':(' + { 'http:': 80, 'https:': 443 }[location.protocol] + ')?$' ), '' ) !== location.host ) { return true; } return false; }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
TEST_F(AsStringGraphTest, String) { Status s = Init(DT_STRING); ASSERT_EQ(error::INVALID_ARGUMENT, s.code()); ASSERT_TRUE(absl::StrContains( s.error_message(), "Value for attr 'T' of string is not in the list of allowed values")); }
1
TypeScript
CWE-134
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.
https://cwe.mitre.org/data/definitions/134.html
safe
return function verify(data, signature, algo) { const pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; try { return verify_(algo, data, pem, signature); } catch (ex) { return ex; } };
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
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(target); } }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
const matrix = node.getScreenCTM(); if (res && matrix) { const [x, y, content] = res; const t = tooltip(); t.style.opacity = "1"; t.innerHTML = content; t.style.left = `${window.scrollX + x + matrix.e}px`; t.style.top = `${window.scrollY + y + matrix.f - 15}px`; } else { hide(); } } node.addEventListener("mousemove", mousemove); node.addEventListener("mouseleave", hide); return { destroy: hide, }; }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
function setProp(obj, property, value) { if (!obj.hasOwnProperty(property)) { throw new Error(`Property '${property}' is not valid`); } obj[property] = value; }
1
TypeScript
CWE-915
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.
https://cwe.mitre.org/data/definitions/915.html
safe
function checkCredentials(req, res, next) { if (!sqlInit.isDbInitialized()) { res.status(400).send('Database is not initialized yet.'); return; } if (!passwordService.isPasswordSet()) { res.status(400).send('Password has not been set yet. Please set a password and repeat the action'); return; } const header = req.headers['trilium-cred'] || ''; const auth = new Buffer.from(header, 'base64').toString(); const [username, password] = auth.split(/:/); // username is ignored if (!passwordEncryptionService.verifyPassword(password)) { res.status(401).send('Incorrect password'); } else { next(); } }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
const pdf = await mdToPdf({ path: resolve(__dirname, 'mathjax', 'math.md') }); t.is(pdf.filename, ''); t.truthy(pdf.content); const doc = await getDocument({ data: pdf.content }).promise; const page = await doc.getPage(1); const text = (await page.getTextContent()).items.map(({ str }) => str).join(''); t.true(text.startsWith('Formulas with MathJax')); t.true(text.includes('a≠0')); });
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
function onCipherData(data) { ciphered = Buffer.concat([ciphered, data]); }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
onUpdate: function (username, accessToken) { users[username] = accessToken; }
1
TypeScript
CWE-88
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.
https://cwe.mitre.org/data/definitions/88.html
safe
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 exec(`git log -1 --format="%at" -- ${path}`); return new Date(Number(ts) * 1000); };
0
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
triggerMassAction: function (massActionUrl, type) { const self = this.relatedListInstance; let validationResult = self.checkListRecordSelected(); if (validationResult != true) { let progressIndicatorElement = $.progressIndicator(), selectedIds = self.readSelectedIds(true), excludedIds = self.readExcludedIds(true), cvId = self.getCurrentCvId(), postData = self.getCompleteParams(); delete postData.mode; delete postData.view; postData.viewname = cvId; postData.selected_ids = selectedIds; postData.excluded_ids = excludedIds; let actionParams = { type: 'POST', url: massActionUrl, data: postData }; if (type === 'sendByForm') { app.openUrlMethodPost(massActionUrl, postData); progressIndicatorElement.progressIndicator({ mode: 'hide' }); } else { AppConnector.request(actionParams) .done(function (responseData) { progressIndicatorElement.progressIndicator({ mode: 'hide' }); if (responseData && responseData.result !== null) { if (responseData.result.notify) { Vtiger_Helper_Js.showMessage(responseData.result.notify); } if (responseData.result.reloadList) { Vtiger_Detail_Js.reloadRelatedList(); } if (responseData.result.processStop) { progressIndicatorElement.progressIndicator({ mode: 'hide' }); return false; } } }) .fail(function (error, err) { progressIndicatorElement.progressIndicator({ mode: 'hide' }); }); } } else { self.noRecordSelectedAlert(); } },
0
TypeScript
CWE-352
Cross-Site Request Forgery (CSRF)
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.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
content: Buffer.concat(buffers), mimeType: resp.headers["content-type"] || null, }); });
1
TypeScript
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
function text({ url, host }: Record<"url" | "host", string>) { return `Sign in to ${host}\n${url}\n\n` }
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
const handleVote = (pollId, answerId) => { makeCall('publishVote', pollId, answerId.id); };
1
TypeScript
NVD-CWE-noinfo
null
null
null
safe
function networkStats(ifaces, callback) { let ifacesArray = []; return new Promise((resolve) => { process.nextTick(() => { // fallback - if only callback is given if (util.isFunction(ifaces) && !callback) { callback = ifaces; ifacesArray = [getDefaultNetworkInterface()]; } else { if (typeof ifaces !== 'string' && ifaces !== undefined) { if (callback) { callback([]); } return resolve([]); } ifaces = ifaces || getDefaultNetworkInterface(); ifaces.__proto__.toLowerCase = util.stringToLower; ifaces.__proto__.replace = util.stringReplace; ifaces.__proto__.trim = util.stringTrim; ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|'); ifacesArray = ifaces.split('|'); } const result = []; const workload = []; if (ifacesArray.length && ifacesArray[0].trim() === '*') { ifacesArray = []; networkInterfaces(false).then(allIFaces => { for (let iface of allIFaces) { ifacesArray.push(iface.iface); } networkStats(ifacesArray.join(',')).then(result => { if (callback) { callback(result); } resolve(result); }); }); } else { for (let iface of ifacesArray) { workload.push(networkStatsSingle(iface.trim())); } if (workload.length) { Promise.all( workload ).then(data => { if (callback) { callback(data); } resolve(data); }); } else { if (callback) { callback(result); } resolve(result); } } }); }); }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
parse(cookieStr) { let cookie = {}; (cookieStr || '') .toString() .split(';') .forEach(cookiePart => { let valueParts = cookiePart.split('='); let key = valueParts.shift().trim().toLowerCase(); let value = valueParts.join('=').trim(); let domain; if (!key) { // skip empty parts return; } switch (key) { case 'expires': value = new Date(value); // ignore date if can not parse it if (value.toString() !== 'Invalid Date') { cookie.expires = value; } break; case 'path': cookie.path = value; break; case 'domain': domain = value.toLowerCase(); if (domain.length && domain.charAt(0) !== '.') { domain = '.' + domain; // ensure preceeding dot for user set domains } cookie.domain = domain; break; case 'max-age': cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000); break; case 'secure': cookie.secure = true; break; case 'httponly': cookie.httponly = true; break; default: if (!cookie.name) { cookie.name = key; cookie.value = value; } } }); return cookie; }
1
TypeScript
CWE-88
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.
https://cwe.mitre.org/data/definitions/88.html
safe
GraphQLPlayground.init(root, ${JSON.stringify( extendedOptions, null, 2, )}) })
0
TypeScript
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
function getNetwork(addr, bits) { // npm ip's "mask" and "cidr" functions are broken for ipv6. :( const parsed = Ip.toBuffer(addr); for (let i = Math.ceil(bits / 8); i < parsed.length; i++) { parsed[i] = 0; } const n = Math.floor(bits / 8); if (n < parsed.length) { parsed[n] = parsed[n] & (0xff << (8 - bits % 8)); } return parsed; }
1
TypeScript
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
public void testUnpackDoesntLeaveTarget() throws Exception { File file = File.createTempFile("temp", null); File tmpDir = file.getParentFile(); try { ZipUtil.unpack(badFile, tmpDir); fail(); } catch (ZipException e) { assertTrue(true); } }
1
TypeScript
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
const replaceCharactersWithSpaces = (text) => { const re = new RegExp(`[${settings.CHARACTERS_TO_REPLACE_WITH_SPACES}]`, 'g'); const newText = text.replace(re, ' ').trim(); return newText; };
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
var downloadCLIDriver = function(res) { if( res.statusCode != 200 ) { console.log( "Unable to download IBM ODBC and CLI Driver from " + installerfileURL ); process.exit(1); } //var file = fs.createWriteStream(INSTALLER_FILE); var fileLength = parseInt( res.headers['content-length'] ); var buf = new Buffer( fileLength ); var byteIndex = 0; res.on('data', function(data) { if( byteIndex + data.length > buf.length ) { console.log( "Error downloading IBM ODBC and CLI Driver from " + installerfileURL ); process.exit(1); } data.copy( buf, byteIndex ); byteIndex += data.length; process.stdout.write((platform == 'win32') ? "\033[0G": "\r"); process.stdout.write("Downloaded " + (100.0 * byteIndex / fileLength).toFixed(2) + "% (" + byteIndex + " bytes)"); }).on('end', function() { console.log("\n"); if( byteIndex != buf.length ) { console.log( "Error downloading IBM ODBC and CLI Driver from " + installerfileURL ); process.exit(1); } copyAndExtractDriver(buf); }); } // downloadCLIDriver
1
TypeScript
CWE-310
Cryptographic Issues
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.
https://cwe.mitre.org/data/definitions/310.html
safe
export function createMuteOgg( outputFile: string, options: { seconds: number; sampleRate: number; numOfChannels: number } ) { return new Promise<true>((resolve, reject) => { if (!outputFile || !options || !options.seconds || !options.sampleRate || !options.numOfChannels) return reject(new Error('malformed props to createMuteOgg')) if ( !Number.isInteger(options.seconds) || !Number.isInteger(options.sampleRate) || !Number.isInteger(options.numOfChannels) ) return reject(new Error('malformed numerico options prop for createMuteOgg')) const ch = options.numOfChannels === 1 ? 'mono' : 'stereo' exec( 'ffmpeg -f lavfi -i anullsrc=r=' + options.sampleRate + ':cl=' + ch + ' -t ' + options.seconds + ' -c:a libvorbis ' + outputFile, (error, stdout, stderr) => { if (error) return reject(error) // if (!stdout) return reject(new Error('can\'t probe file ' + outputFile)) resolve(true) } ) }) }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, totalHours, }
0
TypeScript
CWE-1236
Improper Neutralization of Formula Elements in a CSV File
The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.
https://cwe.mitre.org/data/definitions/1236.html
vulnerable
function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; }
1
TypeScript
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
a: () => { /*_*/ } }, { a: source } ); assert.deepEqual({ a: source }, target); assert.strictEqual(source, target.a); });
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
}validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${ v.name }), validatorOptions)${v.hasQuestion ? ' : null' : ''}` : '' ) .join(',\n')}\n ])`
0
TypeScript
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
const requestOptions = { method: 'POST', headers: authHeader(), body: JSON.stringify(body) }; return fetch(`${config.apiUrl}/users/set_password_from_token`, requestOptions).then(handleResponse); }
0
TypeScript
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
export function setDeepProperty(obj: any, propertyPath: string, value: any): void { const a = splitPath(propertyPath); const n = a.length; for (let i = 0; i < n - 1; i++) { const k = a[i]; if (!(k in obj)) { obj[k] = {}; } obj = obj[k]; } obj[a[n - 1]] = value; return; }
0
TypeScript
CWE-915
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.
https://cwe.mitre.org/data/definitions/915.html
vulnerable