Sample code for 30+ languages & platforms
Visual Basic 6.0 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 Visual Basic 6.0 Downloads

Visual Basic 6.0
Dim success As Long
success = 0

Dim stringCompare As New ChilkatStringBuilder
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.

Dim batch As New ChilkatJsonObject
batch.Strict = 1
success = batch.LoadFile("qa_data/aws/sns_notifications.json")
If (success <> 1) Then
    Debug.Print "Could not parse notification envelopes."
    Exit Sub
End If

If (batch.JsonTypeOf("messages") <> 4) Then
    Debug.Print "Expected a messages array."
    Exit Sub
End If

Dim count As Long
count = batch.SizeOfArray("messages")
If ((count < 1) Or (count > 100)) Then
    Debug.Print "Use 1 to 100 envelopes per verification batch."
    Exit Sub
End If

Dim allowedTopic As String
allowedTopic = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
Dim certPrefix As String
certPrefix = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-"
'  Pin the expected topic and matching regional SNS host in application configuration.
Dim seenMessages As New ChilkatHashtable
Dim envelope As New ChilkatJsonObject
Dim now As New CkDateTime
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
    Debug.Print "Could not read current time."
    Exit Sub
End If

Dim envelopeIndex As Long
envelopeIndex = 0
Do While (envelopeIndex < count)
    batch.I = envelopeIndex
    success = batch.ObjectOf2("messages[i]",envelope)
    If (success <> 1) Then
        Debug.Print "Expected a JSON object envelope."
        Exit Sub
    End If

    Dim fieldNames As New ChilkatHashtable
    Dim fieldIndex As Long
    fieldIndex = 0
    Do While (fieldIndex < envelope.Size)
        Dim fieldName As String
        fieldName = envelope.NameAt(fieldIndex)
        If (fieldNames.Contains(fieldName) = 1) Then
            Debug.Print "Duplicate envelope field."
            Exit Sub
        End If

        success = fieldNames.AddStr(fieldName,"seen")
        If (success <> 1) Then
            Debug.Print "Could not track envelope fields."
            Exit Sub
        End If

        fieldIndex = fieldIndex + 1
    Loop
    success = stringCompare.SetString(envelope.StringOf("Type"))
    Dim stringMatch1 As Long
    stringMatch1 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("Type") <> 1) Or (stringMatch1 = 1)) Then
        Debug.Print "Missing or invalid Type."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("MessageId"))
    Dim stringMatch2 As Long
    stringMatch2 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("MessageId") <> 1) Or (stringMatch2 = 1)) Then
        Debug.Print "Missing or invalid MessageId."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("Message"))
    Dim stringMatch3 As Long
    stringMatch3 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("Message") <> 1) Or (stringMatch3 = 1)) Then
        Debug.Print "Missing or invalid Message."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("Timestamp"))
    Dim stringMatch4 As Long
    stringMatch4 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("Timestamp") <> 1) Or (stringMatch4 = 1)) Then
        Debug.Print "Missing or invalid Timestamp."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("TopicArn"))
    Dim stringMatch5 As Long
    stringMatch5 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("TopicArn") <> 1) Or (stringMatch5 = 1)) Then
        Debug.Print "Missing or invalid TopicArn."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("SignatureVersion"))
    Dim stringMatch6 As Long
    stringMatch6 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("SignatureVersion") <> 1) Or (stringMatch6 = 1)) Then
        Debug.Print "Missing or invalid SignatureVersion."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("Signature"))
    Dim stringMatch7 As Long
    stringMatch7 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("Signature") <> 1) Or (stringMatch7 = 1)) Then
        Debug.Print "Missing or invalid Signature."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("SigningCertURL"))
    Dim stringMatch8 As Long
    stringMatch8 = stringCompare.ContentsEqual("",1)
    If ((envelope.JsonTypeOf("SigningCertURL") <> 1) Or (stringMatch8 = 1)) Then
        Debug.Print "Missing or invalid SigningCertURL."
        Exit Sub
    End If

    Dim messageType As String
    messageType = envelope.StringOf("Type")
    success = stringCompare.SetString(messageType)
    Dim stringMatch9 As Long
    stringMatch9 = stringCompare.ContentsEqual("Notification",1)
    success = stringCompare.SetString(messageType)
    Dim stringMatch10 As Long
    stringMatch10 = stringCompare.ContentsEqual("SubscriptionConfirmation",1)
    success = stringCompare.SetString(messageType)
    Dim stringMatch11 As Long
    stringMatch11 = stringCompare.ContentsEqual("UnsubscribeConfirmation",1)
    If ((stringMatch9 <> 1) And (stringMatch10 <> 1) And (stringMatch11 <> 1)) Then
        Debug.Print "Unsupported SNS message type."
        Exit Sub
    End If

    success = stringCompare.SetString(envelope.StringOf("TopicArn"))
    Dim stringMatch12 As Long
    stringMatch12 = stringCompare.ContentsEqual(allowedTopic,1)
    If (stringMatch12 <> 1) Then
        Debug.Print "Unexpected SNS topic."
        Exit Sub
    End If

    Dim signatureVersion As String
    signatureVersion = envelope.StringOf("SignatureVersion")
    success = stringCompare.SetString(signatureVersion)
    Dim stringMatch13 As Long
    stringMatch13 = stringCompare.ContentsEqual("1",1)
    success = stringCompare.SetString(signatureVersion)
    Dim stringMatch14 As Long
    stringMatch14 = stringCompare.ContentsEqual("2",1)
    If ((stringMatch13 <> 1) And (stringMatch14 <> 1)) Then
        Debug.Print "Unsupported delivery signature version."
        Exit Sub
    End If

    Dim hashAlgorithm As String
    hashAlgorithm = "sha256"
    success = stringCompare.SetString(signatureVersion)
    Dim stringMatch15 As Long
    stringMatch15 = stringCompare.ContentsEqual("1",1)
    If (stringMatch15 = 1) Then
        hashAlgorithm = "sha1"
    End If

    success = stringCompare.SetString(messageType)
    Dim stringMatch16 As Long
    stringMatch16 = stringCompare.ContentsEqual("Notification",1)
    If (stringMatch16 <> 1) Then
        success = stringCompare.SetString(envelope.StringOf("SubscribeURL"))
        Dim stringMatch17 As Long
        stringMatch17 = stringCompare.ContentsEqual("",1)
        success = stringCompare.SetString(envelope.StringOf("Token"))
        Dim stringMatch18 As Long
        stringMatch18 = stringCompare.ContentsEqual("",1)
        If ((envelope.JsonTypeOf("SubscribeURL") <> 1) Or (stringMatch17 = 1) Or (envelope.JsonTypeOf("Token") <> 1) Or (stringMatch18 = 1)) Then
            Debug.Print "Confirmation envelope is missing fields."
            Exit Sub
        End If

    End If

    If (envelope.HasMember("Subject") = 1) Then
        If (envelope.JsonTypeOf("Subject") <> 1) Then
            Debug.Print "Subject must be a string when present."
            Exit Sub
        End If

    End If

    Dim timestamp As New CkDateTime
    success = timestamp.SetFromTimestamp(envelope.StringOf("Timestamp"))
    If (success <> 1) Then
        Debug.Print "Invalid notification timestamp."
        Exit Sub
    End If

    Dim ageSeconds As Long
    ageSeconds = now.DiffSeconds(timestamp)
    If ((ageSeconds < -300) Or (ageSeconds > 86400)) Then
        Debug.Print "Notification outside the configured 24-hour age / 5-minute clock-skew window."
        Exit Sub
    End If

    Dim certUrl As New ChilkatStringBuilder
    success = certUrl.Append(envelope.StringOf("SigningCertURL"))
    Dim prefix As New ChilkatStringBuilder
    success = prefix.Append(certPrefix)
    If ((certUrl.StartsWith(certPrefix,1) <> 1) Or (certUrl.EndsWith(".pem",1) <> 1) Or (certUrl.Length <= prefix.Length + 4)) Then
        Debug.Print "Untrusted signing-certificate URL."
        Exit Sub
    End If

    '  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    '  userinfo, alternate port, path traversal, or redirect destination.
    Dim filenameChars As New ChilkatStringBuilder
    success = filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
    Dim charIndex As Long
    charIndex = prefix.Length
    Do While (charIndex < certUrl.Length - 4)
        If (filenameChars.Contains(certUrl.GetRange(charIndex,1,0),1) <> 1) Then
            Debug.Print "Invalid signing-certificate filename."
            Exit Sub
        End If

        charIndex = charIndex + 1
    Loop
    Dim http As New ChilkatHttp
    http.RequireSslCertVerify = 1
    http.FollowRedirects = 0
    http.ConnectTimeout = 20
    http.ReadTimeout = 30
    Dim maxCertBytes As Long
    maxCertBytes = 65536
    http.MaxResponseSize = maxCertBytes
    http.VerboseLogging = 0
    Dim certPem As String
    certPem = http.QuickGetStr(certUrl.GetAsString())
    If ((http.LastMethodSuccess <> 1) Or (http.LastStatus <> 200)) Then
        Debug.Print "Could not retrieve the certificate securely from the pinned SNS endpoint."
        Exit Sub
    End If

    Dim signingCert As New ChilkatCert
    success = signingCert.LoadPem(certPem)
    If (success <> 1) Then
        Debug.Print "Invalid signing certificate."
        Exit Sub
    End If

    Dim chain As New ChilkatCertChain
    success = signingCert.BuildCertChain(chain)
    If (success <> 1) Then
        Debug.Print "Could not build signing-certificate chain."
        Exit Sub
    End If

    If (chain.ReachesRoot <> 1) Then
        Debug.Print "Incomplete signing-certificate chain; provision trusted intermediates."
        Exit Sub
    End If

    Dim roots As New ChilkatTrustedRoots
    roots.TrustSystemCaRoots = 1
    If (chain.IsRootTrusted(roots) <> 1) Then
        Debug.Print "Untrusted signing-certificate root."
        Exit Sub
    End If

    success = chain.VerifyCertSignatures()
    If (success <> 1) Then
        Debug.Print "Invalid certificate-chain signatures."
        Exit Sub
    End If

    Dim certIndex As Long
    certIndex = 0
    Dim chainCert As New ChilkatCert
    Do While (certIndex < chain.NumCerts)
        success = chain.CertAt(certIndex,chainCert)
        If (success <> 1) Then
            Debug.Print "Could not read chain certificate."
            Exit Sub
        End If

        Dim validFrom As New CkDateTime
        Dim validTo As New CkDateTime
        success = validFrom.SetFromRfc822(chainCert.ValidFromStr)
        If (success <> 1) Then
            Debug.Print "Invalid certificate validity start."
            Exit Sub
        End If

        success = validTo.SetFromRfc822(chainCert.ValidToStr)
        If (success <> 1) Then
            Debug.Print "Invalid certificate validity end."
            Exit Sub
        End If

        If ((now.DiffSeconds(validFrom) < 0) Or (now.DiffSeconds(validTo) > 0)) Then
            Debug.Print "Certificate outside its validity period."
            Exit Sub
        End If

        certIndex = certIndex + 1
    Loop
    Dim canonical As New ChilkatStringBuilder
    success = canonical.AppendLine("Message",0)
    success = canonical.AppendLine(envelope.StringOf("Message"),0)
    success = canonical.AppendLine("MessageId",0)
    success = canonical.AppendLine(envelope.StringOf("MessageId"),0)
    success = stringCompare.SetString(messageType)
    Dim stringMatch19 As Long
    stringMatch19 = stringCompare.ContentsEqual("Notification",1)
    If (stringMatch19 = 1) Then
        If (envelope.HasMember("Subject") = 1) Then
            success = canonical.AppendLine("Subject",0)
            success = canonical.AppendLine(envelope.StringOf("Subject"),0)
        End If

    Else
        success = canonical.AppendLine("SubscribeURL",0)
        success = canonical.AppendLine(envelope.StringOf("SubscribeURL"),0)
    End If

    success = canonical.AppendLine("Timestamp",0)
    success = canonical.AppendLine(envelope.StringOf("Timestamp"),0)
    success = stringCompare.SetString(messageType)
    Dim stringMatch20 As Long
    stringMatch20 = stringCompare.ContentsEqual("Notification",1)
    If (stringMatch20 <> 1) Then
        success = canonical.AppendLine("Token",0)
        success = canonical.AppendLine(envelope.StringOf("Token"),0)
    End If

    success = canonical.AppendLine("TopicArn",0)
    success = canonical.AppendLine(envelope.StringOf("TopicArn"),0)
    success = canonical.AppendLine("Type",0)
    success = canonical.AppendLine(envelope.StringOf("Type"),0)
    Dim publicKey As New PublicKey
    success = signingCert.GetPublicKey(publicKey)
    If (success <> 1) Then
        Debug.Print "Could not extract signing public key."
        Exit Sub
    End If

    Dim rsa As New ChilkatRsa
    rsa.Charset = "utf-8"
    rsa.EncodingMode = "base64"
    rsa.LittleEndian = 0
    success = rsa.UsePublicKey(publicKey)
    If (success <> 1) Then
        Debug.Print "Could not configure verification key."
        Exit Sub
    End If

    success = rsa.VerifyStringENC(canonical.GetAsString(),hashAlgorithm,envelope.StringOf("Signature"))
    If (success <> 1) Then
        Debug.Print "SNS delivery signature is invalid."
        Exit Sub
    End If

    '  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    Dim identity As New ChilkatJsonObject
    success = identity.UpdateString("topic",allowedTopic)
    If (success <> 1) Then
        Debug.Print "Could not form duplicate key."
        Exit Sub
    End If

    success = identity.UpdateString("id",envelope.StringOf("MessageId"))
    If (success <> 1) Then
        Debug.Print "Could not form duplicate key."
        Exit Sub
    End If

    Dim duplicateKey As String
    duplicateKey = identity.Emit()
    If (seenMessages.Contains(duplicateKey) = 1) Then
        Debug.Print "Verified duplicate skipped: " & envelope.StringOf("MessageId")
    Else
        success = seenMessages.AddStr(duplicateKey,"verified")
        If (success <> 1) Then
            Debug.Print "Could not track duplicate key."
            Exit Sub
        End If

        Debug.Print "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.
    End If

    envelopeIndex = envelopeIndex + 1
Loop
Debug.Print "All envelopes verified; duplicate detection was limited to this batch."