Blame SOURCES/011-use-hmac-sha-256-for-password-reset-tokens.patch

b83884
commit f13c08e9f45d7776cb264b17ec41bc4ff51fc0b9
b83884
Author: Andreas Gerstmayr <agerstmayr@redhat.com>
b83884
Date:   Thu Nov 25 18:49:52 2021 +0100
b83884
b83884
    notifications: use HMAC-SHA256 to generate time limit codes
b83884
    
b83884
    * changes the time limit code generation function to use HMAC-SHA256
b83884
      instead of SHA-1
b83884
    * multiple new testcases
b83884
b83884
diff --git a/pkg/services/notifications/codes.go b/pkg/services/notifications/codes.go
b83884
index ea9beb30cc..1ddf05dc69 100644
b83884
--- a/pkg/services/notifications/codes.go
b83884
+++ b/pkg/services/notifications/codes.go
b83884
@@ -1,48 +1,53 @@
b83884
 package notifications
b83884
 
b83884
 import (
b83884
-	"crypto/sha1" // #nosec
b83884
+	"crypto/hmac"
b83884
+	"crypto/sha256"
b83884
 	"encoding/hex"
b83884
 	"fmt"
b83884
+	"strconv"
b83884
 	"time"
b83884
 
b83884
-	"github.com/unknwon/com"
b83884
-
b83884
 	"github.com/grafana/grafana/pkg/models"
b83884
 	"github.com/grafana/grafana/pkg/setting"
b83884
 )
b83884
 
b83884
-const timeLimitCodeLength = 12 + 6 + 40
b83884
+const timeLimitStartDateLength = 12
b83884
+const timeLimitMinutesLength = 6
b83884
+const timeLimitHmacLength = 64
b83884
+const timeLimitCodeLength = timeLimitStartDateLength + timeLimitMinutesLength + timeLimitHmacLength
b83884
 
b83884
 // create a time limit code
