-
-
Notifications
You must be signed in to change notification settings - Fork 497
/
generate.go
406 lines (356 loc) · 10.7 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
package action
import (
"context"
"fmt"
"path"
"regexp"
"sort"
"strconv"
"strings"
"github.com/gopasspw/gopass/internal/clipboard"
"github.com/gopasspw/gopass/internal/debug"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/internal/termio"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/gopasspw/gopass/pkg/gopass"
"github.com/gopasspw/gopass/pkg/gopass/secret"
"github.com/gopasspw/gopass/pkg/gopass/secret/secparse"
"github.com/gopasspw/gopass/pkg/pwgen"
"github.com/gopasspw/gopass/pkg/pwgen/pwrules"
"github.com/gopasspw/gopass/pkg/pwgen/xkcdgen"
"github.com/fatih/color"
"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")
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 ExitError(ExitNoName, 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 ExitError(ExitAborted, 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 ExitError(ExitUnknown, err, "failed to edit '%s': %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.Print(ctx, "Password for %s generated", entry)
if ctxutil.IsAutoClip(ctx) || IsClip(ctx) {
if err := clipboard.CopyTo(ctx, name, []byte(password)); err != nil {
return ExitError(ExitIO, err, "failed to copy to clipboard: %s", err)
}
if ctxutil.IsAutoClip(ctx) && !c.Bool("print") {
return nil
}
}
if !c.Bool("print") {
return nil
}
if c.IsSet("print") && !c.Bool("print") && ctxutil.IsShowSafeContent(ctx) {
return nil
}
out.Print(
ctx,
"The generated password is:\n%s",
color.YellowString(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 != "" {
out.Yellow(ctx, "Using password rules for %s ...", domain)
wl := 16
if iv, err := strconv.Atoi(length); err == nil {
if iv < rule.Minlen {
iv = rule.Minlen
}
if iv > rule.Maxlen {
iv = rule.Maxlen
}
wl = 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 "", ExitError(ExitUsage, 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
}
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 "", ExitError(ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ExitUsage, err, "password length must be a number")
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ExitUsage, nil, "password length must not be zero")
}
switch c.String("generator") {
case "xkcd":
return s.generatePasswordXKCD(ctx, c, length)
case "memorable":
return pwgen.GenerateMemorablePassword(pwlen, symbols), nil
case "external":
return pwgen.GenerateExternal(pwlen)
default:
if c.Bool("strict") {
return pwgen.GeneratePasswordWithAllClasses(pwlen)
}
return pwgen.GeneratePassword(pwlen, symbols), 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 "", ExitError(ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ExitUsage, err, "password length must be a number: %s", err)
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ExitUsage, 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 a yaml doc
if key != "" {
gs, err := s.Store.Get(ctx, name)
if err != nil {
return ctx, ExitError(ExitEncrypt, err, "failed to set key '%s' of '%s': %s", key, name, err)
}
sec := gs.MIME()
setMetadata(sec, kvps)
sec.Set(key, password)
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated password for YAML key"), name, sec); err != nil {
return ctx, ExitError(ExitEncrypt, err, "failed to set key '%s' of '%s': %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.Error(ctx, "Failed to read existing secret. Creating anew. Error: %s", err.Error())
}
// generate a completely new secret
var sec gopass.Secret
sec = secret.New()
sec.Set("password", password)
if u := hasChangeURL(name); u != "" {
sec.Set("password-change-url", u)
}
if content, found := s.renderTemplate(ctx, name, []byte(password)); found {
nSec, err := secparse.Parse(content)
if err == nil {
sec = nSec
} else {
debug.Log("failed to parse template: %s", err)
}
}
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated Password"), name, sec); err != nil {
return ctx, ExitError(ExitEncrypt, err, "failed to create '%s': %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, ExitError(ExitEncrypt, err, "failed to set key '%s' of '%s': %s", key, name, err)
}
setMetadata(sec, kvps)
sec.Set("password", password)
if err := s.Store.Set(ctxutil.WithCommitMessage(ctx, "Generated password for YAML key"), name, sec); err != nil {
return ctx, ExitError(ExitEncrypt, err, "failed to set key '%s' of '%s': %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)
_, err := s.Store.Initialized(ctx) // important to make sure the structs are not nil
if err != nil {
out.Error(ctx, "Store not initialized: %s", err)
return
}
list, err := s.Store.List(ctx, 0)
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
}