Skip to content

Commit 8debdc1

Browse files
committed
kubeadm: more random tokens
The strategy of hex encoding a random byte array only uses the following characters: 0123456789abcdef Instead of the entire bootstrapping token character set: 0123456789abcdefghijklmnopqrstuvwxyz Update the token generation to use the entire character set. This increases the token secret from 48 bits of entropy to ~82 bits. 256^8 (1.8e+19) vs. 36^16 (7.9e+24).
1 parent df2428c commit 8debdc1

File tree

2 files changed

+32
-10
lines changed

2 files changed

+32
-10
lines changed

cmd/kubeadm/app/util/token/tokens.go

+30-8
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ limitations under the License.
1717
package token
1818

1919
import (
20+
"bufio"
2021
"crypto/rand"
21-
"encoding/hex"
2222
"fmt"
2323
"regexp"
2424

@@ -27,9 +27,9 @@ import (
2727

2828
const (
2929
// TokenIDBytes defines a number of bytes used for a token id
30-
TokenIDBytes = 3
30+
TokenIDBytes = 6
3131
// TokenSecretBytes defines a number of bytes used for a secret
32-
TokenSecretBytes = 8
32+
TokenSecretBytes = 16
3333
)
3434

3535
var (
@@ -43,13 +43,35 @@ var (
4343
TokenRegexp = regexp.MustCompile(TokenRegexpString)
4444
)
4545

46+
const validBootstrapTokenChars = "0123456789abcdefghijklmnopqrstuvwxyz"
47+
4648
func randBytes(length int) (string, error) {
47-
b := make([]byte, length)
48-
_, err := rand.Read(b)
49-
if err != nil {
50-
return "", err
49+
// len("0123456789abcdefghijklmnopqrstuvwxyz") = 36 which doesn't evenly divide
50+
// the possible values of a byte: 256 mod 36 = 4. Discard any random bytes we
51+
// read that are >= 252 so the bytes we evenly divide the character set.
52+
const maxByteValue = 252
53+
54+
var (
55+
b byte
56+
err error
57+
token = make([]byte, length)
58+
)
59+
60+
reader := bufio.NewReaderSize(rand.Reader, length*2)
61+
for i := range token {
62+
for {
63+
if b, err = reader.ReadByte(); err != nil {
64+
return "", err
65+
}
66+
if b < maxByteValue {
67+
break
68+
}
69+
}
70+
71+
token[i] = validBootstrapTokenChars[int(b)%len(validBootstrapTokenChars)]
5172
}
52-
return hex.EncodeToString(b), nil
73+
74+
return string(token), nil
5375
}
5476

5577
// GenerateToken generates a new token with a token ID that is valid as a

cmd/kubeadm/app/util/token/tokens_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,8 @@ func TestRandBytes(t *testing.T) {
147147
if err != nil {
148148
t.Errorf("failed randBytes: %v", err)
149149
}
150-
if len(actual) != rt*2 {
151-
t.Errorf("failed randBytes:\n\texpected: %d\n\t actual: %d\n", rt*2, len(actual))
150+
if len(actual) != rt {
151+
t.Errorf("failed randBytes:\n\texpected: %d\n\t actual: %d\n", rt, len(actual))
152152
}
153153
}
154154
}

0 commit comments

Comments
 (0)