0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GoのAPIGatewayでslackのslashコマンド発行時にリクエストを検証するサンプル

Posted at

説明

  • Bodyの中のtokenを使うこともできるが、非推奨とされている
  • HMACを利用して自身のSlackから送信していることを検証できる

image.png

イメージ

  1. v0:<X-Slack-Request-TimeStamp>:<body>の文字列に対して、Signin Secretで復号する
  2. 1の値をX-Slack-Signatureを比較して一致しなければ、リクエストから落とす

サンプル

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)
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?