-
Notifications
You must be signed in to change notification settings - Fork 2
/
password.go
278 lines (224 loc) · 6.18 KB
/
password.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package atoll
import (
"errors"
"fmt"
"math"
"regexp"
"strings"
)
// Password level.
const (
Lowercase = Level("abcdefghijklmnopqrstuvwxyz")
Uppercase = Level("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Digit = Level("0123456789")
Space = Level(" ")
Special = Level("&$%@#|/\\=\"*~^`'.?!,;:-+_(){}[]<>")
)
// Level represents a determined group of characters.
type Level string
// Password represents a sequence of characters required for access to a computer system.
type Password struct {
pool string
// Password length.
Length uint64
// Group of characters used to generate the pool.
Levels []Level
// Characters that will be part of the password.
Include string
// Characters that won't be part of the password.
Exclude string
// Character repetition.
Repeat bool
}
// NewPassword returns a random password.
func NewPassword(length uint64, levels []Level) (string, error) {
p := &Password{
Length: length,
Levels: levels,
}
return p.Generate()
}
// Generate generates a random password.
func (p *Password) Generate() (string, error) {
password, err := p.generate()
if err != nil {
return "", fmt.Errorf("atoll: %v", err)
}
return password, nil
}
func (p *Password) generate() (string, error) {
if p.Length < 1 {
return "", errors.New("invalid password length")
}
if len(p.Levels) == 0 {
return "", errors.New("no levels were specified")
}
if strings.ContainsAny(p.Include, p.Exclude) {
return "", errors.New("included characters cannot be excluded")
}
// Check if include contains 2/3 bytes characters
for _, incl := range p.Include {
if len(string(incl)) != 1 {
return "", fmt.Errorf("include contains invalid characters: %q", string(incl))
}
}
if len(p.Include) > int(p.Length) {
return "", errors.New("characters to include exceed the password length")
}
if err := p.validateLevels(); err != nil {
return "", err
}
p.generatePool()
if p.Exclude != "" {
// Remove excluded characters from the pool
exclChars := strings.Split(p.Exclude, "")
for _, c := range exclChars {
p.pool = strings.Replace(p.pool, c, "", 1)
}
}
if !p.Repeat && int(p.Length) > (len(p.pool)+len(p.Include)) {
return "", errors.New("password length is higher than the pool and repetition is turned off")
}
password := p.initPassword()
// Subtract the number of characters already added to the password from the total length
remaining := int(p.Length) - len(password)
for i := 0; i < remaining; i++ {
char := p.pool[randInt(len(p.pool))]
password = randInsert(password, char)
if !p.Repeat {
// Remove element used
p.pool = strings.Replace(p.pool, string(char), "", 1)
}
}
password = p.sanitize(password)
return password, nil
}
func (p *Password) generatePool() {
var sb strings.Builder
unique := make(map[Level]struct{})
for _, lvl := range p.Levels {
// Ensure that duplicated levels aren't added twice
if _, ok := unique[lvl]; !ok && len(lvl) > 0 {
unique[lvl] = struct{}{}
sb.Grow(len(lvl))
sb.WriteString(string(lvl))
}
}
p.pool = sb.String()
}
// initPassword creates the password, adds any included word and makes sure that it contains
// at least 1 character of each level (only if p.Length is longer than levels).
func (p *Password) initPassword() string {
var (
password string
char byte
)
// Add included characters
for _, c := range p.Include {
password = randInsert(password, byte(c))
if !p.Repeat {
// Remove character used
p.pool = strings.Replace(p.pool, string(c), "", 1)
}
}
if int(p.Length) < len(p.Levels) {
return password
}
for _, lvl := range p.Levels {
repeat:
char = lvl[randInt(len(lvl))]
// If the pool does not contain the character selected it's because
// it was either excluded or already used
if !strings.Contains(p.pool, string(char)) {
if lvl == Space {
continue
}
goto repeat
}
password = randInsert(password, char)
if !p.Repeat {
// Remove character used
p.pool = strings.Replace(p.pool, string(char), "", 1)
}
}
return password
}
// sanitize clears common patterns and removes leading and trailing spaces.
func (p *Password) sanitize(password string) string {
password = strings.TrimSpace(password)
// In case any space was removed, generate new characters and add
// them to the password to meet the length required
if len(password) < int(p.Length) {
offset := int(p.Length) - len(password)
for i := 0; i < offset; i++ {
// Add remaining characters in random positions
password = randInsert(password, p.pool[randInt(len(p.pool))])
}
}
// Shuffle the password in case it has common patterns until it doesn't
repeat:
if regexp.MustCompile(commonPatterns).MatchString(password) {
password = shuffle([]rune(password))
goto repeat
}
return password
}
// validateLevels checks if Exclude contains all the characters of a level that is in Levels.
func (p *Password) validateLevels() error {
for _, lvl := range p.Levels {
if len(lvl) < 1 {
return errors.New("empty levels aren't allowed")
}
counter := 0
for _, excl := range p.Exclude {
if strings.Contains(string(lvl), string(excl)) {
counter++
// Stop counting if the character is a space (as it's only one)
if lvl == Space {
break
}
}
}
if counter == len(lvl) {
var lvlName string
switch lvl {
case Lowercase:
lvlName = "lowercase"
case Uppercase:
lvlName = "uppercase"
case Digit:
lvlName = "digit"
case Space:
lvlName = "space"
case Special:
lvlName = "special"
default:
lvlName = "custom"
}
return fmt.Errorf("%s level is used and all its characters are excluded", lvlName)
}
}
return nil
}
// Entropy returns the password entropy in bits.
func (p *Password) Entropy() float64 {
poolLength := len(p.pool)
if p.pool == "" {
p.generatePool()
poolLength = len(p.pool)
if !p.Repeat {
poolLength -= int(p.Length)
}
// Do not count 2/3 byte characters as they aren't in the pool
for _, excl := range p.Exclude {
if len(string(excl)) != 1 {
poolLength -= strings.Count(p.Exclude, string(excl))
}
}
}
// Add the characters that were removed from the pool
if !p.Repeat {
poolLength += int(p.Length)
}
return math.Log2(math.Pow(float64(poolLength), float64(p.Length)))
}