-
-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathgenerate.go
428 lines (372 loc) · 11.6 KB
/
generate.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package action
import (
"context"
"fmt"
"path"
"regexp"
"sort"
"strconv"
"strings"
"github.com/gopasspw/gopass/internal/action/exit"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/internal/tree"
"github.com/gopasspw/gopass/pkg/clipboard"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/gopasspw/gopass/pkg/debug"
"github.com/gopasspw/gopass/pkg/gopass"
"github.com/gopasspw/gopass/pkg/gopass/secrets"
"github.com/gopasspw/gopass/pkg/pwgen"
"github.com/gopasspw/gopass/pkg/pwgen/pwrules"
"github.com/gopasspw/gopass/pkg/pwgen/xkcdgen"
"github.com/gopasspw/gopass/pkg/termio"
"github.com/urfave/cli/v2"
)
const (
defaultLength = 24
defaultXKCDLength = 4
)
var (
reNumber = regexp.MustCompile(`^\d+$`)
)
// Generate and save a password.
func (s *Action) Generate(c *cli.Context) error {
ctx := ctxutil.WithGlobalFlags(c)
ctx = WithClip(ctx, c.Bool("clip"))
force := c.Bool("force")
edit := c.Bool("edit") // nolint:ifshort
args, kvps := parseArgs(c)
name := args.Get(0)
key, length := keyAndLength(args)
ctx = ctxutil.WithForce(ctx, force)
// ask for name of the secret if it wasn't provided already.
if name == "" {
var err error
name, err = termio.AskForString(ctx, "Which name do you want to use?", "")
if err != nil || name == "" {
return exit.Error(exit.NoName, err, "please provide a password name")
}
}
// ask for confirmation before overwriting existing entry.
if !force { // don't check if it's force anyway.
if s.Store.Exists(ctx, name) && key == "" && !termio.AskForConfirmation(ctx, fmt.Sprintf("An entry already exists for %s. Overwrite the current password?", name)) {
return exit.Error(exit.Aborted, nil, "user aborted. not overwriting your current password")
}
}
// generate password.
password, err := s.generatePassword(ctx, c, length, name)
if err != nil {
return err
}
// display or copy to clipboard.
if err := s.generateCopyOrPrint(ctx, c, name, key, password); err != nil {
return err
}
// write generated password to store.
ctx, err = s.generateSetPassword(ctx, name, key, password, kvps)
if err != nil {
return err
}
// if requested launch editor to add more data to the generated secret.
if edit && termio.AskForConfirmation(ctx, fmt.Sprintf("Do you want to add more data for %s?", name)) {
c.Context = ctx
if err := s.Edit(c); err != nil {
return exit.Error(exit.Unknown, err, "failed to edit %q: %s", name, err)
}
}
return nil
}
func keyAndLength(args argList) (string, string) {
key := args.Get(1)
length := args.Get(2)
// generate can be called with one positional arg or two.
// * one - the desired length for the "master" secret itself
// * two - the key in a YAML doc and the length for a secret generated for this
// key only.
if length == "" && key != "" && reNumber.MatchString(key) {
length = key
key = ""
}
return key, length
}
// generateCopyOrPrint will print the password to the screen or copy to the
// clipboard.
func (s *Action) generateCopyOrPrint(ctx context.Context, c *cli.Context, name, key, password string) error {
entry := name
if key != "" {
entry += ":" + key
}
out.OKf(ctx, "Password for entry %q generated", entry)
// copy to clipboard if:
// - explicitly requested with -c
// - autoclip=true, but only if output is not being redirected.
if IsClip(ctx) || (s.cfg.AutoClip && ctxutil.IsTerminal(ctx)) {
if err := clipboard.CopyTo(ctx, name, []byte(password), s.cfg.ClipTimeout); err != nil {
return exit.Error(exit.IO, err, "failed to copy to clipboard: %s", err)
}
// if autoclip is on and we're not printing the password to the terminal
// at least leave a notice that we did indeed copy it.
if s.cfg.AutoClip && !c.Bool("print") {
out.Print(ctx, "Copied to clipboard")
return nil
}
}
if !c.Bool("print") {
out.Printf(ctx, "Not printing secrets by default. Use 'gopass show %s' to display the password.", entry)
return nil
}
if c.IsSet("print") && !c.Bool("print") && ctxutil.IsShowSafeContent(ctx) {
debug.Log("safecontent suppresing printing")
return nil
}
out.Printf(
ctx,
"⚠ The generated password is:\n\n%s\n",
out.Secret(password),
)
return nil
}
func hasPwRuleForSecret(name string) (string, pwrules.Rule) {
for name != "" && name != "." {
d := path.Base(name)
if r, found := pwrules.LookupRule(d); found {
return d, r
}
name = path.Dir(name)
}
return "", pwrules.Rule{}
}
// generatePassword will run through the password generation steps.
func (s *Action) generatePassword(ctx context.Context, c *cli.Context, length, name string) (string, error) {
if domain, rule := hasPwRuleForSecret(name); domain != "" {
return s.generatePasswordForRule(ctx, c, length, name, domain, rule)
}
symbols := false
if c.IsSet("symbols") {
symbols = c.Bool("symbols")
}
var pwlen int
if length == "" {
candidateLength := defaultLength
question := "How long should the password be?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", exit.Error(exit.Usage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", exit.Error(exit.Usage, err, "password length must be a number")
}
pwlen = iv
}
if pwlen < 1 {
return "", exit.Error(exit.Usage, nil, "password length must not be zero")
}
switch c.String("generator") {
case "xkcd":
return s.generatePasswordXKCD(ctx, c, length)
case "memorable":
if c.Bool("strict") {
return pwgen.GenerateMemorablePassword(pwlen, symbols, true), nil
}
return pwgen.GenerateMemorablePassword(pwlen, symbols, false), nil
case "external":
return pwgen.GenerateExternal(pwlen)
default:
if c.Bool("strict") {
return pwgen.GeneratePasswordWithAllClasses(pwlen, symbols)
}
return pwgen.GeneratePassword(pwlen, symbols), nil
}
}
func clamp(min, max, value int) int {
if value < min {
return min
}
if value > max {
return max
}
return value
}
func (s *Action) generatePasswordForRule(ctx context.Context, c *cli.Context, length, name, domain string, rule pwrules.Rule) (string, error) {
out.Printf(ctx, "Using password rules for %s ...", domain)
wl := 16
if iv, err := strconv.Atoi(length); err == nil {
wl = clamp(rule.Minlen, rule.Maxlen, iv)
}
question := fmt.Sprintf("How long should the password be? (min: %d, max: %d)", rule.Minlen, rule.Maxlen)
iv, err := termio.AskForInt(ctx, question, wl)
if err != nil {
return "", exit.Error(exit.Usage, err, "password length must be a number")
}
pw := pwgen.NewCrypticForDomain(iv, domain).Password()
if pw == "" {
return "", fmt.Errorf("failed to generate password for %s", domain)
}
return pw, nil
}
// generatePasswordXKCD walks through the steps necessary to create an XKCD-style
// password.
func (s *Action) generatePasswordXKCD(ctx context.Context, c *cli.Context, length string) (string, error) {
xkcdSeparator := " "
if c.IsSet("sep") {
xkcdSeparator = c.String("sep")
}
var pwlen int
if length == "" {
candidateLength := defaultXKCDLength
question := "How many words should be combined to a password?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", exit.Error(exit.Usage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", exit.Error(exit.Usage, err, "password length must be a number: %s", err)
}
pwlen = iv
}
if pwlen < 1 {
return "", exit.Error(exit.Usage, nil, "password length must not be zero")
}
return xkcdgen.RandomLengthDelim(pwlen, xkcdSeparator, c.String("lang"))
}
// generateSetPassword will update or create a secret.
func (s *Action) generateSetPassword(ctx context.Context, name, key, password string, kvps map[string]string) (context.Context, error) {
// set a single key in an entry.
if key != "" {
sec, err := s.Store.Get(ctx, name)
if err != nil {
return ctx, exit.Error(exit.Encrypt, err, "failed to set key %q of %q: %s", key, name, err)
}
setMetadata(sec, kvps)
sec.Set(key, password)
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated password for key"), name, sec); err != nil {
return ctx, exit.Error(exit.Encrypt, err, "failed to set key %q of %q: %s", key, name, err)
}
return ctx, nil
}
// replace password in existing secret.
if s.Store.Exists(ctx, name) {
ctx, err := s.generateReplaceExisting(ctx, name, key, password, kvps)
if err == nil {
return ctx, nil
}
out.Errorf(ctx, "Failed to read existing secret. Creating anew. Error: %s", err.Error())
}
// generate a completely new secret.
var sec gopass.Secret
sec = secrets.New()
sec.SetPassword(password)
if u := hasChangeURL(name); u != "" {
sec.Set("password-change-url", u)
}
if content, found := s.renderTemplate(ctx, name, []byte(password)); found {
nSec := &secrets.Plain{}
if _, err := nSec.Write(content); err == nil {
sec = nSec
} else {
debug.Log("failed to handle template: %s", err)
}
}
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated Password"), name, sec); err != nil {
return ctx, exit.Error(exit.Encrypt, err, "failed to create %q: %s", name, err)
}
return ctx, nil
}
func hasChangeURL(name string) string {
p := strings.Split(name, "/")
for i := len(p) - 1; i > 0; i-- {
if u := pwrules.LookupChangeURL(p[i]); u != "" {
return u
}
}
return ""
}
func (s *Action) generateReplaceExisting(ctx context.Context, name, key, password string, kvps map[string]string) (context.Context, error) {
sec, err := s.Store.Get(ctx, name)
if err != nil {
return ctx, exit.Error(exit.Encrypt, err, "failed to set key %q of %q: %s", key, name, err)
}
setMetadata(sec, kvps)
sec.SetPassword(password)
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated password for YAML key"), name, sec); err != nil {
return ctx, exit.Error(exit.Encrypt, err, "failed to set key %q of %q: %s", key, name, err)
}
return ctx, nil
}
func setMetadata(sec gopass.Secret, kvps map[string]string) {
for k, v := range kvps {
sec.Set(k, v)
}
}
// CompleteGenerate implements the completion heuristic for the generate command.
func (s *Action) CompleteGenerate(c *cli.Context) {
ctx := ctxutil.WithGlobalFlags(c)
if c.Args().Len() < 1 {
return
}
needle := c.Args().Get(0) // nolint:ifshort
_, err := s.Store.IsInitialized(ctx) // important to make sure the structs are not nil.
if err != nil {
out.Errorf(ctx, "Store not initialized: %s", err)
return
}
list, err := s.Store.List(ctx, tree.INF)
if err != nil {
return
}
if strings.Contains(needle, "/") {
list = filterPrefix(uniq(extractEmails(list)), path.Base(needle))
} else {
list = filterPrefix(uniq(extractDomains(list)), needle)
}
for _, v := range list {
fmt.Fprintln(stdout, bashEscape(v))
}
}
func extractEmails(list []string) []string {
results := make([]string, 0, len(list))
for _, e := range list {
e = path.Base(e)
if strings.Contains(e, "@") || strings.Contains(e, "_") {
results = append(results, e)
}
}
return results
}
var reDomain = regexp.MustCompile(`^(?i)([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$`)
func extractDomains(list []string) []string {
results := make([]string, 0, len(list))
for _, e := range list {
e = path.Base(e)
if reDomain.MatchString(e) {
results = append(results, e)
}
}
return results
}
func uniq(in []string) []string {
set := make(map[string]struct{}, len(in))
for _, e := range in {
set[e] = struct{}{}
}
out := make([]string, 0, len(set))
for k := range set {
out = append(out, k)
}
sort.Strings(out)
return out
}
func filterPrefix(in []string, prefix string) []string {
out := make([]string, 0, len(in))
for _, e := range in {
if strings.HasPrefix(e, prefix) {
out = append(out, e)
}
}
return out
}