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

PHP ActiveX
<?php

$success = 0;

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

$batch = new COM("Chilkat.JsonObject");
$batch->Strict = 1;
$success = $batch->LoadFile('qa_data/aws/sns_notifications.json');
if ($success != 1) {
    print 'Could not parse notification envelopes.' . "\n";
    exit;
}

if ($batch->JsonTypeOf('messages') != 4) {
    print 'Expected a messages array.' . "\n";
    exit;
}

$count = $batch->SizeOfArray('messages');
if (($count < 1) or ($count > 100)) {
    print 'Use 1 to 100 envelopes per verification batch.' . "\n";
    exit;
}

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

$envelopeIndex = 0;
while (($envelopeIndex < $count)) {
    $batch->I = $envelopeIndex;
    $success = $batch->ObjectOf2('messages[i]',$envelope);
    if ($success != 1) {
        print 'Expected a JSON object envelope.' . "\n";
        exit;
    }

    $fieldNames = new COM("Chilkat.Hashtable");
    $fieldIndex = 0;
    while (($fieldIndex < $envelope->Size)) {
        $fieldName = $envelope->nameAt($fieldIndex);
        if ($fieldNames->Contains($fieldName) == 1) {
            print 'Duplicate envelope field.' . "\n";
            exit;
        }

        $success = $fieldNames->AddStr($fieldName,'seen');
        if ($success != 1) {
            print 'Could not track envelope fields.' . "\n";
            exit;
        }

        $fieldIndex = $fieldIndex + 1;
    }

    $stringCompare->SetString($envelope->stringOf('Type'));
    $stringMatch1 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('Type') != 1) or ($stringMatch1 == 1)) {
        print 'Missing or invalid Type.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('MessageId'));
    $stringMatch2 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('MessageId') != 1) or ($stringMatch2 == 1)) {
        print 'Missing or invalid MessageId.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('Message'));
    $stringMatch3 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('Message') != 1) or ($stringMatch3 == 1)) {
        print 'Missing or invalid Message.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('Timestamp'));
    $stringMatch4 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('Timestamp') != 1) or ($stringMatch4 == 1)) {
        print 'Missing or invalid Timestamp.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('TopicArn'));
    $stringMatch5 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('TopicArn') != 1) or ($stringMatch5 == 1)) {
        print 'Missing or invalid TopicArn.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('SignatureVersion'));
    $stringMatch6 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('SignatureVersion') != 1) or ($stringMatch6 == 1)) {
        print 'Missing or invalid SignatureVersion.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('Signature'));
    $stringMatch7 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('Signature') != 1) or ($stringMatch7 == 1)) {
        print 'Missing or invalid Signature.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('SigningCertURL'));
    $stringMatch8 = $stringCompare->ContentsEqual('',1);
    if (($envelope->JsonTypeOf('SigningCertURL') != 1) or ($stringMatch8 == 1)) {
        print 'Missing or invalid SigningCertURL.' . "\n";
        exit;
    }

    $messageType = $envelope->stringOf('Type');
    $stringCompare->SetString($messageType);
    $stringMatch9 = $stringCompare->ContentsEqual('Notification',1);
    $stringCompare->SetString($messageType);
    $stringMatch10 = $stringCompare->ContentsEqual('SubscriptionConfirmation',1);
    $stringCompare->SetString($messageType);
    $stringMatch11 = $stringCompare->ContentsEqual('UnsubscribeConfirmation',1);
    if (($stringMatch9 != 1) and ($stringMatch10 != 1) and ($stringMatch11 != 1)) {
        print 'Unsupported SNS message type.' . "\n";
        exit;
    }

    $stringCompare->SetString($envelope->stringOf('TopicArn'));
    $stringMatch12 = $stringCompare->ContentsEqual($allowedTopic,1);
    if ($stringMatch12 != 1) {
        print 'Unexpected SNS topic.' . "\n";
        exit;
    }

    $signatureVersion = $envelope->stringOf('SignatureVersion');
    $stringCompare->SetString($signatureVersion);
    $stringMatch13 = $stringCompare->ContentsEqual('1',1);
    $stringCompare->SetString($signatureVersion);
    $stringMatch14 = $stringCompare->ContentsEqual('2',1);
    if (($stringMatch13 != 1) and ($stringMatch14 != 1)) {
        print 'Unsupported delivery signature version.' . "\n";
        exit;
    }

    $hashAlgorithm = 'sha256';
    $stringCompare->SetString($signatureVersion);
    $stringMatch15 = $stringCompare->ContentsEqual('1',1);
    if ($stringMatch15 == 1) {
        $hashAlgorithm = 'sha1';
    }

    $stringCompare->SetString($messageType);
    $stringMatch16 = $stringCompare->ContentsEqual('Notification',1);
    if ($stringMatch16 != 1) {
        $stringCompare->SetString($envelope->stringOf('SubscribeURL'));
        $stringMatch17 = $stringCompare->ContentsEqual('',1);
        $stringCompare->SetString($envelope->stringOf('Token'));
        $stringMatch18 = $stringCompare->ContentsEqual('',1);
        if (($envelope->JsonTypeOf('SubscribeURL') != 1) or ($stringMatch17 == 1) or ($envelope->JsonTypeOf('Token') != 1) or ($stringMatch18 == 1)) {
            print 'Confirmation envelope is missing fields.' . "\n";
            exit;
        }

    }

    if ($envelope->HasMember('Subject') == 1) {
        if ($envelope->JsonTypeOf('Subject') != 1) {
            print 'Subject must be a string when present.' . "\n";
            exit;
        }

    }

    $timestamp = new COM("Chilkat.CkDateTime");
    $success = $timestamp->SetFromTimestamp($envelope->stringOf('Timestamp'));
    if ($success != 1) {
        print 'Invalid notification timestamp.' . "\n";
        exit;
    }

    $ageSeconds = $now->DiffSeconds($timestamp);
    if (($ageSeconds < -300) or ($ageSeconds > 86400)) {
        print 'Notification outside the configured 24-hour age / 5-minute clock-skew window.' . "\n";
        exit;
    }

    $certUrl = new COM("Chilkat.StringBuilder");
    $certUrl->Append($envelope->stringOf('SigningCertURL'));
    $prefix = new COM("Chilkat.StringBuilder");
    $prefix->Append($certPrefix);
    if (($certUrl->StartsWith($certPrefix,1) != 1) or ($certUrl->EndsWith('.pem',1) != 1) or ($certUrl->Length <= $prefix->Length + 4)) {
        print 'Untrusted signing-certificate URL.' . "\n";
        exit;
    }

    //  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    //  userinfo, alternate port, path traversal, or redirect destination.
    $filenameChars = new COM("Chilkat.StringBuilder");
    $filenameChars->Append('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
    $charIndex = $prefix->Length;
    while (($charIndex < $certUrl->Length - 4)) {
        if ($filenameChars->Contains($certUrl->getRange($charIndex,1,0),1) != 1) {
            print 'Invalid signing-certificate filename.' . "\n";
            exit;
        }

        $charIndex = $charIndex + 1;
    }

    $http = new COM("Chilkat.Http");
    $http->RequireSslCertVerify = 1;
    $http->FollowRedirects = 0;
    $http->ConnectTimeout = 20;
    $http->ReadTimeout = 30;
    $maxCertBytes = 65536;
    $http->MaxResponseSize = $maxCertBytes;
    $http->VerboseLogging = 0;
    $certPem = $http->quickGetStr($certUrl->getAsString());
    if (($http->LastMethodSuccess != 1) or ($http->LastStatus != 200)) {
        print 'Could not retrieve the certificate securely from the pinned SNS endpoint.' . "\n";
        exit;
    }

    $signingCert = new COM("Chilkat.Cert");
    $success = $signingCert->LoadPem($certPem);
    if ($success != 1) {
        print 'Invalid signing certificate.' . "\n";
        exit;
    }

    $chain = new COM("Chilkat.CertChain");
    $success = $signingCert->BuildCertChain($chain);
    if ($success != 1) {
        print 'Could not build signing-certificate chain.' . "\n";
        exit;
    }

    if ($chain->ReachesRoot != 1) {
        print 'Incomplete signing-certificate chain; provision trusted intermediates.' . "\n";
        exit;
    }

    $roots = new COM("Chilkat.TrustedRoots");
    $roots->TrustSystemCaRoots = 1;
    if ($chain->IsRootTrusted($roots) != 1) {
        print 'Untrusted signing-certificate root.' . "\n";
        exit;
    }

    $success = $chain->VerifyCertSignatures();
    if ($success != 1) {
        print 'Invalid certificate-chain signatures.' . "\n";
        exit;
    }

    $certIndex = 0;
    $chainCert = new COM("Chilkat.Cert");
    while (($certIndex < $chain->NumCerts)) {
        $success = $chain->CertAt($certIndex,$chainCert);
        if ($success != 1) {
            print 'Could not read chain certificate.' . "\n";
            exit;
        }

        $validFrom = new COM("Chilkat.CkDateTime");
        $validTo = new COM("Chilkat.CkDateTime");
        $success = $validFrom->SetFromRfc822($chainCert->ValidFromStr);
        if ($success != 1) {
            print 'Invalid certificate validity start.' . "\n";
            exit;
        }

        $success = $validTo->SetFromRfc822($chainCert->ValidToStr);
        if ($success != 1) {
            print 'Invalid certificate validity end.' . "\n";
            exit;
        }

        if (($now->DiffSeconds($validFrom) < 0) or ($now->DiffSeconds($validTo) > 0)) {
            print 'Certificate outside its validity period.' . "\n";
            exit;
        }

        $certIndex = $certIndex + 1;
    }

    $canonical = new COM("Chilkat.StringBuilder");
    $canonical->AppendLine('Message',0);
    $canonical->AppendLine($envelope->stringOf('Message'),0);
    $canonical->AppendLine('MessageId',0);
    $canonical->AppendLine($envelope->stringOf('MessageId'),0);
    $stringCompare->SetString($messageType);
    $stringMatch19 = $stringCompare->ContentsEqual('Notification',1);
    if ($stringMatch19 == 1) {
        if ($envelope->HasMember('Subject') == 1) {
            $canonical->AppendLine('Subject',0);
            $canonical->AppendLine($envelope->stringOf('Subject'),0);
        }

    }
    else {
        $canonical->AppendLine('SubscribeURL',0);
        $canonical->AppendLine($envelope->stringOf('SubscribeURL'),0);
    }

    $canonical->AppendLine('Timestamp',0);
    $canonical->AppendLine($envelope->stringOf('Timestamp'),0);
    $stringCompare->SetString($messageType);
    $stringMatch20 = $stringCompare->ContentsEqual('Notification',1);
    if ($stringMatch20 != 1) {
        $canonical->AppendLine('Token',0);
        $canonical->AppendLine($envelope->stringOf('Token'),0);
    }

    $canonical->AppendLine('TopicArn',0);
    $canonical->AppendLine($envelope->stringOf('TopicArn'),0);
    $canonical->AppendLine('Type',0);
    $canonical->AppendLine($envelope->stringOf('Type'),0);
    $publicKey = new COM("Chilkat.PublicKey");
    $success = $signingCert->GetPublicKey($publicKey);
    if ($success != 1) {
        print 'Could not extract signing public key.' . "\n";
        exit;
    }

    $rsa = new COM("Chilkat.Rsa");
    $rsa->Charset = 'utf-8';
    $rsa->EncodingMode = 'base64';
    $rsa->LittleEndian = 0;
    $success = $rsa->UsePublicKey($publicKey);
    if ($success != 1) {
        print 'Could not configure verification key.' . "\n";
        exit;
    }

    $success = $rsa->VerifyStringENC($canonical->getAsString(),$hashAlgorithm,$envelope->stringOf('Signature'));
    if ($success != 1) {
        print 'SNS delivery signature is invalid.' . "\n";
        exit;
    }

    //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    $identity = new COM("Chilkat.JsonObject");
    $success = $identity->UpdateString('topic',$allowedTopic);
    if ($success != 1) {
        print 'Could not form duplicate key.' . "\n";
        exit;
    }

    $success = $identity->UpdateString('id',$envelope->stringOf('MessageId'));
    if ($success != 1) {
        print 'Could not form duplicate key.' . "\n";
        exit;
    }

    $duplicateKey = $identity->emit();
    if ($seenMessages->Contains($duplicateKey) == 1) {
        print 'Verified duplicate skipped: ' . $envelope->stringOf('MessageId') . "\n";
    }
    else {
        $success = $seenMessages->AddStr($duplicateKey,'verified');
        if ($success != 1) {
            print 'Could not track duplicate key.' . "\n";
            exit;
        }

        print 'Verified ' . $messageType . ' / ' . $envelope->stringOf('MessageId') . "\n";
        //  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;
}

print 'All envelopes verified; duplicate detection was limited to this batch.' . "\n";

?>