From 1622b772ab0af7cf3d8ce6cbe6be7ee17f22b0ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Mon, 20 Apr 2020 23:09:11 +0200 Subject: [PATCH] Allow to read password when stdin is not a tty. --- cmd/sojuctl/main.go | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/cmd/sojuctl/main.go b/cmd/sojuctl/main.go index 841dc80..714a33d 100644 --- a/cmd/sojuctl/main.go +++ b/cmd/sojuctl/main.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "flag" "fmt" "log" @@ -54,12 +55,10 @@ func main() { os.Exit(1) } - fmt.Printf("Password: ") - password, err := terminal.ReadPassword(int(os.Stdin.Fd())) + password, err := readPassword() if err != nil { log.Fatalf("failed to read password: %v", err) } - fmt.Printf("\n") hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { @@ -80,12 +79,10 @@ func main() { os.Exit(1) } - fmt.Printf("New password: ") - password, err := terminal.ReadPassword(int(os.Stdin.Fd())) + password, err := readPassword() if err != nil { - log.Fatalf("failed to read new password: %v", err) + log.Fatalf("failed to read password: %v", err) } - fmt.Printf("\n") hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { @@ -107,3 +104,29 @@ func main() { } } } + +func readPassword() ([]byte, error) { + var password []byte + var err error + fd := int(os.Stdin.Fd()) + + if terminal.IsTerminal(fd) { + fmt.Printf("Password: ") + password, err = terminal.ReadPassword(int(os.Stdin.Fd())) + if err != nil { + return nil, err + } + fmt.Printf("\n") + } else { + fmt.Fprintf(os.Stderr, "Warning: Reading password from stdin.\n") + scanner := bufio.NewScanner(os.Stdin) + scanner.Scan() + password = scanner.Bytes() + + if len(password) == 0 { + return nil, fmt.Errorf("zero length password") + } + } + + return password, nil +}