Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Enforce webhook secret in BitbucketServer event source #1917

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions eventsources/sources/bitbucketserver/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ package bitbucketserver

import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"math/rand"
Expand Down Expand Up @@ -80,9 +83,9 @@ func (router *Router) HandleRoute(writer http.ResponseWriter, request *http.Requ
route.Metrics.EventProcessingDuration(route.EventSourceName, route.EventName, float64(time.Since(start)/time.Millisecond))
}(time.Now())

body, err := ioutil.ReadAll(request.Body)
body, err := router.parseAndValidateBitbucketServerRequest(request)
if err != nil {
logger.Errorw("failed to parse request body", zap.Error(err))
logger.Errorw("failed to parse/validate request", zap.Error(err))
common.SendErrorResponse(writer, err.Error())
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
Expand Down Expand Up @@ -387,3 +390,27 @@ func (router *Router) createRequestBodyFromWebhook(hook bitbucketv1.Webhook) ([]

return requestBody, nil
}

func (router *Router) parseAndValidateBitbucketServerRequest(request *http.Request) ([]byte, error) {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to parse request body")
}

if len(router.hookSecret) != 0 {
signature := request.Header.Get("X-Hub-Signature")
if len(signature) == 0 {
return nil, errors.New("missing signature header")
}

mac := hmac.New(sha256.New, []byte(router.hookSecret))
_, _ = mac.Write(body)
expectedMAC := hex.EncodeToString(mac.Sum(nil))

if !hmac.Equal([]byte(signature[7:]), []byte(expectedMAC)) {
return nil, errors.New("hmac verification failed")
}
}

return body, nil
}