Skip to content
Open
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
29 changes: 20 additions & 9 deletions apps/web/src/app/api/ses_callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { env } from "~/env";
import { db } from "~/server/db";
import { logger } from "~/server/logger/log";
import { parseSesHook, SesHookParser } from "~/server/service/ses-hook-parser";
import { SesHookParser } from "~/server/service/ses-hook-parser";
import { SesSettingsService } from "~/server/service/ses-settings-service";
import { SnsNotificationMessage } from "~/types/aws-types";
import { verifySnsMessageSignature } from "~/server/aws/sns-message-validator";

export const dynamic = "force-dynamic";

Expand Down Expand Up @@ -34,7 +35,7 @@ export async function POST(req: Request) {
message = JSON.parse(data.Message || "{}");
const status = await SesHookParser.queue({
event: message,
messageId: data.MessageId,
messageId: data.MessageId
});
if (!status) {
return Response.json({ data: "Error in parsing hook" });
Expand All @@ -52,14 +53,14 @@ export async function POST(req: Request) {
*/
async function handleSubscription(message: any) {
await fetch(message.SubscribeURL, {
method: "GET",
method: "GET"
});

const topicArn = message.TopicArn as string;
const setting = await db.sesSetting.findFirst({
where: {
topicArn,
},
topicArn
}
});

if (!setting) {
Expand All @@ -68,11 +69,11 @@ async function handleSubscription(message: any) {

await db.sesSetting.update({
where: {
id: setting?.id,
id: setting?.id
},
data: {
callbackSuccess: true,
},
callbackSuccess: true
}
});

SesSettingsService.invalidateCache();
Expand All @@ -81,7 +82,7 @@ async function handleSubscription(message: any) {
}

/**
* A simple check to ensure that the event is from the correct topic
* A simple check to ensure that the event is from the correct topic and has a valid signature
*/
async function checkEventValidity(message: SnsNotificationMessage) {
if (env.NODE_ENV === "development") {
Expand All @@ -95,5 +96,15 @@ async function checkEventValidity(message: SnsNotificationMessage) {
return false;
}

// Verify the SNS message signature
const isSignatureValid = await verifySnsMessageSignature(message);
if (!isSignatureValid) {
logger.error({
topicArn: TopicArn,
msg: "Rejected SNS message with invalid signature"
});
return false;
}

return true;
}
183 changes: 183 additions & 0 deletions apps/web/src/server/aws/sns-message-validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { createVerify } from "crypto";
import https from "https";
import { SnsNotificationMessage } from "~/types/aws-types";

/**
* Extracts the region from an SNS TopicArn.
* TopicArn format: arn:aws:sns:REGION:ACCOUNT-ID:TOPIC-NAME
*/
function extractRegionFromTopicArn(topicArn: string): string | null {
const parts = topicArn.split(":");
if (parts.length >= 4 && parts[0] === "arn" && parts[2] === "sns") {
return parts[3];
}
return null;
}

/**
* Validates that the signing certificate URL is from an AWS SNS host in the correct region.
* Prevents SSRF attacks by:
* 1. Deriving the expected region from TopicArn
* 2. Validating the certificate URL hostname matches that region
* 3. Enforcing HTTPS protocol
* 4. Verifying the path contains expected SNS certificate path pattern
*/
function isValidSnsSigningCertificateUrl(
url: string,
topicArn: string
): boolean {
try {
const urlObj = new URL(url);

// Extract region from TopicArn
const region = extractRegionFromTopicArn(topicArn);
if (!region) {
return false;
}

// Build expected hostname patterns for this region
const expectedHostnames = [
`sns.${region}.amazonaws.com`,
// Some regions might use the regional endpoint
`sns.amazonaws.com`
];

// Check if the certificate URL hostname matches expected patterns
const isExpectedHost = expectedHostnames.some(
(host) => urlObj.hostname === host
);

// Ensure it's HTTPS and has the expected SNS certificate path format
return (
urlObj.protocol === "https:" &&
(urlObj.pathname.includes("/sns/") || urlObj.pathname.endsWith(".pem")) &&
isExpectedHost
);
} catch {
return false;
}
}

/**
* Builds the canonical string to sign for SNS message signature verification.
* AWS SNS signs a string where every field is terminated by a newline, including the last one.
* Field order depends on message type:
* - Notification: Message, MessageId, Subject, Timestamp, TopicArn, Type
* - SubscriptionConfirmation: Message, MessageId, SubscribeURL, Timestamp, Token, TopicArn, Type
* Format: field1\nvalue1\nfield2\nvalue2\n...\n
*/
export function buildSnsStringToSign(message: SnsNotificationMessage): string {
let fields: string[];
const values: Record<string, string | undefined> = {};

if (message.Type === "SubscriptionConfirmation") {
// SubscriptionConfirmation message field order
fields = [
"Message",
"MessageId",
"SubscribeURL",
"Timestamp",
"Token",
"TopicArn",
"Type"
];
values.Message = message.Message;
values.MessageId = message.MessageId;
values.SubscribeURL = message.SubscribeURL;
values.Timestamp = message.Timestamp;
values.Token = message.Token;
values.TopicArn = message.TopicArn;
values.Type = message.Type;
} else {
// Notification message field order (default)
fields = [
"Message",
"MessageId",
"Subject",
"Timestamp",
"TopicArn",
"Type"
];
values.Message = message.Message;
values.MessageId = message.MessageId;
values.Subject = message.Subject;
values.Timestamp = message.Timestamp;
values.TopicArn = message.TopicArn;
values.Type = message.Type;
}

return fields
.filter((field) => values[field] !== undefined)
.map((field) => `${field}\n${values[field] as string}\n`)
.join("");
}

/**
* Fetches the certificate from the SigningCertURL after validation.
* Validates that the URL is from an AWS SNS host in the same region as TopicArn before fetching.
*/
export async function getCertificate(
signingCertUrl: string,
topicArn: string
): Promise<string> {
// Validate the URL before making any network request
if (!isValidSnsSigningCertificateUrl(signingCertUrl, topicArn)) {
const region = extractRegionFromTopicArn(topicArn);
throw new Error(
`Invalid SNS signing certificate URL: must be from aws SNS host in region ${region}`
);
}

return new Promise((resolve, reject) => {
https
.get(signingCertUrl, (res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => resolve(data));
})
.on("error", reject);
});
}

/**
* Determines the hash algorithm based on SignatureVersion.
* Version 1 uses RSA-SHA1, Version 2 uses RSA-SHA256.
*/
function getSignatureAlgorithm(signatureVersion: string): string {
switch (signatureVersion) {
case "1":
return "RSA-SHA1";
case "2":
return "RSA-SHA256";
default:
throw new Error(
`Unsupported SNS SignatureVersion: ${signatureVersion}. Supported versions are 1 (RSA-SHA1) and 2 (RSA-SHA256)`
);
}
}

/**
* Verifies the SNS message signature using the appropriate algorithm based on SignatureVersion.
*/
export async function verifySnsMessageSignature(
message: SnsNotificationMessage
): Promise<boolean> {
try {
// Validate signature version before proceeding
const algorithm = getSignatureAlgorithm(message.SignatureVersion);

const stringToSign = buildSnsStringToSign(message);
const certificate = await getCertificate(
message.SigningCertURL,
message.TopicArn
);

const verifier = createVerify(algorithm);
verifier.update(stringToSign);

return verifier.verify(certificate, message.Signature, "base64");
} catch (error) {
console.error("Error verifying SNS message signature:", error);
return false;
}
}
Loading