Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid injected code execution #98

Merged
merged 1 commit into from Dec 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/djv.js
Expand Up @@ -66,7 +66,8 @@ Object.assign(Environment.prototype, {
* @returns {string} error - undefined if it is valid
*/
validate(name, object) {
return this.resolve(name).fn(object);
const foundSchema = this.resolve(name);
return foundSchema.fn(object);
},

/**
Expand Down
13 changes: 11 additions & 2 deletions lib/utils/template.js
Expand Up @@ -4,6 +4,15 @@
* Defines a small templater functionality for creating functions body.
*/

function sanitizeString(str) {
if (typeof str !== 'string') {
return str;
}

const sanitzedStr = String.prototype.replace.call(str, /[^a-z0-9áéíóúñü .,_-]/gim, '');
return String.prototype.trim.call(sanitzedStr);
}

/**
* @name template
* @type function
Expand All @@ -21,7 +30,7 @@ function template(state, options) {
tpl.lines.push(
expression
.replace(/%i/g, () => 'i')
.replace(/\$(\d)/g, (match, index) => `${args[index - 1]}`)
.replace(/\$(\d)/g, (match, index) => `${sanitizeString(args[index - 1])}`)
.replace(/(%[sd])/g, () => {
if (args.length) {
last = args.shift();
Expand All @@ -45,7 +54,7 @@ function template(state, options) {
path
.replace(/\[i([0-9]*)\]/ig, '/items')
.replace(/\['([^']+)'\]/ig, '/properties/$1')
}/${errorType}`;
}/${errorType}`;

return `return {
keyword: '${errorType}',
Expand Down
20 changes: 20 additions & 0 deletions test/issues/vulnerability-exec-file-from-schema.js
@@ -0,0 +1,20 @@
/*
If an attacker can control the schema file, it could run arbitrary JavaScript code on the victim machine.
This is demonstrated by the following POC:
const djv = require('djv');
const env = new djv();
const evilSchema = JSON.parse('{"common":{"type":"array", "minItems":"process.mainModule.require(`child_process`).execSync(`touch HACKED`)"}}')
env.addSchema('test', evilSchema);
env.validate('test#/common', { type: 'custom' });
*/
const assert = require('assert');
const djv = require('../../');

describe('Code execution injection', () => {
it('should be avoided', () => {
const env = new djv();
const evilSchema = JSON.parse('{"common":{"type":"array", "minItems":"process.mainModule.require(`child_process`).execSync(`touch HACKED`)"}}')
env.addSchema('test', evilSchema);
assert.throws(() => env.validate('test#/common', { type: 'custom' }))
});
});