Amazon SNS: Verify HTTPS Notifications and Detect Batch Duplicates
See more Amazon SNS Examples
Verify an SNS HTTPS delivery envelope before processing it. Delivery signatures use RSA, not the SigV4 used to call the SNS API.
Reads a private file shaped as {"messages":[SNS-envelope,...]}. Verifies Notifications and both confirmation types, including optional Subject, exact LF canonicalization, RSA/SHA-256 signature version 2, and SHA-1 version 1 compatibility. It pins an expected topic and regional HTTPS certificate source, disallows redirects and unusual certificate paths, validates chain signatures/root trust/validity dates, and checks a configurable timestamp window. Provision required intermediates and approved roots; never accept roots from an incoming envelope. The checks are not an online certificate-revocation service or a general-purpose PKIX policy engine.
Duplicate detection uses (TopicArn, MessageId) and lasts only within this batch; the example performs no business side effects. For an HTTP receiver, enforce request-size limits before JSON parsing, persist a unique inbox key and accepted payload transactionally, acknowledge only durable acceptance, and process idempotently. Choose timestamp retention to cover the intended delivery/replay window; the illustrative 24-hour bound may reject deliberately replayed old messages. Confirm only subscriptions the application requested, using the verified Token and a configured API endpoint; it never follows SubscribeURL or automatically resubscribes.
AWS signature verification guidance
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoHashtable.h>
#import <CkoDateTime.h>
#import <CkoHttp.h>
#import <CkoCert.h>
#import <CkoCertChain.h>
#import <CkoTrustedRoots.h>
#import <CkoPublicKey.h>
#import <CkoRsa.h>
BOOL success = NO;
CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.
CkoJsonObject *batch = [[CkoJsonObject alloc] init];
batch.Strict = YES;
success = [batch LoadFile: @"qa_data/aws/sns_notifications.json"];
if (success != YES) {
NSLog(@"%@",@"Could not parse notification envelopes.");
return;
}
if ([[batch JsonTypeOf: @"messages"] intValue] != 4) {
NSLog(@"%@",@"Expected a messages array.");
return;
}
int count = [[batch SizeOfArray: @"messages"] intValue];
if ((count < 1) || (count > 100)) {
NSLog(@"%@",@"Use 1 to 100 envelopes per verification batch.");
return;
}
NSString *allowedTopic = @"arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
NSString *certPrefix = @"https://sns.us-west-2.amazonaws.com/SimpleNotificationService-";
// Pin the expected topic and matching regional SNS host in application configuration.
CkoHashtable *seenMessages = [[CkoHashtable alloc] init];
CkoJsonObject *envelope = [[CkoJsonObject alloc] init];
CkoDateTime *now = [[CkoDateTime alloc] init];
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read current time.");
return;
}
int envelopeIndex = 0;
while ((envelopeIndex < count)) {
batch.I = [NSNumber numberWithInt: envelopeIndex];
success = [batch ObjectOf2: @"messages[i]" jsonObj: envelope];
if (success != YES) {
NSLog(@"%@",@"Expected a JSON object envelope.");
return;
}
CkoHashtable *fieldNames = [[CkoHashtable alloc] init];
int fieldIndex = 0;
while ((fieldIndex < [envelope.Size intValue])) {
NSString *fieldName = [envelope NameAt: [NSNumber numberWithInt: fieldIndex]];
if ([fieldNames Contains: fieldName] == YES) {
NSLog(@"%@",@"Duplicate envelope field.");
return;
}
success = [fieldNames AddStr: fieldName value: @"seen"];
if (success != YES) {
NSLog(@"%@",@"Could not track envelope fields.");
return;
}
fieldIndex = fieldIndex + 1;
}
[stringCompare SetString: [envelope StringOf: @"Type"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"Type"] intValue] != 1) || (stringMatch1 == YES)) {
NSLog(@"%@",@"Missing or invalid Type.");
return;
}
[stringCompare SetString: [envelope StringOf: @"MessageId"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"MessageId"] intValue] != 1) || (stringMatch2 == YES)) {
NSLog(@"%@",@"Missing or invalid MessageId.");
return;
}
[stringCompare SetString: [envelope StringOf: @"Message"]];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"Message"] intValue] != 1) || (stringMatch3 == YES)) {
NSLog(@"%@",@"Missing or invalid Message.");
return;
}
[stringCompare SetString: [envelope StringOf: @"Timestamp"]];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"Timestamp"] intValue] != 1) || (stringMatch4 == YES)) {
NSLog(@"%@",@"Missing or invalid Timestamp.");
return;
}
[stringCompare SetString: [envelope StringOf: @"TopicArn"]];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"TopicArn"] intValue] != 1) || (stringMatch5 == YES)) {
NSLog(@"%@",@"Missing or invalid TopicArn.");
return;
}
[stringCompare SetString: [envelope StringOf: @"SignatureVersion"]];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"SignatureVersion"] intValue] != 1) || (stringMatch6 == YES)) {
NSLog(@"%@",@"Missing or invalid SignatureVersion.");
return;
}
[stringCompare SetString: [envelope StringOf: @"Signature"]];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"Signature"] intValue] != 1) || (stringMatch7 == YES)) {
NSLog(@"%@",@"Missing or invalid Signature.");
return;
}
[stringCompare SetString: [envelope StringOf: @"SigningCertURL"]];
BOOL stringMatch8 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"SigningCertURL"] intValue] != 1) || (stringMatch8 == YES)) {
NSLog(@"%@",@"Missing or invalid SigningCertURL.");
return;
}
NSString *messageType = [envelope StringOf: @"Type"];
[stringCompare SetString: messageType];
BOOL stringMatch9 = [stringCompare ContentsEqual: @"Notification" caseSensitive: YES];
[stringCompare SetString: messageType];
BOOL stringMatch10 = [stringCompare ContentsEqual: @"SubscriptionConfirmation" caseSensitive: YES];
[stringCompare SetString: messageType];
BOOL stringMatch11 = [stringCompare ContentsEqual: @"UnsubscribeConfirmation" caseSensitive: YES];
if ((stringMatch9 != YES) && (stringMatch10 != YES) && (stringMatch11 != YES)) {
NSLog(@"%@",@"Unsupported SNS message type.");
return;
}
[stringCompare SetString: [envelope StringOf: @"TopicArn"]];
BOOL stringMatch12 = [stringCompare ContentsEqual: allowedTopic caseSensitive: YES];
if (stringMatch12 != YES) {
NSLog(@"%@",@"Unexpected SNS topic.");
return;
}
NSString *signatureVersion = [envelope StringOf: @"SignatureVersion"];
[stringCompare SetString: signatureVersion];
BOOL stringMatch13 = [stringCompare ContentsEqual: @"1" caseSensitive: YES];
[stringCompare SetString: signatureVersion];
BOOL stringMatch14 = [stringCompare ContentsEqual: @"2" caseSensitive: YES];
if ((stringMatch13 != YES) && (stringMatch14 != YES)) {
NSLog(@"%@",@"Unsupported delivery signature version.");
return;
}
NSString *hashAlgorithm = @"sha256";
[stringCompare SetString: signatureVersion];
BOOL stringMatch15 = [stringCompare ContentsEqual: @"1" caseSensitive: YES];
if (stringMatch15 == YES) {
hashAlgorithm = @"sha1";
}
[stringCompare SetString: messageType];
BOOL stringMatch16 = [stringCompare ContentsEqual: @"Notification" caseSensitive: YES];
if (stringMatch16 != YES) {
[stringCompare SetString: [envelope StringOf: @"SubscribeURL"]];
BOOL stringMatch17 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
[stringCompare SetString: [envelope StringOf: @"Token"]];
BOOL stringMatch18 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[envelope JsonTypeOf: @"SubscribeURL"] intValue] != 1) || (stringMatch17 == YES) || ([[envelope JsonTypeOf: @"Token"] intValue] != 1) || (stringMatch18 == YES)) {
NSLog(@"%@",@"Confirmation envelope is missing fields.");
return;
}
}
if ([envelope HasMember: @"Subject"] == YES) {
if ([[envelope JsonTypeOf: @"Subject"] intValue] != 1) {
NSLog(@"%@",@"Subject must be a string when present.");
return;
}
}
CkoDateTime *timestamp = [[CkoDateTime alloc] init];
success = [timestamp SetFromTimestamp: [envelope StringOf: @"Timestamp"]];
if (success != YES) {
NSLog(@"%@",@"Invalid notification timestamp.");
return;
}
int ageSeconds = [[now DiffSeconds: timestamp] intValue];
if ((ageSeconds < -300) || (ageSeconds > 86400)) {
NSLog(@"%@",@"Notification outside the configured 24-hour age / 5-minute clock-skew window.");
return;
}
CkoStringBuilder *certUrl = [[CkoStringBuilder alloc] init];
[certUrl Append: [envelope StringOf: @"SigningCertURL"]];
CkoStringBuilder *prefix = [[CkoStringBuilder alloc] init];
[prefix Append: certPrefix];
if (([certUrl StartsWith: certPrefix caseSensitive: YES] != YES) || ([certUrl EndsWith: @".pem" caseSensitive: YES] != YES) || ([certUrl.Length intValue] <= [prefix.Length intValue] + 4)) {
NSLog(@"%@",@"Untrusted signing-certificate URL.");
return;
}
// Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
// userinfo, alternate port, path traversal, or redirect destination.
CkoStringBuilder *filenameChars = [[CkoStringBuilder alloc] init];
[filenameChars Append: @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"];
int charIndex = [prefix.Length intValue];
while ((charIndex < [certUrl.Length intValue] - 4)) {
if ([filenameChars Contains: [certUrl GetRange: [NSNumber numberWithInt: charIndex] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid signing-certificate filename.");
return;
}
charIndex = charIndex + 1;
}
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:30];
unsigned long maxCertBytes = 65536;
http.MaxResponseSize = [NSNumber numberWithUnsignedInt: maxCertBytes];
http.VerboseLogging = NO;
NSString *certPem = [http QuickGetStr: [certUrl GetAsString]];
if ((http.LastMethodSuccess != YES) || ([http.LastStatus intValue] != 200)) {
NSLog(@"%@",@"Could not retrieve the certificate securely from the pinned SNS endpoint.");
return;
}
CkoCert *signingCert = [[CkoCert alloc] init];
success = [signingCert LoadPem: certPem];
if (success != YES) {
NSLog(@"%@",@"Invalid signing certificate.");
return;
}
CkoCertChain *chain = [[CkoCertChain alloc] init];
success = [signingCert BuildCertChain: chain];
if (success != YES) {
NSLog(@"%@",@"Could not build signing-certificate chain.");
return;
}
if (chain.ReachesRoot != YES) {
NSLog(@"%@",@"Incomplete signing-certificate chain; provision trusted intermediates.");
return;
}
CkoTrustedRoots *roots = [[CkoTrustedRoots alloc] init];
roots.TrustSystemCaRoots = YES;
if ([chain IsRootTrusted: roots] != YES) {
NSLog(@"%@",@"Untrusted signing-certificate root.");
return;
}
success = [chain VerifyCertSignatures];
if (success != YES) {
NSLog(@"%@",@"Invalid certificate-chain signatures.");
return;
}
int certIndex = 0;
CkoCert *chainCert = [[CkoCert alloc] init];
while ((certIndex < [chain.NumCerts intValue])) {
success = [chain CertAt: [NSNumber numberWithInt: certIndex] cert: chainCert];
if (success != YES) {
NSLog(@"%@",@"Could not read chain certificate.");
return;
}
CkoDateTime *validFrom = [[CkoDateTime alloc] init];
CkoDateTime *validTo = [[CkoDateTime alloc] init];
success = [validFrom SetFromRfc822: chainCert.ValidFromStr];
if (success != YES) {
NSLog(@"%@",@"Invalid certificate validity start.");
return;
}
success = [validTo SetFromRfc822: chainCert.ValidToStr];
if (success != YES) {
NSLog(@"%@",@"Invalid certificate validity end.");
return;
}
if (([[now DiffSeconds: validFrom] intValue] < 0) || ([[now DiffSeconds: validTo] intValue] > 0)) {
NSLog(@"%@",@"Certificate outside its validity period.");
return;
}
certIndex = certIndex + 1;
}
CkoStringBuilder *canonical = [[CkoStringBuilder alloc] init];
[canonical AppendLine: @"Message" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"Message"] crlf: NO];
[canonical AppendLine: @"MessageId" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"MessageId"] crlf: NO];
[stringCompare SetString: messageType];
BOOL stringMatch19 = [stringCompare ContentsEqual: @"Notification" caseSensitive: YES];
if (stringMatch19 == YES) {
if ([envelope HasMember: @"Subject"] == YES) {
[canonical AppendLine: @"Subject" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"Subject"] crlf: NO];
}
}
else {
[canonical AppendLine: @"SubscribeURL" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"SubscribeURL"] crlf: NO];
}
[canonical AppendLine: @"Timestamp" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"Timestamp"] crlf: NO];
[stringCompare SetString: messageType];
BOOL stringMatch20 = [stringCompare ContentsEqual: @"Notification" caseSensitive: YES];
if (stringMatch20 != YES) {
[canonical AppendLine: @"Token" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"Token"] crlf: NO];
}
[canonical AppendLine: @"TopicArn" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"TopicArn"] crlf: NO];
[canonical AppendLine: @"Type" crlf: NO];
[canonical AppendLine: [envelope StringOf: @"Type"] crlf: NO];
CkoPublicKey *publicKey = [[CkoPublicKey alloc] init];
success = [signingCert GetPublicKey: publicKey];
if (success != YES) {
NSLog(@"%@",@"Could not extract signing public key.");
return;
}
CkoRsa *rsa = [[CkoRsa alloc] init];
rsa.Charset = @"utf-8";
rsa.EncodingMode = @"base64";
rsa.LittleEndian = NO;
success = [rsa UsePublicKey: publicKey];
if (success != YES) {
NSLog(@"%@",@"Could not configure verification key.");
return;
}
success = [rsa VerifyStringENC: [canonical GetAsString] hashAlg: hashAlgorithm sig: [envelope StringOf: @"Signature"]];
if (success != YES) {
NSLog(@"%@",@"SNS delivery signature is invalid.");
return;
}
// Use a JSON-encoded composite key to avoid ambiguous concatenation.
CkoJsonObject *identity = [[CkoJsonObject alloc] init];
success = [identity UpdateString: @"topic" value: allowedTopic];
if (success != YES) {
NSLog(@"%@",@"Could not form duplicate key.");
return;
}
success = [identity UpdateString: @"id" value: [envelope StringOf: @"MessageId"]];
if (success != YES) {
NSLog(@"%@",@"Could not form duplicate key.");
return;
}
NSString *duplicateKey = [identity Emit];
if ([seenMessages Contains: duplicateKey] == YES) {
NSLog(@"%@%@",@"Verified duplicate skipped: ",[envelope StringOf: @"MessageId"]);
}
else {
success = [seenMessages AddStr: duplicateKey value: @"verified"];
if (success != YES) {
NSLog(@"%@",@"Could not track duplicate key.");
return;
}
NSLog(@"%@%@%@%@",@"Verified ",messageType,@" / ",[envelope StringOf: @"MessageId"]);
// Notification: durably enqueue/process only after verification.
// SubscriptionConfirmation: submit the verified Token to the configured SNS
// endpoint only if this is a subscription your application requested.
// UnsubscribeConfirmation: record status; do not automatically resubscribe.
// Never follow SubscribeURL merely because it appeared in an envelope.
}
envelopeIndex = envelopeIndex + 1;
}
NSLog(@"%@",@"All envelopes verified; duplicate detection was limited to this batch.");