code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
function reset_graph_history() {
var table = eventGraph.menu_history.items["table_graph_history_actiontable"];
dataHandler.fetch_graph_history(function(history_formatted, network_previews) {
table.set_table_data(history_formatted);
for(var i=0; i<history_formatted.length; i++) {
var history = history_formatted[i];
var cur_email = history[2];
var tr = eventGraph.menu_history.items.table_graph_history_actiontable.get_DOM_row(i);
if (!(cur_email == user_email || is_siteadmin)) {
// disable delete button
var btn_del = $(tr).find('.btn-danger');
btn_del.prop('disabled', true);
}
// set tooltip preview
var preview = network_previews[i];
if (typeof preview == 'string') {
var btn_plot = $(tr).find('.btn-success');
btn_plot.data('network-preview', preview);
btn_plot.popover({
container: 'body',
content: function() { return '<img style="width: 500px; height: 150px;" src="' + $('<div>').text($(this).data('network-preview')).html() + '" />'; },
placement: 'right',
trigger: 'hover',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content" style="width: 500px; height: 150px;"></div></div>',
html: true,
});
}
}
});
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
async function _alertFromGet(type) {
if (urlParams.has(type)) {
var msg = urlParams.get(type);
var div = document.createElement("div");
div.innerHTML = cleanHTML(msg, false);
var text = div.textContent || div.innerText || "";
if (!empty(text)) {
switch (type) {
case 'error':
avideoAlertError(text);
break;
case 'msg':
avideoAlertInfo(text);
break;
case 'success':
avideoAlertSuccess(text);
break;
case 'toast':
avideoToast(text);
break;
}
var url = removeGetParam(window.location.href, type);
window.history.pushState({}, document.title, url);
}
}
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function removeScripts (html) {
let scripts = html.querySelectorAll('script');
for (let script of scripts) {
script.remove();
}
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function stringToHTML () {
let parser = new DOMParser();
let doc = parser.parseFromString(str, 'text/html');
return doc.body || document.createElement('body');
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function clean (html) {
let nodes = html.children;
for (let node of nodes) {
removeAttributes(node);
clean(node);
}
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function isPossiblyDangerous (name, value) {
let val = value.replace(/\s+/g, '').toLowerCase();
if (['src', 'href', 'xlink:href'].includes(name)) {
if (val.includes('javascript:') || val.includes('data:text/html')) return true;
}
if (name.startsWith('on')) return true;
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function removeAttributes (elem) {
// Loop through each attribute
// If it's dangerous, remove it
let atts = elem.attributes;
for (let {name, value} of atts) {
if (!isPossiblyDangerous(name, value)) continue;
elem.removeAttribute(name);
}
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
function cleanHTML (str, nodes) {
/**
* Convert the string to an HTML document
* @return {Node} An HTML document
*/
function stringToHTML () {
let parser = new DOMParser();
let doc = parser.parseFromString(str, 'text/html');
return doc.body || document.createElement('body');
}
/**
* Remove <script> elements
* @param {Node} html The HTML
*/
function removeScripts (html) {
let scripts = html.querySelectorAll('script');
for (let script of scripts) {
script.remove();
}
}
/**
* Check if the attribute is potentially dangerous
* @param {String} name The attribute name
* @param {String} value The attribute value
* @return {Boolean} If true, the attribute is potentially dangerous
*/
function isPossiblyDangerous (name, value) {
let val = value.replace(/\s+/g, '').toLowerCase();
if (['src', 'href', 'xlink:href'].includes(name)) {
if (val.includes('javascript:') || val.includes('data:text/html')) return true;
}
if (name.startsWith('on')) return true;
}
/**
* Remove potentially dangerous attributes from an element
* @param {Node} elem The element
*/
function removeAttributes (elem) {
// Loop through each attribute
// If it's dangerous, remove it
let atts = elem.attributes;
for (let {name, value} of atts) {
if (!isPossiblyDangerous(name, value)) continue;
elem.removeAttribute(name);
}
}
/**
* Remove dangerous stuff from the HTML document's nodes
* @param {Node} html The HTML document
*/
function clean (html) {
let nodes = html.children;
for (let node of nodes) {
removeAttributes(node);
clean(node);
}
}
// Convert the string to HTML
let html = stringToHTML();
// Sanitize it
removeScripts(html);
clean(html);
// If the user wants HTML nodes back, return them
// Otherwise, pass a sanitized string back
return nodes ? html.childNodes : html.innerHTML;
} | 1 | JavaScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product 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 | safe |
headers: form.getHeaders(),
method: 'POST'
}
const randomFileBuffer = Buffer.alloc(15_000_000)
crypto.randomFillSync(randomFileBuffer)
const req = http.request(opts)
form.append('upload', randomFileBuffer)
form.pipe(req)
try {
const [res] = await once(req, 'response')
t.equal(res.statusCode, 413)
res.resume()
await once(res, 'end')
} catch (error) {
t.error(error, 'request')
}
}) | 1 | JavaScript | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}
const req = http.request(opts, (res) => {
t.equal(res.statusCode, 500)
res.resume()
res.on('end', () => {
t.pass('res ended successfully')
t.end()
})
})
for (let i = 0; i < 1000; ++i) {
form.append('hello' + i, 'world')
}
// Exceeds the default limit (1000)
form.append('hello', 'world')
form.pipe(req)
})
}) | 1 | JavaScript | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
function barrettReduce(x) {
if (x.s < 0) { throw Error("Barrett reduction on negative input"); }
x.drShiftTo(this.m.t-1,this.r2);
if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
x.subTo(this.r2,x);
while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
} | 1 | JavaScript | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
const positiveModInverse = function(m) {
const inv = originalModInverse.apply(this, [m]);
return inv.mod(m);
} | 1 | JavaScript | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
const runner = () => {
for (const kStr of negativeModInverseCases) {
const k = new BigInteger(kStr);
const kinv = k.modInverse(p);
assert.isAtLeast(kinv.s, 0, "Negative mod inverse");
}
}; | 1 | JavaScript | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
success: function (data) {
data = data.replace(/\s+/g, ' ');
if (data.indexOf('error:') != '-1') {
toastr.error(data);
} else {
$("#dialog-settings-service").html(data)
$( "input[type=checkbox]" ).checkboxradio();
$("#dialog-settings-service").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
title: settings_word + " "+for_word+" " + name,
buttons: [{
text: save_word,
click: function () {
$(this).dialog("close");
serverSettingsSave(id, name, service, $(this));
}
}, {
text: cancel_word,
click: function () {
$(this).dialog("close");
}
}]
});
}
} | 1 | JavaScript | 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 | safe |
token: $('#token').val()
},
type: "POST",
success: function (data) {
data = data.replace(/\s+/g, ' ');
if (data.indexOf('error:') != '-1') {
toastr.error(data);
} else {
$("#dialog-settings-service").html(data)
$( "input[type=checkbox]" ).checkboxradio();
$("#dialog-settings-service").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
title: settings_word + " "+for_word+" " + name,
buttons: [{
text: save_word,
click: function () {
$(this).dialog("close");
serverSettingsSave(id, name, service, $(this));
}
}, {
text: cancel_word,
click: function () {
$(this).dialog("close");
}
}]
});
}
}
});
} | 1 | JavaScript | 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 | safe |
function confirmAjaxAction(action, service, id) {
var cancel_word = $('#translate').attr('data-cancel');
var action_word = $('#translate').attr('data-'+action);
$( "#dialog-confirm" ).dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
title: action_word + " " + id + "?",
buttons: [{
text: action_word,
click: function () {
$(this).dialog("close");
if (service == "haproxy") {
ajaxActionServers(action, id);
if (action == "restart" || action == "reload") {
if (localStorage.getItem('restart')) {
localStorage.removeItem('restart');
$("#apply").css('display', 'none');
}
}
} else if (service == "waf") {
ajaxActionWafServers(action, id)
} else if (service == "nginx") {
ajaxActionNginxServers(action, id)
} else if (service == "keepalived") {
ajaxActionKeepalivedServers(action, id)
} else if (service == "apache") {
ajaxActionApacheServers(action, id)
} else if (service == "waf_nginx") {
ajaxActionWafNginxServers(action, id)
}
}
}, {
text: cancel_word,
click: function() {
$( this ).dialog( "close" );
}
}]
});
} | 1 | JavaScript | 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 | safe |
click: function () {
$(this).dialog("close");
if (service == "haproxy") {
ajaxActionServers(action, id);
if (action == "restart" || action == "reload") {
if (localStorage.getItem('restart')) {
localStorage.removeItem('restart');
$("#apply").css('display', 'none');
}
}
} else if (service == "waf") {
ajaxActionWafServers(action, id)
} else if (service == "nginx") {
ajaxActionNginxServers(action, id)
} else if (service == "keepalived") {
ajaxActionKeepalivedServers(action, id)
} else if (service == "apache") {
ajaxActionApacheServers(action, id)
} else if (service == "waf_nginx") {
ajaxActionWafNginxServers(action, id)
}
} | 1 | JavaScript | 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 | safe |
const exec = (cmd, options, cb) => child.exec(cmd, options, cb)
class GitFn { | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
tag (cb) {
assertVersionValid(this._version)
const cmd = ['git', 'tag', 'v' + this._version].join(' ')
exec(cmd, this._options, cb)
} | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
constructor (version, options) {
this._version = version
this._options = {
cwd: options.dir,
env: process.env,
setsid: false,
stdio: [0, 1, 2]
}
} | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
untag (cb) {
assertVersionValid(this._version)
const cmd = ['git', 'tag', '-d', 'v' + this._version].join(' ')
exec(cmd, this._options, cb)
} | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
commit (cb) {
assertVersionValid(this._version)
const cmd = ['git', 'commit', '-am', '"' + this._version + '"'].join(' ')
exec(cmd, this._options, cb)
} | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
const assertVersionValid = version => {
if (!semver.valid(version)) {
throw new Error('version is invalid')
}
} | 1 | JavaScript | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
function isBackslashEscaped(string: string, pos: number): boolean {
let escaped = false;
for (let i = pos; i >= 0; i--) {
const char = string[i];
if (char !== '\\') {
break;
}
escaped = !escaped;
}
return escaped;
} | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
await this.sequelize.query('select :one as foo, :two as bar', { raw: true, replacements: new Buffer([1]) })
.should.be.rejectedWith(Error, '"replacements" must be an array or a plain object, but received {"type":"Buffer","data":[1]} instead.');
}); | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
minifySql(sql) {
// replace all consecutive whitespaces with a single plain space character
return sql.replace(/\s+/g, ' ')
// remove space before comma
.replace(/ ,/g, ',')
// remove space before )
.replace(/ \)/g, ')') | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
expectsql(query, assertions) {
const expectations = assertions.query || assertions;
let expectation = expectations[Support.sequelize.dialect.name];
const dialect = Support.sequelize.dialect;
if (!expectation) {
if (expectations['default'] !== undefined) {
expectation = expectations['default'];
if (typeof expectation === 'string') {
// replace [...] with the proper quote character for the dialect
// except for ARRAY[...]
expectation = expectation.replace(/(?<!ARRAY)\[([^\]]+)]/g, `${dialect.TICK_CHAR_LEFT}$1${dialect.TICK_CHAR_RIGHT}`);
}
} else {
throw new Error(`Undefined expectation for "${Support.sequelize.dialect.name}"!`);
}
}
if (query instanceof Error) {
expect(query.message).to.equal(expectation.message);
} else {
expect(Support.minifySql(query.query || query)).to.equal(Support.minifySql(expectation));
}
if (assertions.bind) {
const bind = assertions.bind[Support.sequelize.dialect.name] || assertions.bind['default'] || assertions.bind;
expect(query.bind).to.deep.equal(bind);
}
}, | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
module.exports.stubQueryRun = function stubQueryRun() {
let lastExecutedSql;
class FakeQuery {
run(sql) {
lastExecutedSql = sql;
return [];
}
}
sinon.stub(sequelize.dialect, 'Query').get(() => FakeQuery);
sinon.stub(sequelize.connectionManager, 'getConnection').returns({});
sinon.stub(sequelize.connectionManager, 'releaseConnection');
return () => {
return lastExecutedSql;
};
}; | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
run(sql) {
lastExecutedSql = sql;
return [];
} | 1 | JavaScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
usersAPI.generateExport = async (caller, { uid, type }) => {
const validTypes = ['profile', 'posts', 'uploads'];
if (!validTypes.includes(type)) {
throw new Error('[[error:invalid-data]]');
}
const count = await db.incrObjectField('locks', `export:${uid}${type}`);
if (count > 1) {
throw new Error('[[error:already-exporting]]');
}
const child = require('child_process').fork(`./src/user/jobs/export-${type}.js`, [], {
env: process.env,
});
child.send({ uid });
child.on('error', async (err) => {
winston.error(err.stack);
await db.deleteObjectField('locks', `export:${uid}${type}`);
});
child.on('exit', async () => {
await db.deleteObjectField('locks', `export:${uid}${type}`);
const userData = await user.getUserFields(uid, ['username', 'userslug']);
const { displayname } = userData;
const n = await notifications.create({
bodyShort: `[[notifications:${type}-exported, ${displayname}]]`,
path: `/api/user/${userData.userslug}/export/${type}`,
nid: `${type}:export:${uid}`,
from: uid,
});
await notifications.push(n, [caller.uid]);
await events.log({
type: `export:${type}`,
uid: caller.uid,
targetUid: uid,
ip: caller.ip,
});
});
}; | 1 | JavaScript | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 |
async function doExport(socket, data, type) {
sockets.warnDeprecated(socket, 'POST /api/v3/users/:uid/exports/:type');
if (!socket.uid) {
throw new Error('[[error:invalid-uid]]');
}
if (!data || parseInt(data.uid, 10) <= 0) {
throw new Error('[[error:invalid-data]]');
}
await user.isAdminOrSelf(socket.uid, data.uid);
api.users.generateExport(socket, { type, uid: data.uid });
} | 1 | JavaScript | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product 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 product 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 |
sessionId: request.signedCookies ? request.signedCookies[nconf.get('sessionKey')] : null,
request: request,
});
const sessionData = await getSessionAsync(sessionId);
request.session = sessionData;
let uid = 0;
if (sessionData && sessionData.passport && sessionData.passport.user) {
uid = parseInt(sessionData.passport.user, 10);
}
request.uid = uid;
callback(null, uid);
} | 1 | JavaScript | CWE-346 | Origin Validation Error | The product does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | safe |
allowRequest: (req, callback) => {
authorize(req, (err) => {
if (err) {
return callback(err);
}
const csrf = require('../middleware/csrf');
const isValid = csrf.isRequestValid({
session: req.session || {},
query: req._query,
headers: req.headers,
});
callback(null, isValid);
});
},
};
/*
* Restrict socket.io listener to cookie domain. If none is set, infer based on url.
* Production only so you don't get accidentally locked out.
* Can be overridden via config (socket.io:origins)
*/
if (process.env.NODE_ENV !== 'development' || nconf.get('socket.io:cors')) {
const origins = nconf.get('socket.io:origins');
opts.cors = nconf.get('socket.io:cors') || {
origin: origins,
methods: ['GET', 'POST'],
allowedHeaders: ['content-type'],
};
winston.info(`[socket.io] Restricting access to origin: ${origins}`);
}
io.listen(server, opts);
Sockets.server = io;
}; | 1 | JavaScript | CWE-346 | Origin Validation Error | The product does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | safe |
allowRequest: (req, callback) => {
authorize(req, (err) => {
if (err) {
return callback(err);
}
const csrf = require('../middleware/csrf');
const isValid = csrf.isRequestValid({
session: req.session || {},
query: req._query,
headers: req.headers,
});
callback(null, isValid);
});
}, | 1 | JavaScript | CWE-346 | Origin Validation Error | The product does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | safe |
Dottie.transform = function Dottie$transformfunction(object, options) {
if (Array.isArray(object)) {
return object.map(function(o) {
return Dottie.transform(o, options);
});
}
options = options || {};
options.delimiter = options.delimiter || '.';
var pieces
, piecesLength
, piece
, current
, transformed = {}
, key
, keys = Object.keys(object)
, length = keys.length
, i;
for (i = 0; i < length; i++) {
key = keys[i];
if (key.indexOf(options.delimiter) !== -1) {
pieces = key.split(options.delimiter);
if (pieces[0] === '__proto__') break;
piecesLength = pieces.length;
current = transformed;
for (var index = 0; index < piecesLength; index++) {
piece = pieces[index];
if (index != (piecesLength - 1) && !current.hasOwnProperty(piece)) {
current[piece] = {};
}
if (index == (piecesLength - 1)) {
current[piece] = object[key];
}
current = current[piece];
if (current === null) {
break;
}
}
} else {
transformed[key] = object[key];
}
}
return transformed;
}; | 1 | JavaScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product 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 |
Dottie.set = function(object, path, value, options) {
var pieces = Array.isArray(path) ? path : path.split('.'), current = object, piece, length = pieces.length;
if (pieces[0] === '__proto__') return;
if (typeof current !== 'object') {
throw new Error('Parent is not an object.');
}
for (var index = 0; index < length; index++) {
piece = pieces[index];
// Create namespace (object) where none exists.
// If `force === true`, bruteforce the path without throwing errors.
if (
!hasOwnProp.call(current, piece)
|| current[piece] === undefined
|| ((typeof current[piece] !== 'object' || current[piece] === null) && options && options.force === true)) {
current[piece] = {};
}
if (index == (length - 1)) {
// Set final value
current[piece] = value;
} else {
// We do not overwrite existing path pieces by default
if (typeof current[piece] !== 'object' || current[piece] === null) {
throw new Error('Target key "' + piece + '" is not suitable for a nested value. (It is in use as non-object. Set `force` to `true` to override.)');
}
// Traverse next in path
current = current[piece];
}
}
// Is there any case when this is relevant? It's also the last line in the above for-loop
current[piece] = value;
}; | 1 | JavaScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product 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 |
"results in a cookie that is not affected by the attempted prototype pollution": function() {
const pollutedObject = {};
assert(pollutedObject["/notauth"] === undefined);
} | 1 | JavaScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product 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 |
topic: function() {
const jar = new tough.CookieJar(undefined, {
rejectPublicSuffixes: false
});
// try to pollute the prototype
jar.setCookieSync(
"Slonser=polluted; Domain=__proto__; Path=/notauth",
"https://__proto__/admin"
);
jar.setCookieSync(
"Auth=Lol; Domain=google.com; Path=/notauth",
"https://google.com/"
);
this.callback();
}, | 1 | JavaScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product 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 |
CryptoModule.prototype.encrypt = function (data) {
var encrypted = this.defaultCryptor.encrypt(data);
if (!encrypted.metadata)
return encrypted.data;
var headerData = this.getHeaderData(encrypted);
return this.concatArrayBuffer(headerData, encrypted.data);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this.decrypt = function (data, key) {
if (typeof key === 'undefined' && cryptoModule) {
var decrypted = modules.cryptoModule.decrypt(data);
return decrypted instanceof ArrayBuffer ? encode$1(decrypted) : decrypted;
}
else {
return crypto.decrypt(data, key);
}
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: data.slice(header.length),
metadata: metadata,
})];
case 2: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(),
_c)])];
}
}); | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function encode$1(input) {
var base64 = '';
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bytes = new Uint8Array(input);
var byteLength = bytes.byteLength;
var byteRemainder = byteLength % 3;
var mainLength = byteLength - byteRemainder;
var a, b, c, d;
var chunk;
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
d = chunk & 63; // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4; // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '==';
}
else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2; // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return base64;
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.encryptFile = function (key, file, File) {
return __awaiter(this, void 0, void 0, function () {
var bKey, abPlaindata, abCipherdata;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (file.data.byteLength <= 0)
throw new Error('encryption error. empty content');
return [4 /*yield*/, this.getKey(key)];
case 1:
bKey = _a.sent();
return [4 /*yield*/, file.data.arrayBuffer()];
case 2:
abPlaindata = _a.sent();
return [4 /*yield*/, this.encryptArrayBuffer(bKey, abPlaindata)];
case 3:
abCipherdata = _a.sent();
return [2 /*return*/, File.create({
name: file.name,
mimeType: 'application/octet-stream',
data: abCipherdata,
})];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default: new LegacyCryptor({
cipherKey: config.cipherKey,
useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
}),
cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })],
}); | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptorHeader.from = function (id, metadata) {
if (id === CryptorHeader.LEGACY_IDENTIFIER)
return;
return new CryptorHeaderV1(id, metadata.byteLength);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default_1.prototype.setCipherKey = function (val, setup, modules) {
var _a;
this.cipherKey = val;
if (this.cipherKey) {
this.cryptoModule =
(_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs });
if (modules)
modules.cryptoModule = this.cryptoModule;
}
return this;
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function CryptorHeader() {
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: decode$1(this.CryptoJS.AES.encrypt(data, this.encryptedKey, {
iv: this.bufferToWordArray(abIv),
mode: this.CryptoJS.mode.CBC,
}).ciphertext.toString(this.CryptoJS.enc.Base64)), | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get: function () {
return '';
}, | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
LegacyCryptor.prototype.encrypt = function (data) {
var stringData = typeof data === 'string' ? data : new TextDecoder().decode(data);
return {
data: this.cryptor.encrypt(stringData),
metadata: null,
};
};
LegacyCryptor.prototype.decrypt = function (encryptedData) {
var data = typeof encryptedData.data === 'string' ? encryptedData.data : encode$1(encryptedData.data);
return this.cryptor.decrypt(data);
};
LegacyCryptor.prototype.encryptFile = function (file, File) {
var _a;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)];
});
});
};
LegacyCryptor.prototype.decryptFile = function (file, File) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
});
});
};
return LegacyCryptor;
}()); | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.getCryptorFromId = function (id) {
var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; });
if (cryptor) {
return cryptor;
}
throw Error('unknown cryptor error');
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.getCryptor = function (header) {
if (header === '') {
var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; });
if (cryptor)
return cryptor;
throw new Error('unknown cryptor error');
}
else if (header instanceof CryptorHeaderV1) {
return this.getCryptorFromId(header.identifier);
}
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.decryptString = function (key, ciphertext) {
return __awaiter(this, void 0, void 0, function () {
var abCiphertext, abIv, abPayload, abPlaintext;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer;
abIv = abCiphertext.slice(0, 16);
abPayload = abCiphertext.slice(16);
return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload)];
case 1:
abPlaintext = _a.sent();
return [2 /*return*/, WebCryptography.decoder.decode(abPlaintext)];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
LegacyCryptor.prototype.decrypt = function (encryptedData) {
var data = typeof encryptedData.data === 'string' ? encryptedData.data : encode$1(encryptedData.data);
return this.cryptor.decrypt(data);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this.encryptFile = function (key, file) {
if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) {
file = key;
return modules.cryptoModule.encryptFile(file, this.File);
}
return cryptography.encryptFile(key, file, this.File);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.getFileData = function (input) {
if (input instanceof ArrayBuffer) {
return input;
}
if (typeof input === 'string') {
return CryptoModule.encoder.encode(input);
}
throw new Error('Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer');
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
setup.initCryptoModule = function (cryptoConfiguration) {
return new CryptoModule({
default: new LegacyCryptor({
cipherKey: cryptoConfiguration.cipherKey,
useRandomIVs: cryptoConfiguration.useRandomIVs,
}),
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
};
_this = _super.call(this, setup) || this;
if (listenToBrowserNetworkEvents) {
// mount network events.
window.addEventListener('offline', function () {
_this.networkDownDetected();
});
window.addEventListener('online', function () {
_this.networkUpDetected();
});
}
return _this;
}
default_1.CryptoModule = CryptoModule;
return default_1;
}(default_1$3)); | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this.encrypt = function (data, key) {
if (typeof key === 'undefined' && modules.cryptoModule) {
var encrypted = modules.cryptoModule.encrypt(data);
return typeof encrypted === 'string' ? encrypted : encode$1(encrypted);
}
else {
return crypto.encrypt(data, key);
}
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function prepareMessagePayload$1(modules, messagePayload) {
var stringifiedPayload = JSON.stringify(messagePayload);
if (modules.cryptoModule) {
var encrypted = modules.cryptoModule.encrypt(stringifiedPayload);
stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
return stringifiedPayload || '';
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.decrypt = function (encryptedData) {
var iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata));
var data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data));
return AesCbcCryptor.encoder.encode(this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, {
iv: iv,
mode: this.CryptoJS.mode.CBC,
}).toString(this.CryptoJS.enc.Utf8)).buffer;
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: this.cryptor.encrypt(stringData),
metadata: null,
};
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function __processMessage(modules, message) {
if (!modules.cryptoModule)
return message;
try {
var decryptedData = modules.cryptoModule.decrypt(message);
var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData;
return decryptedPayload;
}
catch (e) {
if (console && console.log)
console.log('decryption error', e.message);
return message;
}
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
LegacyCryptor.prototype.encryptFile = function (file, File) {
var _a;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)];
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.legacyCryptoModule = function (config) {
var _a;
return new this({
default: new LegacyCryptor({
cipherKey: config.cipherKey,
useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
}),
cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })],
}); | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.decryptArrayBuffer = function (key, ciphertext) {
return __awaiter(this, void 0, void 0, function () {
var abIv, data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
abIv = ciphertext.slice(0, 16);
if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0)
throw new Error('decryption error: empty content');
return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(WebCryptography.IV_LENGTH))];
case 1:
data = _a.sent();
return [2 /*return*/, data];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.getIv = function () {
return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE));
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: this.concatArrayBuffer(this.getHeaderData(encrypted), encrypted.data),
})];
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptorHeader.tryParse = function (data) {
var encryptedData = new Uint8Array(data);
var sentinel = '';
var version = null;
if (encryptedData.byteLength >= 4) {
sentinel = encryptedData.slice(0, 4);
if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL)
return '';
}
if (encryptedData.byteLength >= 5) {
version = encryptedData[4];
}
else {
throw new Error('decryption error. invalid header version');
}
if (version > CryptorHeader.MAX_VERSION)
throw new Error('unknown cryptor error');
var identifier = '';
var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH;
if (encryptedData.byteLength >= pos) {
identifier = encryptedData.slice(5, pos);
}
else {
throw new Error('decryption error. invalid crypto identifier');
}
var metadataLength = null;
if (encryptedData.byteLength >= pos + 1) {
metadataLength = encryptedData[pos];
}
else {
throw new Error('decryption error. invalid metadata length');
}
pos += 1;
if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) {
metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0);
pos += 2;
}
return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
LegacyCryptor.prototype.decryptFile = function (file, File) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.encrypt = function (data) {
var stringData = typeof data === 'string' ? data : AesCbcCryptor.decoder.decode(data);
if (stringData.length === 0)
throw new Error('encryption error. empty content');
var abIv = this.getIv();
return {
metadata: abIv,
data: decode$1(this.CryptoJS.AES.encrypt(data, this.encryptedKey, {
iv: this.bufferToWordArray(abIv),
mode: this.CryptoJS.mode.CBC,
}).ciphertext.toString(this.CryptoJS.enc.Base64)), | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.concatArrayBuffer = function (ab1, ab2) {
var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength);
tmp.set(new Uint8Array(ab1), 0);
tmp.set(new Uint8Array(ab2), ab1.byteLength);
return tmp.buffer;
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this.setCipherKey = function (key) { return modules.config.setCipherKey(key, setup, modules); }; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.getKey = function () {
return __awaiter(this, void 0, void 0, function () {
var bKey, abHash;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
bKey = AesCbcCryptor.encoder.encode(this.cipherKey);
return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)];
case 1:
abHash = _a.sent();
return [2 /*return*/, crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt'])];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.decryptFile = function (key, file, File) {
return __awaiter(this, void 0, void 0, function () {
var bKey, abCipherdata, abPlaindata;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getKey(key)];
case 1:
bKey = _a.sent();
return [4 /*yield*/, file.data.arrayBuffer()];
case 2:
abCipherdata = _a.sent();
return [4 /*yield*/, this.decryptArrayBuffer(bKey, abCipherdata)];
case 3:
abPlaindata = _a.sent();
return [2 /*return*/, File.create({
name: file.name,
data: abPlaindata,
})];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
set: function (value) {
this._identifier = value;
}, | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.getHeaderData = function (encrypted) {
if (!encrypted.metadata)
return;
var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata);
var headerData = new Uint8Array(header.length);
var pos = 0;
headerData.set(header.data, pos);
pos += header.length - encrypted.metadata.byteLength;
headerData.set(new Uint8Array(encrypted.metadata), pos);
return headerData.buffer;
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.prototype.getAllCryptors = function () {
return __spreadArray([this.defaultCryptor], __read(this.cryptors), false);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
CryptoModule.withDefaultCryptor = function (defaultCryptor) {
return new this({ default: defaultCryptor });
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function CryptoModule(cryptoModuleConfiguration) {
var _a;
this.defaultCryptor = cryptoModuleConfiguration.default;
this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : [];
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function LegacyCryptor(config) {
this.config = config;
this.cryptor = new default_1$a({ config: config });
this.fileCryptor = new WebCryptography();
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
var preparePayload = function (modules, payload) {
var stringifiedPayload = JSON.stringify(payload);
if (modules.cryptoModule) {
var encrypted = modules.cryptoModule.encrypt(stringifiedPayload);
stringifiedPayload = typeof encrypted === 'string' ? encrypted : encode$1(encrypted);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
return stringifiedPayload || '';
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.encryptFileData = function (data) {
return __awaiter(this, void 0, void 0, function () {
var key, iv;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.getKey()];
case 1:
key = _b.sent();
iv = this.getIv();
_a = {};
return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: iv }, key, data)];
case 2: return [2 /*return*/, (_a.data = _b.sent(),
_a.metadata = iv,
_a)];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.bufferToWordArray = function (b) {
var wa = [];
var i;
for (i = 0; i < b.length; i += 1) {
wa[(i / 4) | 0] |= b[i] << (24 - 8 * i);
}
return this.CryptoJS.lib.WordArray.create(wa, b.length);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: encryptedData.slice(header.length),
metadata: metadata,
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default_1.prototype.getVersion = function () {
return '7.4.0';
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this.decryptFile = function (key, file) {
if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) {
file = key;
return modules.cryptoModule.decryptFile(file, this.File);
}
return cryptography.decryptFile(key, file, this.File);
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
AesCbcCryptor.prototype.decryptFileData = function (encryptedData) {
return __awaiter(this, void 0, void 0, function () {
var key;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getKey()];
case 1:
key = _a.sent();
return [2 /*return*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function AesCbcCryptor(configuration) {
this.cipherKey = configuration.cipherKey;
this.CryptoJS = hmacSha256;
this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey);
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function CryptorHeaderV1(id, metadataLength) {
this._identifier = id;
this._metadataLength = metadataLength;
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default: new LegacyCryptor({
cipherKey: cryptoConfiguration.cipherKey,
useRandomIVs: cryptoConfiguration.useRandomIVs,
}),
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
};
_this = _super.call(this, setup) || this;
if (listenToBrowserNetworkEvents) {
// mount network events.
window.addEventListener('offline', function () {
_this.networkDownDetected();
});
window.addEventListener('online', function () {
_this.networkUpDetected();
});
}
return _this;
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.encryptString = function (key, plaintext) {
return __awaiter(this, void 0, void 0, function () {
var abIv, abPlaintext, abPayload, ciphertext;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
abIv = crypto.getRandomValues(new Uint8Array(16));
abPlaintext = WebCryptography.encoder.encode(plaintext).buffer;
return [4 /*yield*/, crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext)];
case 1:
abPayload = _a.sent();
ciphertext = concatArrayBuffer(abIv.buffer, abPayload);
return [2 /*return*/, WebCryptography.decoder.decode(ciphertext)];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
WebCryptography.prototype.getKey = function (key) {
return __awaiter(this, void 0, void 0, function () {
var digest, hashHex, abKey;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key))];
case 1:
digest = _a.sent();
hashHex = Array.from(new Uint8Array(digest))
.map(function (b) { return b.toString(16).padStart(2, '0'); })
.join('');
abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer;
return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])];
}
});
});
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function __processMessage$1(modules, message) {
if (!modules.cryptoModule)
return message;
try {
var decryptedData = modules.cryptoModule.decrypt(message);
var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData;
return decryptedPayload;
}
catch (e) {
if (console && console.log)
console.log('decryption error', e.message);
return message;
}
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function stringToArrayBuffer(str) {
var buf = new ArrayBuffer(str.length * 2);
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function encode(input) {
var base64 = '';
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bytes = new Uint8Array(input);
var byteLength = bytes.byteLength;
var byteRemainder = byteLength % 3;
var mainLength = byteLength - byteRemainder;
var a, b, c, d;
var chunk;
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
d = chunk & 63; // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4; // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '==';
}
else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2; // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return base64;
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default_1.prototype.setCipherKey = function (val, setup, modules) {
var _a;
this.cipherKey = val;
if (this.cipherKey) {
this.cryptoModule =
(_a = setup.cryptoModule) !== null && _a !== void 0 ? _a : setup.initCryptoModule({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs });
if (modules)
modules.cryptoModule = this.cryptoModule;
}
return this;
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default_1.prototype.getVersion = function () {
return '7.4.0';
}; | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function default_1(_a) {
var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule;
this._listenerManager = listenerManager;
this._config = config;
this._leaveEndpoint = leaveEndpoint;
this._heartbeatEndpoint = heartbeatEndpoint;
this._setStateEndpoint = setStateEndpoint;
this._subscribeEndpoint = subscribeEndpoint;
this._getFileUrl = getFileUrl;
this._crypto = crypto;
this._cryptoModule = cryptoModule;
this._channels = {};
this._presenceChannels = {};
this._heartbeatChannels = {};
this._heartbeatChannelGroups = {};
this._channelGroups = {};
this._presenceChannelGroups = {};
this._pendingChannelSubscriptions = [];
this._pendingChannelGroupSubscriptions = [];
this._currentTimetoken = 0;
this._lastTimetoken = 0;
this._storedTimetoken = null;
this._subscriptionStatusAnnounced = false;
this._isOnline = true;
this._reconnectionManager = new reconnection_manager_1.default({ timeEndpoint: timeEndpoint });
this._dedupingManager = new deduping_manager_1.default({ config: config });
if (this._cryptoModule)
this._decoder = new TextDecoder();
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
function __processMessage(modules, message) {
if (!modules.cryptoModule)
return message;
try {
var decryptedData = modules.cryptoModule.decrypt(message);
var decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData;
return decryptedPayload;
}
catch (e) {
if (console && console.log)
console.log('decryption error', e.message);
return message;
}
} | 1 | JavaScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.