mirror of
https://github.com/wahyd4/telegraf.git
synced 2026-08-13 06:36:07 +10:00
GitHub webhooks: check signature (#2493)
This commit is contained in:
committed by
Daniel Nelson
parent
dc5779e2a7
commit
58ee962679
@@ -1,6 +1,9 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
@@ -11,8 +14,9 @@ import (
|
||||
)
|
||||
|
||||
type GithubWebhook struct {
|
||||
Path string
|
||||
acc telegraf.Accumulator
|
||||
Path string
|
||||
Secret string
|
||||
acc telegraf.Accumulator
|
||||
}
|
||||
|
||||
func (gh *GithubWebhook) Register(router *mux.Router, acc telegraf.Accumulator) {
|
||||
@@ -23,12 +27,19 @@ func (gh *GithubWebhook) Register(router *mux.Router, acc telegraf.Accumulator)
|
||||
|
||||
func (gh *GithubWebhook) eventHandler(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
eventType := r.Header["X-Github-Event"][0]
|
||||
eventType := r.Header.Get("X-Github-Event")
|
||||
data, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if gh.Secret != "" && !checkSignature(gh.Secret, data, r.Header.Get("X-Hub-Signature")) {
|
||||
log.Printf("E! Fail to check the github webhook signature\n")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
e, err := NewEvent(data, eventType)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@@ -108,3 +119,14 @@ func NewEvent(data []byte, name string) (Event, error) {
|
||||
}
|
||||
return nil, &newEventError{"Not a recognized event type"}
|
||||
}
|
||||
|
||||
func checkSignature(secret string, data []byte, signature string) bool {
|
||||
return hmac.Equal([]byte(signature), []byte(generateSignature(secret, data)))
|
||||
}
|
||||
|
||||
func generateSignature(secret string, data []byte) string {
|
||||
mac := hmac.New(sha1.New, []byte(secret))
|
||||
mac.Write(data)
|
||||
result := mac.Sum(nil)
|
||||
return "sha1=" + hex.EncodeToString(result)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user