Skip to content

Commit

Permalink
Make Gitlab token verification constant time (#165)
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.

It's also good practice to hash first to prevent leakage of the length
of the secret, as `subtle.ConstantTimeCompare` has the undesired
behavior of returning early if the length of the two given byte slices
does not match. A hash function always generates a byte slice of
constant length though.
  • Loading branch information
neiser authored May 21, 2023
1 parent ec393fa commit 7647123
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 7647123

Please sign in to comment.