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

fix(middleware-ssec): ssecMiddleware with strict base64 validation #5875

Merged
merged 3 commits into from
Mar 18, 2024
Merged
Changes from 1 commit
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
19 changes: 17 additions & 2 deletions packages/middleware-ssec/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ export function ssecMiddleware(options: PreviouslyResolved): InitializeMiddlewar
if (value) {
let valueForHash: Uint8Array;
if (typeof value === "string") {
const isBase64Encoded = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
if (isBase64Encoded) {
if (isValidBase64(value)) {
valueForHash = options.base64Decoder(value);
} else {
valueForHash = options.utf8Decoder(value);
Expand Down Expand Up @@ -78,3 +77,19 @@ export const getSsecPlugin = (config: PreviouslyResolved): Pluggable<any, any> =
clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions);
},
});

function isValidBase64(str: string) {
RanVaknin marked this conversation as resolved.
Show resolved Hide resolved
const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;

if (!base64Regex.test(str)) return false;

try {
const decodedBytes = Buffer.from(str, "base64");
RanVaknin marked this conversation as resolved.
Show resolved Hide resolved
if (decodedBytes.length !== 32) return false;

const reEncoded = decodedBytes.toString("base64");
return str === reEncoded;
} catch {
return false;
}
}
Loading