Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

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 Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHashtableW.h>
#include <CkDateTimeW.h>
#include <CkHttpW.h>
#include <CkCertW.h>
#include <CkCertChainW.h>
#include <CkTrustedRootsW.h>
#include <CkPublicKeyW.h>
#include <CkRsaW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.

    CkJsonObjectW batch;
    batch.put_Strict(true);
    success = batch.LoadFile(L"qa_data/aws/sns_notifications.json");
    if (success != true) {
        wprintf(L"Could not parse notification envelopes.\n");
        return;
    }

    if (batch.JsonTypeOf(L"messages") != 4) {
        wprintf(L"Expected a messages array.\n");
        return;
    }

    int count = batch.SizeOfArray(L"messages");
    if ((count < 1) || (count > 100)) {
        wprintf(L"Use 1 to 100 envelopes per verification batch.\n");
        return;
    }

    const wchar_t *allowedTopic = L"arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    const wchar_t *certPrefix = L"https://sns.us-west-2.amazonaws.com/SimpleNotificationService-";
    //  Pin the expected topic and matching regional SNS host in application configuration.
    CkHashtableW seenMessages;
    CkJsonObjectW envelope;
    CkDateTimeW now;
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read current time.\n");
        return;
    }

    int envelopeIndex = 0;
    while ((envelopeIndex < count)) {
        batch.put_I(envelopeIndex);
        success = batch.ObjectOf2(L"messages[i]",envelope);
        if (success != true) {
            wprintf(L"Expected a JSON object envelope.\n");
            return;
        }

        CkHashtableW fieldNames;
        int fieldIndex = 0;
        while ((fieldIndex < envelope.get_Size())) {
            const wchar_t *fieldName = envelope.nameAt(fieldIndex);
            if (fieldNames.Contains(fieldName) == true) {
                wprintf(L"Duplicate envelope field.\n");
                return;
            }

            success = fieldNames.AddStr(fieldName,L"seen");
            if (success != true) {
                wprintf(L"Could not track envelope fields.\n");
                return;
            }

            fieldIndex = fieldIndex + 1;
        }

        stringCompare.SetString(envelope.stringOf(L"Type"));
        bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"Type") != 1) || (stringMatch1 == true)) {
            wprintf(L"Missing or invalid Type.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"MessageId"));
        bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"MessageId") != 1) || (stringMatch2 == true)) {
            wprintf(L"Missing or invalid MessageId.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"Message"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"Message") != 1) || (stringMatch3 == true)) {
            wprintf(L"Missing or invalid Message.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"Timestamp"));
        bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"Timestamp") != 1) || (stringMatch4 == true)) {
            wprintf(L"Missing or invalid Timestamp.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"TopicArn"));
        bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"TopicArn") != 1) || (stringMatch5 == true)) {
            wprintf(L"Missing or invalid TopicArn.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"SignatureVersion"));
        bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"SignatureVersion") != 1) || (stringMatch6 == true)) {
            wprintf(L"Missing or invalid SignatureVersion.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"Signature"));
        bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"Signature") != 1) || (stringMatch7 == true)) {
            wprintf(L"Missing or invalid Signature.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"SigningCertURL"));
        bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
        if ((envelope.JsonTypeOf(L"SigningCertURL") != 1) || (stringMatch8 == true)) {
            wprintf(L"Missing or invalid SigningCertURL.\n");
            return;
        }

        const wchar_t *messageType = envelope.stringOf(L"Type");
        stringCompare.SetString(messageType);
        bool stringMatch9 = stringCompare.ContentsEqual(L"Notification",true);
        stringCompare.SetString(messageType);
        bool stringMatch10 = stringCompare.ContentsEqual(L"SubscriptionConfirmation",true);
        stringCompare.SetString(messageType);
        bool stringMatch11 = stringCompare.ContentsEqual(L"UnsubscribeConfirmation",true);
        if ((stringMatch9 != true) && (stringMatch10 != true) && (stringMatch11 != true)) {
            wprintf(L"Unsupported SNS message type.\n");
            return;
        }

        stringCompare.SetString(envelope.stringOf(L"TopicArn"));
        bool stringMatch12 = stringCompare.ContentsEqual(allowedTopic,true);
        if (stringMatch12 != true) {
            wprintf(L"Unexpected SNS topic.\n");
            return;
        }

        const wchar_t *signatureVersion = envelope.stringOf(L"SignatureVersion");
        stringCompare.SetString(signatureVersion);
        bool stringMatch13 = stringCompare.ContentsEqual(L"1",true);
        stringCompare.SetString(signatureVersion);
        bool stringMatch14 = stringCompare.ContentsEqual(L"2",true);
        if ((stringMatch13 != true) && (stringMatch14 != true)) {
            wprintf(L"Unsupported delivery signature version.\n");
            return;
        }

        const wchar_t *hashAlgorithm = L"sha256";
        stringCompare.SetString(signatureVersion);
        bool stringMatch15 = stringCompare.ContentsEqual(L"1",true);
        if (stringMatch15 == true) {
            hashAlgorithm = L"sha1";
        }

        stringCompare.SetString(messageType);
        bool stringMatch16 = stringCompare.ContentsEqual(L"Notification",true);
        if (stringMatch16 != true) {
            stringCompare.SetString(envelope.stringOf(L"SubscribeURL"));
            bool stringMatch17 = stringCompare.ContentsEqual(L"",true);
            stringCompare.SetString(envelope.stringOf(L"Token"));
            bool stringMatch18 = stringCompare.ContentsEqual(L"",true);
            if ((envelope.JsonTypeOf(L"SubscribeURL") != 1) || (stringMatch17 == true) || (envelope.JsonTypeOf(L"Token") != 1) || (stringMatch18 == true)) {
                wprintf(L"Confirmation envelope is missing fields.\n");
                return;
            }

        }

        if (envelope.HasMember(L"Subject") == true) {
            if (envelope.JsonTypeOf(L"Subject") != 1) {
                wprintf(L"Subject must be a string when present.\n");
                return;
            }

        }

        CkDateTimeW timestamp;
        success = timestamp.SetFromTimestamp(envelope.stringOf(L"Timestamp"));
        if (success != true) {
            wprintf(L"Invalid notification timestamp.\n");
            return;
        }

        int ageSeconds = now.DiffSeconds(timestamp);
        if ((ageSeconds < -300) || (ageSeconds > 86400)) {
            wprintf(L"Notification outside the configured 24-hour age / 5-minute clock-skew window.\n");
            return;
        }

        CkStringBuilderW certUrl;
        certUrl.Append(envelope.stringOf(L"SigningCertURL"));
        CkStringBuilderW prefix;
        prefix.Append(certPrefix);
        if ((certUrl.StartsWith(certPrefix,true) != true) || (certUrl.EndsWith(L".pem",true) != true) || (certUrl.get_Length() <= prefix.get_Length() + 4)) {
            wprintf(L"Untrusted signing-certificate URL.\n");
            return;
        }

        //  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
        //  userinfo, alternate port, path traversal, or redirect destination.
        CkStringBuilderW filenameChars;
        filenameChars.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_");
        int charIndex = prefix.get_Length();
        while ((charIndex < certUrl.get_Length() - 4)) {
            if (filenameChars.Contains(certUrl.getRange(charIndex,1,false),true) != true) {
                wprintf(L"Invalid signing-certificate filename.\n");
                return;
            }

            charIndex = charIndex + 1;
        }

        CkHttpW http;
        http.put_RequireSslCertVerify(true);
        http.put_FollowRedirects(false);
        http.put_ConnectTimeout(20);
        http.put_ReadTimeout(30);
        unsigned long maxCertBytes = 65536;
        http.put_MaxResponseSize(maxCertBytes);
        http.put_VerboseLogging(false);
        const wchar_t *certPem = http.quickGetStr(certUrl.getAsString());
        if ((http.get_LastMethodSuccess() != true) || (http.get_LastStatus() != 200)) {
            wprintf(L"Could not retrieve the certificate securely from the pinned SNS endpoint.\n");
            return;
        }

        CkCertW signingCert;
        success = signingCert.LoadPem(certPem);
        if (success != true) {
            wprintf(L"Invalid signing certificate.\n");
            return;
        }

        CkCertChainW chain;
        success = signingCert.BuildCertChain(chain);
        if (success != true) {
            wprintf(L"Could not build signing-certificate chain.\n");
            return;
        }

        if (chain.get_ReachesRoot() != true) {
            wprintf(L"Incomplete signing-certificate chain; provision trusted intermediates.\n");
            return;
        }

        CkTrustedRootsW roots;
        roots.put_TrustSystemCaRoots(true);
        if (chain.IsRootTrusted(roots) != true) {
            wprintf(L"Untrusted signing-certificate root.\n");
            return;
        }

        success = chain.VerifyCertSignatures();
        if (success != true) {
            wprintf(L"Invalid certificate-chain signatures.\n");
            return;
        }

        int certIndex = 0;
        CkCertW chainCert;
        while ((certIndex < chain.get_NumCerts())) {
            success = chain.CertAt(certIndex,chainCert);
            if (success != true) {
                wprintf(L"Could not read chain certificate.\n");
                return;
            }

            CkDateTimeW validFrom;
            CkDateTimeW validTo;
            success = validFrom.SetFromRfc822(chainCert.validFromStr());
            if (success != true) {
                wprintf(L"Invalid certificate validity start.\n");
                return;
            }

            success = validTo.SetFromRfc822(chainCert.validToStr());
            if (success != true) {
                wprintf(L"Invalid certificate validity end.\n");
                return;
            }

            if ((now.DiffSeconds(validFrom) < 0) || (now.DiffSeconds(validTo) > 0)) {
                wprintf(L"Certificate outside its validity period.\n");
                return;
            }

            certIndex = certIndex + 1;
        }

        CkStringBuilderW canonical;
        canonical.AppendLine(L"Message",false);
        canonical.AppendLine(envelope.stringOf(L"Message"),false);
        canonical.AppendLine(L"MessageId",false);
        canonical.AppendLine(envelope.stringOf(L"MessageId"),false);
        stringCompare.SetString(messageType);
        bool stringMatch19 = stringCompare.ContentsEqual(L"Notification",true);
        if (stringMatch19 == true) {
            if (envelope.HasMember(L"Subject") == true) {
                canonical.AppendLine(L"Subject",false);
                canonical.AppendLine(envelope.stringOf(L"Subject"),false);
            }

        }
        else {
            canonical.AppendLine(L"SubscribeURL",false);
            canonical.AppendLine(envelope.stringOf(L"SubscribeURL"),false);
        }

        canonical.AppendLine(L"Timestamp",false);
        canonical.AppendLine(envelope.stringOf(L"Timestamp"),false);
        stringCompare.SetString(messageType);
        bool stringMatch20 = stringCompare.ContentsEqual(L"Notification",true);
        if (stringMatch20 != true) {
            canonical.AppendLine(L"Token",false);
            canonical.AppendLine(envelope.stringOf(L"Token"),false);
        }

        canonical.AppendLine(L"TopicArn",false);
        canonical.AppendLine(envelope.stringOf(L"TopicArn"),false);
        canonical.AppendLine(L"Type",false);
        canonical.AppendLine(envelope.stringOf(L"Type"),false);
        CkPublicKeyW publicKey;
        success = signingCert.GetPublicKey(publicKey);
        if (success != true) {
            wprintf(L"Could not extract signing public key.\n");
            return;
        }

        CkRsaW rsa;
        rsa.put_Charset(L"utf-8");
        rsa.put_EncodingMode(L"base64");
        rsa.put_LittleEndian(false);
        success = rsa.UsePublicKey(publicKey);
        if (success != true) {
            wprintf(L"Could not configure verification key.\n");
            return;
        }

        success = rsa.VerifyStringENC(canonical.getAsString(),hashAlgorithm,envelope.stringOf(L"Signature"));
        if (success != true) {
            wprintf(L"SNS delivery signature is invalid.\n");
            return;
        }

        //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
        CkJsonObjectW identity;
        success = identity.UpdateString(L"topic",allowedTopic);
        if (success != true) {
            wprintf(L"Could not form duplicate key.\n");
            return;
        }

        success = identity.UpdateString(L"id",envelope.stringOf(L"MessageId"));
        if (success != true) {
            wprintf(L"Could not form duplicate key.\n");
            return;
        }

        const wchar_t *duplicateKey = identity.emit();
        if (seenMessages.Contains(duplicateKey) == true) {
            wprintf(L"Verified duplicate skipped: %s\n",envelope.stringOf(L"MessageId"));
        }
        else {
            success = seenMessages.AddStr(duplicateKey,L"verified");
            if (success != true) {
                wprintf(L"Could not track duplicate key.\n");
                return;
            }

            wprintf(L"Verified %s / %s\n",messageType,envelope.stringOf(L"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;
    }

    wprintf(L"All envelopes verified; duplicate detection was limited to this batch.\n");
    }