Skip to content

Commit fd24894

Browse files
committed
Fix code injection vulnerability via malicious field names and encoding names
1 parent ff4ab71 commit fd24894

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

lib/binary_parser.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,30 @@ export class Parser {
292292
return new Parser();
293293
}
294294

295+
private sanitizeFieldName(name: string): string {
296+
if (name && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
297+
throw new Error(`Invalid field name: ${name}`);
298+
}
299+
return name;
300+
}
301+
302+
private sanitizeEncoding(encoding: string): string {
303+
const allowed = [
304+
"utf8",
305+
"utf-8",
306+
"ascii",
307+
"hex",
308+
"base64",
309+
"base64url",
310+
"latin1",
311+
"binary",
312+
];
313+
if (!allowed.includes(encoding.toLowerCase())) {
314+
throw new Error(`Invalid encoding: ${encoding}`);
315+
}
316+
return encoding;
317+
}
318+
295319
private primitiveGenerateN(type: PrimitiveTypes, ctx: Context) {
296320
const typeName = PRIMITIVE_NAMES[type];
297321
const littleEndian = PRIMITIVE_LITTLE_ENDIANS[type];
@@ -593,6 +617,7 @@ export class Parser {
593617
}
594618

595619
options.encoding = options.encoding || "utf8";
620+
this.sanitizeEncoding(options.encoding);
596621

597622
return this.setNextParser("string", varName, options);
598623
}
@@ -914,7 +939,7 @@ export class Parser {
914939
const parser = new Parser();
915940

916941
parser.type = type;
917-
parser.varName = varName;
942+
parser.varName = this.sanitizeFieldName(varName);
918943
parser.options = options;
919944
parser.endian = this.endian;
920945

test/primitive_parser.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,29 @@ function primitiveParserTests(
441441
deepStrictEqual(bufferParser.parse(buffer), { buf: buffer });
442442
});
443443
});
444+
445+
describe("Security", () => {
446+
it("should throw an error on invalid field name", () => {
447+
try {
448+
new Parser().uint8('a; console.log("INJECTED CODE EXECUTED"); //');
449+
throw new Error("Should have thrown error");
450+
} catch (e: any) {
451+
ok(e.message.includes("Invalid field name"));
452+
}
453+
});
454+
455+
it("should throw an error on invalid encoding name", () => {
456+
try {
457+
new Parser().string("s", {
458+
length: 1,
459+
encoding: "utf8'); console.log('INJECTED ENCODING EXECUTED'); //",
460+
});
461+
throw new Error("Should have thrown error");
462+
} catch (e: any) {
463+
ok(e.message.includes("Invalid encoding"));
464+
}
465+
});
466+
});
444467
});
445468
}
446469

0 commit comments

Comments
 (0)