b83884
-// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
b83884
-func createTimeLimitCode(data string, minutes int, startInf interface{}) (string, error) {
b83884
+// code format: 12 length date time string + 6 minutes string + 64 HMAC-SHA256 encoded string
b83884
+func createTimeLimitCode(payload string, minutes int, startStr string) (string, error) {
b83884
 	format := "200601021504"
b83884
 
b83884
 	var start, end time.Time
b83884
-	var startStr, endStr string
b83884
+	var endStr string
b83884
 
b83884
-	if startInf == nil {
b83884
+	if startStr == "" {
b83884
 		// Use now time create code
b83884
 		start = time.Now()
b83884
 		startStr = start.Format(format)
b83884
 	} else {
b83884
 		// use start string create code
b83884
-		startStr = startInf.(string)
b83884
-		start, _ = time.ParseInLocation(format, startStr, time.Local)
b83884
-		startStr = start.Format(format)
b83884
+		var err error
b83884
+		start, err = time.ParseInLocation(format, startStr, time.Local)
b83884
+		if err != nil {
b83884
+			return "", err
b83884
+		}
b83884
 	}
b83884
 
b83884
 	end = start.Add(time.Minute * time.Duration(minutes))
b83884
 	endStr = end.Format(format)
b83884
 
b83884
-	// create sha1 encode string
b83884
-	sh := sha1.New()
b83884
-	if _, err := sh.Write([]byte(data + setting.SecretKey + startStr + endStr +
b83884
-		com.ToStr(minutes))); err != nil {
b83884
-		return "", err
b83884
+	// create HMAC-SHA256 encoded string
b83884
+	key := []byte(setting.SecretKey)
b83884
+	h := hmac.New(sha256.New, key)
b83884
+	if _, err := h.Write([]byte(payload + startStr + endStr)); err != nil {
b83884
+		return "", fmt.Errorf("cannot create hmac: %v", err)
b83884
 	}
b83884
-	encoded := hex.EncodeToString(sh.Sum(nil))
b83884
+	encoded := hex.EncodeToString(h.Sum(nil))
b83884
 
b83884
 	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
b83884
 	return code, nil
b83884
@@ -50,30 +55,29 @@ func createTimeLimitCode(data string, minutes int, startInf interface{}) (string
b83884
 
b83884
 // verify time limit code
b83884
 func validateUserEmailCode(user *models.User, code string) (bool, error) {
b83884
-	if len(code) <= 18 {
b83884
+	if len(code) < timeLimitCodeLength {
b83884
 		return false, nil
b83884
 	}
b83884
 
b83884
-	minutes := setting.EmailCodeValidMinutes
b83884
 	code = code[:timeLimitCodeLength]
b83884
 
b83884
 	// split code
b83884
-	start := code[:12]
b83884
-	lives := code[12:18]
b83884
-	if d, err := com.StrTo(lives).Int(); err == nil {
b83884
-		minutes = d
b83884
+	startStr := code[:timeLimitStartDateLength]
b83884
+	minutesStr := code[timeLimitStartDateLength : timeLimitStartDateLength+timeLimitMinutesLength]
b83884
+	minutes, err := strconv.Atoi(minutesStr)
b83884
+	if err != nil {
b83884
+		return false, fmt.Errorf("invalid time limit code: %v", err)
b83884
 	}
b83884
 
b83884
-	// right active code
b83884
-	data := com.ToStr(user.Id) + user.Email + user.Login + user.Password + user.Rands
b83884
-	retCode, err := createTimeLimitCode(data, minutes, start)
b83884
+	// verify code
b83884
+	payload := strconv.FormatInt(user.Id, 10) + user.Email + user.Login + user.Password + user.Rands
b83884
+	expectedCode, err := createTimeLimitCode(payload, minutes, startStr)
b83884
 	if err != nil {
b83884
 		return false, err
b83884
 	}
b83884
-	fmt.Printf("code : %s\ncode2: %s", retCode, code)
b83884
-	if retCode == code && minutes > 0 {
b83884
+	if hmac.Equal([]byte(code), []byte(expectedCode)) && minutes > 0 {
b83884
 		// check time is expired or not
b83884
-		before, _ := time.ParseInLocation("200601021504", start, time.Local)
b83884
+		before, _ := time.ParseInLocation("200601021504", startStr, time.Local)
b83884
 		now := time.Now()
b83884
 		if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
b83884
 			return true, nil
b83884
@@ -94,15 +98,15 @@ func getLoginForEmailCode(code string) string {
b83884
 	return string(b)
b83884
 }
b83884
 
b83884
-func createUserEmailCode(u *models.User, startInf interface{}) (string, error) {
b83884
+func createUserEmailCode(user *models.User, startStr string) (string, error) {
b83884
 	minutes := setting.EmailCodeValidMinutes
b83884
-	data := com.ToStr(u.Id) + u.Email + u.Login + u.Password + u.Rands
b83884
-	code, err := createTimeLimitCode(data, minutes, startInf)
b83884
+	payload := strconv.FormatInt(user.Id, 10) + user.Email + user.Login + user.Password + user.Rands
b83884
+	code, err := createTimeLimitCode(payload, minutes, startStr)
b83884
 	if err != nil {
b83884
 		return "", err
b83884
 	}
b83884
 
b83884
 	// add tail hex username
b83884
-	code += hex.EncodeToString([]byte(u.Login))
b83884
+	code += hex.EncodeToString([]byte(user.Login))
b83884
 	return code, nil
b83884
 }
b83884
diff --git a/pkg/services/notifications/codes_test.go b/pkg/services/notifications/codes_test.go
b83884
index d2b1f3a617..bea88e0bf5 100644
b83884
--- a/pkg/services/notifications/codes_test.go
b83884
+++ b/pkg/services/notifications/codes_test.go
b83884
@@ -1,19 +1,129 @@
b83884
 package notifications
b83884
 
b83884
 import (
b83884
+	"fmt"
b83884
+	"strconv"
b83884
 	"testing"
b83884
+	"time"
b83884
 
b83884
 	"github.com/grafana/grafana/pkg/models"
b83884
 	"github.com/grafana/grafana/pkg/setting"
b83884
 	. "github.com/smartystreets/goconvey/convey"
b83884
+	"github.com/stretchr/testify/require"
b83884
 )
b83884
 
b83884
+func TestTimeLimitCodes(t *testing.T) {
b83884
+	user := &models.User{Id: 10, Email: "t@a.com", Login: "asd", Password: "1", Rands: "2"}
b83884
+
b83884
+	format := "200601021504"
b83884
+	mailPayload := strconv.FormatInt(user.Id, 10) + user.Email + user.Login + user.Password + user.Rands
b83884
+	tenMinutesAgo := time.Now().Add(-time.Minute * 10)
b83884
+
b83884
+	tests := []struct {
b83884
+		desc    string
b83884
+		payload string
b83884
+		start   time.Time
b83884
+		minutes int
b83884
+		valid   bool
b83884
+	}{
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 5 minutes valid",
b83884
+			payload: mailPayload,
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 5,
b83884
+			valid:   false,
b83884
+		},
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 9 minutes valid",
b83884
+			payload: mailPayload,
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 9,
b83884
+			valid:   false,
b83884
+		},
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 10 minutes valid",
b83884
+			payload: mailPayload,
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 10,
b83884
+			// code was valid exactly 10 minutes since evaluating the tenMinutesAgo assignment
b83884
+			// by the time this test is run the code is already expired
b83884
+			valid: false,
b83884
+		},
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 11 minutes valid",
b83884
+			payload: mailPayload,
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 11,
b83884
+			valid:   true,
b83884
+		},
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 20 minutes valid",
b83884
+			payload: mailPayload,
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 20,
b83884
+			valid:   true,
b83884
+		},
b83884
+		{
b83884
+			desc:    "code generated 10 minutes ago, 20 minutes valid, tampered payload",
b83884
+			payload: mailPayload[:len(mailPayload)-1] + "x",
b83884
+			start:   tenMinutesAgo,
b83884
+			minutes: 20,
b83884
+			valid:   false,
b83884
+		},
b83884
+	}
b83884
+
b83884
+	for _, test := range tests {
b83884
+		t.Run(test.desc, func(t *testing.T) {
b83884
+			code, err := createTimeLimitCode(test.payload, test.minutes, test.start.Format(format))
b83884
+			require.NoError(t, err)
b83884
+
b83884
+			isValid, err := validateUserEmailCode(user, code)
b83884
+			require.NoError(t, err)
b83884
+			require.Equal(t, test.valid, isValid)
b83884
+		})
b83884
+	}
b83884
+
b83884
+	t.Run("tampered minutes", func(t *testing.T) {
b83884
+		code, err := createTimeLimitCode(mailPayload, 5, tenMinutesAgo.Format(format))
b83884
+		require.NoError(t, err)
b83884
+
b83884
+		// code is expired
b83884
+		isValid, err := validateUserEmailCode(user, code)
b83884
+		require.NoError(t, err)
b83884
+		require.Equal(t, false, isValid)
b83884
+
b83884
+		// let's try to extend the code by tampering the minutes
b83884
+		code = code[:12] + fmt.Sprintf("%06d", 20) + code[18:]
b83884
+		isValid, err = validateUserEmailCode(user, code)
b83884
+		require.NoError(t, err)
b83884
+		require.Equal(t, false, isValid)
b83884
+	})
b83884
+
b83884
+	t.Run("tampered start string", func(t *testing.T) {
b83884
+		code, err := createTimeLimitCode(mailPayload, 5, tenMinutesAgo.Format(format))
b83884
+		require.NoError(t, err)
b83884
+
b83884
+		// code is expired
b83884
+		isValid, err := validateUserEmailCode(user, code)
b83884
+		require.NoError(t, err)
b83884
+		require.Equal(t, false, isValid)
b83884
+
b83884
+		// let's try to extend the code by tampering the start string
b83884
+		oneMinuteAgo := time.Now().Add(-time.Minute)
b83884
+
b83884
+		code = oneMinuteAgo.Format(format) + code[12:]
b83884
+		isValid, err = validateUserEmailCode(user, code)
b83884
+		require.NoError(t, err)
b83884
+		require.Equal(t, false, isValid)
b83884
+	})
b83884
+}
b83884
+
b83884
 func TestEmailCodes(t *testing.T) {
b83884
 	Convey("When generating code", t, func() {
b83884
 		setting.EmailCodeValidMinutes = 120
b83884
 
b83884
 		user := &models.User{Id: 10, Email: "t@a.com", Login: "asd", Password: "1", Rands: "2"}
b83884
-		code, err := createUserEmailCode(user, nil)
b83884
+		code, err := createUserEmailCode(user, "")
b83884
 		So(err, ShouldBeNil)
b83884
 
b83884
 		Convey("getLoginForCode should return login", func() {
b83884
@@ -27,7 +137,7 @@ func TestEmailCodes(t *testing.T) {
b83884
 			So(isValid, ShouldBeTrue)
b83884
 		})
b83884
 
b83884
-		Convey("Cannot verify in-valid code", func() {
b83884
+		Convey("Cannot verify invalid code", func() {
b83884
 			code = "ASD"
b83884
 			isValid, err := validateUserEmailCode(user, code)
b83884
 			So(err, ShouldBeNil)
b83884
diff --git a/pkg/services/notifications/notifications.go b/pkg/services/notifications/notifications.go
b83884
index beea82f43e..5a575d1415 100644
b83884
--- a/pkg/services/notifications/notifications.go
b83884
+++ b/pkg/services/notifications/notifications.go
b83884
@@ -149,7 +149,7 @@ func (ns *NotificationService) sendEmailCommandHandler(cmd *models.SendEmailComm
b83884
 }
b83884
 
b83884
 func (ns *NotificationService) sendResetPasswordEmail(cmd *models.SendResetPasswordEmailCommand) error {
b83884
-	code, err := createUserEmailCode(cmd.User, nil)
b83884
+	code, err := createUserEmailCode(cmd.User, "")
b83884
 	if err != nil {
b83884
 		return err
b83884
 	}
b83884
diff --git a/pkg/services/notifications/notifications_test.go b/pkg/services/notifications/notifications_test.go
b83884
index e7680c3943..fb73e332ea 100644
b83884
--- a/pkg/services/notifications/notifications_test.go
b83884
+++ b/pkg/services/notifications/notifications_test.go
b83884
@@ -1,12 +1,14 @@
b83884
 package notifications
b83884
 
b83884
 import (
b83884
+	"regexp"
b83884
 	"testing"
b83884
 
b83884
 	"github.com/grafana/grafana/pkg/bus"
b83884
 	"github.com/grafana/grafana/pkg/models"
b83884
 	"github.com/grafana/grafana/pkg/setting"
b83884
 	. "github.com/smartystreets/goconvey/convey"
b83884
+	"github.com/stretchr/testify/require"
b83884
 )
b83884
 
b83884
 func TestNotifications(t *testing.T) {
b83884
@@ -25,13 +27,28 @@ func TestNotifications(t *testing.T) {
b83884
 		So(err, ShouldBeNil)
b83884
 
b83884
 		Convey("When sending reset email password", func() {
b83884
-			err := ns.sendResetPasswordEmail(&models.SendResetPasswordEmailCommand{User: &models.User{Email: "asd@asd.com"}})
b83884
+			user := models.User{Email: "asd@asd.com", Login: "asd@asd.com"}
b83884
+			err := ns.sendResetPasswordEmail(&models.SendResetPasswordEmailCommand{User: &user})
b83884
 			So(err, ShouldBeNil)
b83884
 
b83884
 			sentMsg := <-ns.mailQueue
b83884
 			So(sentMsg.Body, ShouldContainSubstring, "body")
b83884
 			So(sentMsg.Subject, ShouldEqual, "Reset your Grafana password - asd@asd.com")
b83884
 			So(sentMsg.Body, ShouldNotContainSubstring, "Subject")
b83884
+
b83884
+			// find code in mail
b83884
+			r, _ := regexp.Compile(`code=(\w+)`)
b83884
+			match := r.FindString(sentMsg.Body)
b83884
+			code := match[len("code="):]
b83884
+
b83884
+			// verify code
b83884
+			bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error {
b83884
+				query.Result = &user
b83884
+				return nil
b83884
+			})
b83884
+			query := models.ValidateResetPasswordCodeQuery{Code: code}
b83884
+			err = ns.validateResetPasswordCode(&query)
b83884
+			require.NoError(t, err)
b83884
 		})
b83884
 	})
b83884
 }