Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,30 @@ export class Parser {
return new Parser();
}

private sanitizeFieldName(name: string): string {
if (name && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
throw new Error(`Invalid field name: ${name}`);
}
return name;
}

private sanitizeEncoding(encoding: string): string {
const allowed = [
"utf8",
"utf-8",
"ascii",
"hex",
"base64",
"base64url",
"latin1",
"binary",
];
if (!allowed.includes(encoding.toLowerCase())) {
throw new Error(`Invalid encoding: ${encoding}`);
}
return encoding;
}

private primitiveGenerateN(type: PrimitiveTypes, ctx: Context) {
const typeName = PRIMITIVE_NAMES[type];
const littleEndian = PRIMITIVE_LITTLE_ENDIANS[type];
Expand Down Expand Up @@ -593,6 +617,7 @@ export class Parser {
}

options.encoding = options.encoding || "utf8";
this.sanitizeEncoding(options.encoding);

return this.setNextParser("string", varName, options);
}
Expand Down Expand Up @@ -914,7 +939,7 @@ export class Parser {
const parser = new Parser();

parser.type = type;
parser.varName = varName;
parser.varName = this.sanitizeFieldName(varName);
parser.options = options;
parser.endian = this.endian;

Expand Down
23 changes: 23 additions & 0 deletions test/primitive_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,29 @@ function primitiveParserTests(
deepStrictEqual(bufferParser.parse(buffer), { buf: buffer });
});
});

describe("Security", () => {
it("should throw an error on invalid field name", () => {
try {
new Parser().uint8('a; console.log("INJECTED CODE EXECUTED"); //');
throw new Error("Should have thrown error");
} catch (e: any) {
ok(e.message.includes("Invalid field name"));
}
});

it("should throw an error on invalid encoding name", () => {
try {
new Parser().string("s", {
length: 1,
encoding: "utf8'); console.log('INJECTED ENCODING EXECUTED'); //",
});
throw new Error("Should have thrown error");
} catch (e: any) {
ok(e.message.includes("Invalid encoding"));
}
});
});
});
}

Expand Down
Loading