Sample code for 30+ languages & platforms
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 C# Downloads

C#
bool success = false;

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

Chilkat.JsonObject batch = new Chilkat.JsonObject();
batch.Strict = true;
success = batch.LoadFile("qa_data/aws/sns_notifications.json");
if (success != true) {
    Debug.WriteLine("Could not parse notification envelopes.");
    return;
}

if (batch.JsonTypeOf("messages") != 4) {
    Debug.WriteLine("Expected a messages array.");
    return;
}

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

string allowedTopic = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
string certPrefix = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-";
//  Pin the expected topic and matching regional SNS host in application configuration.
Chilkat.Hashtable seenMessages = new Chilkat.Hashtable();
Chilkat.JsonObject envelope = new Chilkat.JsonObject();
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read current time.");
    return;
}

int envelopeIndex = 0;
while ((envelopeIndex < count)) {
    batch.I = envelopeIndex;
    success = batch.ObjectOf2("messages[i]",envelope);
    if (success != true) {
        Debug.WriteLine("Expected a JSON object envelope.");
        return;
    }

    Chilkat.Hashtable fieldNames = new Chilkat.Hashtable();
    int fieldIndex = 0;
    while ((fieldIndex < envelope.Size)) {
        string fieldName = envelope.NameAt(fieldIndex);
        if (fieldNames.Contains(fieldName) == true) {
            Debug.WriteLine("Duplicate envelope field.");
            return;
        }

        success = fieldNames.AddStr(fieldName,"seen");
        if (success != true) {
            Debug.WriteLine("Could not track envelope fields.");
            return;
        }

        fieldIndex = fieldIndex + 1;
    }

    stringCompare.SetString(envelope.StringOf("Type"));
    bool stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("Type") != 1) || (stringMatch1 == true)) {
        Debug.WriteLine("Missing or invalid Type.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("MessageId"));
    bool stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("MessageId") != 1) || (stringMatch2 == true)) {
        Debug.WriteLine("Missing or invalid MessageId.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("Message"));
    bool stringMatch3 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("Message") != 1) || (stringMatch3 == true)) {
        Debug.WriteLine("Missing or invalid Message.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("Timestamp"));
    bool stringMatch4 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("Timestamp") != 1) || (stringMatch4 == true)) {
        Debug.WriteLine("Missing or invalid Timestamp.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("TopicArn"));
    bool stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("TopicArn") != 1) || (stringMatch5 == true)) {
        Debug.WriteLine("Missing or invalid TopicArn.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("SignatureVersion"));
    bool stringMatch6 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("SignatureVersion") != 1) || (stringMatch6 == true)) {
        Debug.WriteLine("Missing or invalid SignatureVersion.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("Signature"));
    bool stringMatch7 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("Signature") != 1) || (stringMatch7 == true)) {
        Debug.WriteLine("Missing or invalid Signature.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("SigningCertURL"));
    bool stringMatch8 = stringCompare.ContentsEqual("",true);
    if ((envelope.JsonTypeOf("SigningCertURL") != 1) || (stringMatch8 == true)) {
        Debug.WriteLine("Missing or invalid SigningCertURL.");
        return;
    }

    string messageType = envelope.StringOf("Type");
    stringCompare.SetString(messageType);
    bool stringMatch9 = stringCompare.ContentsEqual("Notification",true);
    stringCompare.SetString(messageType);
    bool stringMatch10 = stringCompare.ContentsEqual("SubscriptionConfirmation",true);
    stringCompare.SetString(messageType);
    bool stringMatch11 = stringCompare.ContentsEqual("UnsubscribeConfirmation",true);
    if ((stringMatch9 != true) && (stringMatch10 != true) && (stringMatch11 != true)) {
        Debug.WriteLine("Unsupported SNS message type.");
        return;
    }

    stringCompare.SetString(envelope.StringOf("TopicArn"));
    bool stringMatch12 = stringCompare.ContentsEqual(allowedTopic,true);
    if (stringMatch12 != true) {
        Debug.WriteLine("Unexpected SNS topic.");
        return;
    }

    string signatureVersion = envelope.StringOf("SignatureVersion");
    stringCompare.SetString(signatureVersion);
    bool stringMatch13 = stringCompare.ContentsEqual("1",true);
    stringCompare.SetString(signatureVersion);
    bool stringMatch14 = stringCompare.ContentsEqual("2",true);
    if ((stringMatch13 != true) && (stringMatch14 != true)) {
        Debug.WriteLine("Unsupported delivery signature version.");
        return;
    }

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

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

    }

    if (envelope.HasMember("Subject") == true) {
        if (envelope.JsonTypeOf("Subject") != 1) {
            Debug.WriteLine("Subject must be a string when present.");
            return;
        }

    }

    Chilkat.CkDateTime timestamp = new Chilkat.CkDateTime();
    success = timestamp.SetFromTimestamp(envelope.StringOf("Timestamp"));
    if (success != true) {
        Debug.WriteLine("Invalid notification timestamp.");
        return;
    }

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

    Chilkat.StringBuilder certUrl = new Chilkat.StringBuilder();
    certUrl.Append(envelope.StringOf("SigningCertURL"));
    Chilkat.StringBuilder prefix = new Chilkat.StringBuilder();
    prefix.Append(certPrefix);
    if ((certUrl.StartsWith(certPrefix,true) != true) || (certUrl.EndsWith(".pem",true) != true) || (certUrl.Length <= prefix.Length + 4)) {
        Debug.WriteLine("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.
    Chilkat.StringBuilder filenameChars = new Chilkat.StringBuilder();
    filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_");
    int charIndex = prefix.Length;
    while ((charIndex < certUrl.Length - 4)) {
        if (filenameChars.Contains(certUrl.GetRange(charIndex,1,false),true) != true) {
            Debug.WriteLine("Invalid signing-certificate filename.");
            return;
        }

        charIndex = charIndex + 1;
    }

    Chilkat.Http http = new Chilkat.Http();
    http.RequireSslCertVerify = true;
    http.FollowRedirects = false;
    http.ConnectTimeout = 20;
    http.ReadTimeout = 30;
    uint maxCertBytes = 65536;
    http.MaxResponseSize = maxCertBytes;
    http.VerboseLogging = false;
    string certPem = http.QuickGetStr(certUrl.GetAsString());
    if ((http.LastMethodSuccess != true) || (http.LastStatus != 200)) {
        Debug.WriteLine("Could not retrieve the certificate securely from the pinned SNS endpoint.");
        return;
    }

    Chilkat.Cert signingCert = new Chilkat.Cert();
    success = signingCert.LoadPem(certPem);
    if (success != true) {
        Debug.WriteLine("Invalid signing certificate.");
        return;
    }

    Chilkat.CertChain chain = new Chilkat.CertChain();
    success = signingCert.BuildCertChain(chain);
    if (success != true) {
        Debug.WriteLine("Could not build signing-certificate chain.");
        return;
    }

    if (chain.ReachesRoot != true) {
        Debug.WriteLine("Incomplete signing-certificate chain; provision trusted intermediates.");
        return;
    }

    Chilkat.TrustedRoots roots = new Chilkat.TrustedRoots();
    roots.TrustSystemCaRoots = true;
    if (chain.IsRootTrusted(roots) != true) {
        Debug.WriteLine("Untrusted signing-certificate root.");
        return;
    }

    success = chain.VerifyCertSignatures();
    if (success != true) {
        Debug.WriteLine("Invalid certificate-chain signatures.");
        return;
    }

    int certIndex = 0;
    Chilkat.Cert chainCert = new Chilkat.Cert();
    while ((certIndex < chain.NumCerts)) {
        success = chain.CertAt(certIndex,chainCert);
        if (success != true) {
            Debug.WriteLine("Could not read chain certificate.");
            return;
        }

        Chilkat.CkDateTime validFrom = new Chilkat.CkDateTime();
        Chilkat.CkDateTime validTo = new Chilkat.CkDateTime();
        success = validFrom.SetFromRfc822(chainCert.ValidFromStr);
        if (success != true) {
            Debug.WriteLine("Invalid certificate validity start.");
            return;
        }

        success = validTo.SetFromRfc822(chainCert.ValidToStr);
        if (success != true) {
            Debug.WriteLine("Invalid certificate validity end.");
            return;
        }

        if ((now.DiffSeconds(validFrom) < 0) || (now.DiffSeconds(validTo) > 0)) {
            Debug.WriteLine("Certificate outside its validity period.");
            return;
        }

        certIndex = certIndex + 1;
    }

    Chilkat.StringBuilder canonical = new Chilkat.StringBuilder();
    canonical.AppendLine("Message",false);
    canonical.AppendLine(envelope.StringOf("Message"),false);
    canonical.AppendLine("MessageId",false);
    canonical.AppendLine(envelope.StringOf("MessageId"),false);
    stringCompare.SetString(messageType);
    bool stringMatch19 = stringCompare.ContentsEqual("Notification",true);
    if (stringMatch19 == true) {
        if (envelope.HasMember("Subject") == true) {
            canonical.AppendLine("Subject",false);
            canonical.AppendLine(envelope.StringOf("Subject"),false);
        }

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

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

    canonical.AppendLine("TopicArn",false);
    canonical.AppendLine(envelope.StringOf("TopicArn"),false);
    canonical.AppendLine("Type",false);
    canonical.AppendLine(envelope.StringOf("Type"),false);
    Chilkat.PublicKey publicKey = new Chilkat.PublicKey();
    success = signingCert.GetPublicKey(publicKey);
    if (success != true) {
        Debug.WriteLine("Could not extract signing public key.");
        return;
    }

    Chilkat.Rsa rsa = new Chilkat.Rsa();
    rsa.Charset = "utf-8";
    rsa.EncodingMode = "base64";
    rsa.LittleEndian = false;
    success = rsa.UsePublicKey(publicKey);
    if (success != true) {
        Debug.WriteLine("Could not configure verification key.");
        return;
    }

    success = rsa.VerifyStringENC(canonical.GetAsString(),hashAlgorithm,envelope.StringOf("Signature"));
    if (success != true) {
        Debug.WriteLine("SNS delivery signature is invalid.");
        return;
    }

    //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    Chilkat.JsonObject identity = new Chilkat.JsonObject();
    success = identity.UpdateString("topic",allowedTopic);
    if (success != true) {
        Debug.WriteLine("Could not form duplicate key.");
        return;
    }

    success = identity.UpdateString("id",envelope.StringOf("MessageId"));
    if (success != true) {
        Debug.WriteLine("Could not form duplicate key.");
        return;
    }

    string duplicateKey = identity.Emit();
    if (seenMessages.Contains(duplicateKey) == true) {
        Debug.WriteLine("Verified duplicate skipped: " + envelope.StringOf("MessageId"));
    }
    else {
        success = seenMessages.AddStr(duplicateKey,"verified");
        if (success != true) {
            Debug.WriteLine("Could not track duplicate key.");
            return;
        }

        Debug.WriteLine("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;
}

Debug.WriteLine("All envelopes verified; duplicate detection was limited to this batch.");