/
getpass.go
315 lines (281 loc) · 7.69 KB
/
getpass.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
/*
* Originally written by Jan Schaumann
* <jschauma@netmeister.org> in May 2022.
*
*/
// Package getpass provides a simple way to retrieve a
// password.
package getpass
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"os/user"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
)
// Getpass retrieves a password from the user using a method defined by
// the 'passfrom' string. The following methods are supported:
//
// cmd:command Obtain the password by running the given command.
// The command will be passed to the shell for execution
// via "/bin/sh -c 'command'".
//
// env:var Obtain the password from the environment variable var.
// Since the environment of other processes may be visible
// via e.g. ps(1), this option should be used with caution.
//
// fd:num Obtain the password from the given file descriptor.
// Note that on many platforms this is functionally equivalent
// to `file:/proc/$$/fd/num`.
//
// file:pathname The first line of pathname is the password. pathname need
// not refer to a regular file: it could for example refer to
// a device or named pipe. Note that standard Unix file
// access controls should be used to protect this file.
//
// keychain:name Use the security(1) utility to retrieve the
// password from the macOS keychain.
//
// lpass:name Use the LastPass command-line client lpass(1) to
// retrieve the named password. You should previously have
// run 'lpass login' for this to work.
//
// op:name Use the 1Password command-line client op(1) to
// retrieve the named password.
//
// pass:password The actual password is password. Since the password is
// visible to utilities such as ps(1) and possibly leaked
// into the shell history file, this form should only be
// used where security is not important.
//
// stdin Read the password from stdin. This is actually a
// convenience alias for `fd:0`; on many platforms the same
// effect can be achieved via `file:/dev/stdin`.
//
// tty:prompt This is the default: `Getpass` will prompt the user on
// the controlling tty using the provided `prompt`. If no
// `prompt` is provided, then `Getpass` will use "Password: ".
//
// This function is variadic purely so that you can invoke it without any
// arguments, thereby defaulting to interactively providing the password
// as if 'passfrom' was set to "tty:Password: ".
func Getpass(passfrom ...string) (pass string, err error) {
var passin []string
source := "tty"
prompt := "Password: "
if len(passfrom) > 1 {
return "", errors.New("invalid number of arguments for Getpass")
}
errMsg := "invalid password source"
if len(passfrom) > 0 {
passin = strings.SplitN(passfrom[0], ":", 2)
if len(passin) < 2 && passfrom[0] != "tty" && passfrom[0] != "stdin" {
return "", errors.New(errMsg)
}
source = passin[0]
}
switch source {
case "cmd":
return getpassFromCommand(passin[1])
case "env":
return getpassFromEnv(passin[1])
case "fd":
return getpassFromFd(passin[1])
case "file":
return getpassFromFile(passin[1])
case "keychain":
return getpassFromKeychain(passin[1])
case "lastpass":
fallthrough
case "lpass":
return getpassFromLastpass(passin[1])
case "onepass":
fallthrough
case "op":
return getpassFromOnepass(passin[1])
case "pass":
return passin[1], nil
case "stdin":
if len(passin) > 1 {
return "", errors.New("'stdin' takes no argument")
}
return getpassFromFd("0")
case "tty":
if len(passin) == 2 {
prompt = passin[1]
}
return getpassFromUser(prompt)
default:
return "", errors.New(errMsg)
}
return pass, nil
}
func getpassFromCommand(command string) (pass string, err error) {
cmd := []string{"/bin/sh", "-c", command}
out, err := runCommand(cmd, "", true)
if err != nil {
return "", err
}
return out, nil
}
func getpassFromEnv(varname string) (pass string, err error) {
errMsg := fmt.Sprintf("environment variable '%v' not set", varname)
pass = os.Getenv(varname)
if len(pass) < 1 {
return "", errors.New(errMsg)
}
return pass, nil
}
func getpassFromFd(fnum string) (pass string, err error) {
i, err := strconv.Atoi(fnum)
if err != nil {
return "", errors.New("invalid file descriptor")
}
fd := os.NewFile(uintptr(i), "fd")
if fd == nil {
return "", errors.New("unable to open fd")
}
scanner := bufio.NewScanner(fd)
for scanner.Scan() {
pass = scanner.Text()
/* We only grab the first line. */
break
}
return pass, nil
}
func getpassFromFile(fname string) (pass string, err error) {
r := regexp.MustCompile(`^~([^/]+)?/`)
m := r.FindStringSubmatch(fname)
if len(m) > 0 {
var u *user.User
if len(m[1]) > 0 {
uname := m[1]
tmp, err := user.Lookup(uname)
if err == nil {
u = tmp
}
} else {
u, err = user.Current()
if err != nil {
return "", err
}
}
if u != nil {
fname = u.HomeDir + fname[strings.Index(fname, "/"):]
}
}
fname = os.ExpandEnv(fname)
file, err := os.Open(fname)
if err != nil {
errMsg := fmt.Sprintf("Unable to open '%s': %v", fname, err)
return "", errors.New(errMsg)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
pass = scanner.Text()
/* We only grab the first line. */
break
}
return pass, nil
}
func getpassFromKeychain(entry string) (pass string, err error) {
cmd := []string{"security", "find-generic-password", "-s", entry, "-w"}
out, err := runCommand(cmd, "", false)
if err != nil {
return "", err
}
return out, nil
}
func getpassFromLastpass(entry string) (pass string, err error) {
cmd := []string{"lpass", "show", entry, "--password"}
out, err := runCommand(cmd, "", false)
if err != nil {
return "", err
}
return out, nil
}
func getpassFromOnepass(entry string) (pass string, err error) {
cmd := []string{"op", "item", "get", entry, "--fields", "password"}
out, err := runCommand(cmd, "", false)
if err != nil {
return "", err
}
return out, nil
}
func getpassFromUser(prompt string) (pass string, err error) {
dev_tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", err
}
fmt.Fprintf(dev_tty, prompt)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
err = stty("echo")
if err != nil {
os.Exit(1)
}
}()
err = stty("-echo")
if err != nil {
return "", err
}
input := bufio.NewReader(dev_tty)
b, err := input.ReadBytes('\n')
if err != nil {
return "", err
}
pass = string(b)
err = stty("echo")
if err != nil {
return "", err
}
fmt.Fprintf(dev_tty, "\n")
return string(pass[:len(pass)-1]), nil
}
func runCommand(args []string, stdinData string, need_tty bool) (string, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if need_tty {
dev_tty, err := os.Open("/dev/tty")
if err != nil {
return "", err
}
cmd.Stdin = dev_tty
} else if len(stdinData) > 0 {
var b bytes.Buffer
b.Write([]byte(stdinData))
cmd.Stdin = &b
}
err := cmd.Run()
if err != nil {
errMsg := fmt.Sprintf("unable to run '%v':\n%v\n%v", strings.Join(args, " "), stderr.String(), err)
return "", errors.New(errMsg)
}
return strings.TrimSpace(stdout.String()), nil
}
func stty(arg string) (err error) {
flag := "-f"
if runtime.GOOS == "linux" {
flag = "-F"
}
err = exec.Command("/bin/stty", flag, "/dev/tty", arg).Run()
if err != nil {
errMsg := fmt.Sprintf("Unable to run stty on /dev/tty: %v", err)
return errors.New(errMsg)
}
return nil
}