func CheckSlackSignature(request events.APIGatewayProxyRequest) error {
slackVersion := "v0:"
slackTimestamp := request.Headers["X-Slack-Request-Timestamp"]
slackSignature := request.Headers["X-Slack-Signature"]
slackBody := request.Body
// Defend ReplayAttack
now := time.Now()
n, err := strconv.ParseInt(slackTimestamp, 10, 64)
if err != nil {
fmt.Printf("%d of type %T", n, n)
return err
}
if (now.Unix() - n) > 60*5 {
fmt.Println("replay attack")
err = errors.New("replay attack error")
return err
}
// Check Signature
sigBasestring := slackVersion + slackTimestamp + ":" + slackBody
secret := os.Getenv("SIGNINGSECRET")
fmt.Println("sigBasestring : " + sigBasestring)
fmt.Println("secret : " + secret)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(sigBasestring))
sha := hex.EncodeToString(mac.Sum(nil))
sha = "v0=" + sha
log.Println("---------- check signature ----------")
log.Println(sha)
log.Println(slackSignature)
if sha != slackSignature {
fmt.Println("signature mismatch")
err = errors.New("signature mismatch error")
return err
}
return nil
}
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// Check Signature
err := CheckSlackSignature(request)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
return events.APIGatewayProxyResponse{
Body: string(request.Body),
StatusCode: 200,
}, nil
}
func main() {
lambda.Start(handler)
}