Use regexp instead of substring to do search and replace.

enisoc pointed out how ToLower can change (lengthen even!) the length of
a string given arbitrary input.
pull/6/head
Matt Liggett 2017-04-14 14:25:02 -07:00
parent 55042b0ba9
commit fe202fcfc4
2 changed files with 10 additions and 3 deletions

View File

@ -20,6 +20,7 @@ import (
"bufio"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
@ -58,6 +59,7 @@ var (
},
[]string{"verb", "resource"},
)
kubectlExeRegexp = regexp.MustCompile(`^.*((?i:kubectl\.exe))`)
)
// Register all metrics.
@ -114,9 +116,7 @@ func cleanUserAgent(ua string) string {
return "Browser"
}
// If an old "kubectl.exe" has passed us its full path, we discard the path portion.
if exeIdx := strings.LastIndex(strings.ToLower(ua), "kubectl.exe"); exeIdx != -1 {
return ua[exeIdx:]
}
ua = kubectlExeRegexp.ReplaceAllString(ua, "$1")
return ua
}

View File

@ -19,6 +19,8 @@ package metrics
import "testing"
func TestCleanUserAgent(t *testing.T) {
panicBuf := []byte{198, 73, 129, 133, 90, 216, 104, 29, 13, 134, 209, 233, 30, 0, 22}
for _, tc := range []struct {
In string
Out string
@ -39,6 +41,11 @@ func TestCleanUserAgent(t *testing.T) {
In: `C:\Program Files\kubectl.exe/v1.5.4`,
Out: "kubectl.exe/v1.5.4",
},
{
// This malicious input courtesy of enisoc.
In: string(panicBuf) + "kubectl.exe",
Out: "kubectl.exe",
},
} {
if cleanUserAgent(tc.In) != tc.Out {
t.Errorf("Failed to clean User-Agent: %s", tc.In)