Skip to content

Commit

Permalink
Make Gitlab token verification constant time
Browse files Browse the repository at this point in the history
This prevents leakage of token information using timing
attacks. A simple string comparison does not suffice here.
  • Loading branch information
neiser committed Mar 4, 2023
1 parent 4f72f9c commit 5f7b060
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions gitlab/gitlab.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package gitlab

import (
"crypto/sha512"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -53,14 +55,16 @@ type WebhookOptions struct{}
// Secret registers the GitLab secret
func (WebhookOptions) Secret(secret string) Option {
return func(hook *Webhook) error {
hook.secret = secret
// already convert here to prevent timing attack (conversion depends on secret)
hash := sha512.Sum512([]byte(secret))
hook.secretHash = hash[:]
return nil
}
}

// Webhook instance contains all methods needed to process events
type Webhook struct {
secret string
secretHash []byte
}

// Event defines a GitLab hook event type by the X-Gitlab-Event Header
Expand Down Expand Up @@ -91,10 +95,10 @@ func (hook Webhook) Parse(r *http.Request, events ...Event) (interface{}, error)
return nil, ErrInvalidHTTPMethod
}

// If we have a Secret set, we should check the MAC
if len(hook.secret) > 0 {
signature := r.Header.Get("X-Gitlab-Token")
if signature != hook.secret {
// If we have a Secret set, we should check in constant time
if len(hook.secretHash) > 0 {
tokenHash := sha512.Sum512([]byte(r.Header.Get("X-Gitlab-Token")))
if subtle.ConstantTimeCompare(tokenHash[:], hook.secretHash[:]) == 0 {
return nil, ErrGitLabTokenVerificationFailed
}
}
Expand Down

0 comments on commit 5f7b060

Please sign in to comment.