Skip to content

Commit b27f18d

Browse files
authored
Merge pull request #22 from gravitational/ev/username
Better implementation of IsUnixUsername
2 parents b4d67e3 + 1db4b84 commit b27f18d

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

cstrings/split_test.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,15 @@ func (s *USuite) TestUser(c *C) {
9999
name string
100100
expected bool
101101
}{
102-
{name: "admin", expected: true},
103-
{name: "centos", expected: true},
102+
{name: "Admin", expected: true},
103+
{name: "ce-nt.os", expected: true},
104104
{name: "ubuntu-2", expected: true},
105+
{name: "", expected: false},
105106
{name: " ", expected: false},
107+
{name: "-ab", expected: false},
108+
{name: "a/b", expected: false},
109+
{name: "a\tb", expected: false},
110+
{name: "a\nb", expected: false},
106111
{name: " ubuntu ?", expected: false},
107112
{name: strings.Repeat("a", 33), expected: false},
108113
}

cstrings/user.go

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
11
package cstrings
22

33
import (
4-
"regexp"
4+
"strings"
5+
"unicode"
56
)
67

7-
var usersRe = regexp.MustCompile("^[a-z_][a-z0-9_-]*$")
8+
const (
9+
maxUsernameLen = 32
10+
)
811

9-
// IsValidUnixUser returns true if passed string appears to
12+
// IsValidUnixUser returns true if passed string can be used
13+
// to create a valid UNIX user
1014
func IsValidUnixUser(u string) bool {
11-
if len(u) > 32 {
15+
/* See http://www.unix.com/man-page/linux/8/useradd:
16+
17+
On Debian, the only constraints are that usernames must neither start with a dash ('-')
18+
nor contain a colon (':') or a whitespace (space: ' ', end of line: '\n', tabulation:
19+
'\t', etc.). Note that using a slash ('/') may break the default algorithm for the
20+
definition of the user's home directory.
21+
22+
*/
23+
if len(u) > maxUsernameLen || len(u) == 0 || u[0] == '-' {
1224
return false
1325
}
14-
return usersRe.MatchString(u)
26+
if strings.ContainsAny(u, ":/") {
27+
return false
28+
}
29+
for _, r := range u {
30+
if unicode.IsSpace(r) || unicode.IsControl(r) {
31+
return false
32+
}
33+
}
34+
return true
1535
}

0 commit comments

Comments
 (0)