AWS Lambda verify requests from Slack

Viewed 649

I have the following Python code in AWS Lambda to verify if an event received is indeed from Slack:

   import hmac
   import json
   def verifySignature(header,body):
        h = hmac.new(key=os.getenv('sign_secret').encode(), \
            msg=f'v0:{header.get("X-Slack-Request-Timestamp")}:{body}'.encode(), \
            digestmod="sha256")
        result = hmac.compare_digest('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        print('v0='+h.hexdigest(),header.get('X-Slack-Signature'))
        return result

    def lambda_handler(event, context):
        body = json.loads(event.get('body'))
        if verifySignature(event.get('headers'),body):
            do_something()

Slack's authentication protocol is outlined here. However, I keep getting mismatching signatures (result == False). Does anyone know why?

1 Answers

There is a high chance the issue is coming from the encoding / decoding. There is pip package to verify the slack signature.

But the verification code is simple:

import hashlib
import hmac

def verify_slack_signature(slack_post_request, slack_signing_secret):
    slack_signing_secret = bytes(slack_signing_secret, 'utf-8')
    slack_signature = slack_post_request['headers']['X-Slack-Signature']
    slack_request_timestamp = slack_post_request['headers']['X-Slack-Request-Timestamp']
    request_body = slack_post_request["body"]

    basestring = f"v0:{slack_request_timestamp}:{request_body}".encode('utf-8')
    my_signature = 'v0=' + hmac.new(slack_signing_secret, basestring, hashlib.sha256).hexdigest()

    return hmac.compare_digest(my_signature, slack_signature)
Related