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

GitHub webhooks: check signature #2493

Merged
merged 7 commits into from
Apr 17, 2017
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ be deprecated eventually.
- [#2636](https://github.com/influxdata/telegraf/pull/2636): Add `message_len_max` option to `kafka_consumer` input
- [#1100](https://github.com/influxdata/telegraf/issues/1100): Add collectd parser
- [#1820](https://github.com/influxdata/telegraf/issues/1820): easier plugin testing without outputs
- [#2493](https://github.com/influxdata/telegraf/pull/2493): Check signature in the GitHub webhook plugin

### Bugfixes

Expand Down
1 change: 1 addition & 0 deletions etc/telegraf.conf
Original file line number Diff line number Diff line change
Expand Up @@ -2382,6 +2382,7 @@
#
# [inputs.webhooks.github]
# path = "/github"
# # secret = ""
#
# [inputs.webhooks.mandrill]
# path = "/mandrill"
Expand Down
2 changes: 2 additions & 0 deletions plugins/inputs/webhooks/github/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

You should configure your Organization's Webhooks to point at the `webhooks` service. To do this go to `github.com/{my_organization}` and click `Settings > Webhooks > Add webhook`. In the resulting menu set `Payload URL` to `http://<my_ip>:1619/github`, `Content type` to `application/json` and under the section `Which events would you like to trigger this webhook?` select 'Send me <b>everything</b>'. By default all of the events will write to the `github_webhooks` measurement, this is configurable by setting the `measurement_name` in the config file.

You can also add a secret that will be used by telegraf to verify the authenticity of the requests.

## Events

The titles of the following sections are links to the full payloads and details for each event. The body contains what information from the event is persisted. The format is as follows:
Expand Down
28 changes: 25 additions & 3 deletions plugins/inputs/webhooks/github/github_webhooks.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package github

import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
Expand All @@ -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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of generating the signature on every github event, you should generate it just once and then cache for future calls

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The generation is dependant of the body of the event. Not sure what I can cache. The string to byte op?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, nevermind then

mac := hmac.New(sha1.New, []byte(secret))
mac.Write(data)
result := mac.Sum(nil)
return "sha1=" + hex.EncodeToString(result)
}
33 changes: 33 additions & 0 deletions plugins/inputs/webhooks/github/github_webhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ func GithubWebhookRequest(event string, jsonString string, t *testing.T) {
}
}

func GithubWebhookRequestWithSignature(event string, jsonString string, t *testing.T, signature string, expectedStatus int) {
var acc testutil.Accumulator
gh := &GithubWebhook{Path: "/github", Secret: "signature", acc: &acc}
req, _ := http.NewRequest("POST", "/github", strings.NewReader(jsonString))
req.Header.Add("X-Github-Event", event)
req.Header.Add("X-Hub-Signature", signature)
w := httptest.NewRecorder()
gh.eventHandler(w, req)
if w.Code != expectedStatus {
t.Errorf("POST "+event+" returned HTTP status code %v.\nExpected %v", w.Code, expectedStatus)
}
}

func TestCommitCommentEvent(t *testing.T) {
GithubWebhookRequest("commit_comment", CommitCommentEventJSON(), t)
}
Expand Down Expand Up @@ -100,3 +113,23 @@ func TestTeamAddEvent(t *testing.T) {
func TestWatchEvent(t *testing.T) {
GithubWebhookRequest("watch", WatchEventJSON(), t)
}

func TestEventWithSignatureFail(t *testing.T) {
GithubWebhookRequestWithSignature("watch", WatchEventJSON(), t, "signature", http.StatusBadRequest)
}

func TestEventWithSignatureSuccess(t *testing.T) {
GithubWebhookRequestWithSignature("watch", WatchEventJSON(), t, generateSignature("signature", []byte(WatchEventJSON())), http.StatusOK)
}

func TestCheckSignatureSuccess(t *testing.T) {
if !checkSignature("my_little_secret", []byte("random-signature-body"), "sha1=3dca279e731c97c38e3019a075dee9ebbd0a99f0") {
t.Errorf("check signature failed")
}
}

func TestCheckSignatureFailed(t *testing.T) {
if checkSignature("m_little_secret", []byte("random-signature-body"), "sha1=3dca279e731c97c38e3019a075dee9ebbd0a99f0") {
t.Errorf("check signature failed")
}
}
1 change: 1 addition & 0 deletions plugins/inputs/webhooks/webhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (wb *Webhooks) SampleConfig() string {

[inputs.webhooks.github]
path = "/github"
# secret = ""

[inputs.webhooks.mandrill]
path = "/mandrill"
Expand Down