func createNewVault(path string, lowSecurity bool) { if !strings.HasSuffix(path, ".agilekeychain") { path += ".agilekeychain" } fmt.Printf("Creating new vault in %s\n", path) fmt.Printf("Enter master password: "******"\nRe-enter master password: "******"Passwords do not match") } security := onepass.VaultSecurity{MasterPwd: string(masterPwd)} if lowSecurity { // use fewer PBKDF2 iterations to speed up // master key decryption security.Iterations = 10 } _, err = onepass.NewVault(path, security) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create new vault: %v", err) } }
func createPasswd() { _, err := os.Stat(KEY_ROOT_PASSWD) if err != nil { fmt.Printf("This is your first time working with zzkey\n") fmt.Printf("Please input a password to protect your infomation\n") } fmt.Printf("Password :"******"\n") fmt.Printf("Repeat :") buf1, _ := terminal.ReadPassword(int(os.Stdin.Fd())) fmt.Printf("\n") if string(buf) != string(buf1) { fmt.Printf("not match\n") return } password = string(buf) buf2 := string(buf) + "--salt add by zzkey--" h := sha1.New() io.WriteString(h, buf2) buf2 = fmt.Sprintf("%x", h.Sum(nil)) ioutil.WriteFile(KEY_ROOT_PASSWD, []byte(buf2), 0600) fmt.Println("Password has been set,Having Fun With zzkey!") }
func setRecord(p string) { if e := getRecord(p); e == nil { fmt.Fprintf(os.Stderr, "record already exists\n") return } fmt.Printf("use random password ?\n[y/n] ") ra := bufio.NewReader(os.Stdin) uinput, _, _ := ra.ReadLine() var setpass string if string(uinput) == "y" { pass := randomPasswd(16) fmt.Printf("random password : %s\n", pass) setpass = pass } else { fmt.Printf("%s's Password :"******"\n") fmt.Printf("Repeat Password :"******"\n") if string(pass) != string(passagain) { fmt.Fprintf(os.Stderr, "not match\n") return } setpass = string(pass) } fmt.Printf("%s's Description : ", p) r := bufio.NewReader(os.Stdin) input, _, _ := r.ReadLine() description := string(input) i := Info{p, string(setpass), string(description)} j, _ := json.Marshal(i) j = append(j, '\n') content := string(j) _, err := os.Stat(KEY_ROOT_DB) if err == nil { buf, _ := ioutil.ReadFile(KEY_ROOT_DB) content = decryptFromBase64(string(buf), password) content += string(j) } k := encryptToBase64(content, password) if e := ioutil.WriteFile(KEY_ROOT_DB, []byte(k), 0600); e != nil { fmt.Fprintf(os.Stderr, "add record failed") } fmt.Printf("record add to the database\n") }
func fetchPass() *string { fmt.Print("Enter Password: ") passwordByte, _ := terminal.ReadPassword(0) password := string(passwordByte) password = strings.TrimSpace(password) return &password }
// handleGetPass reads a line of input from a terminal without local echo. func handleGetPass(r *Request) (interface{}, error) { fmt.Print(r.Args.One().MustString()) data, err := terminal.ReadPassword(0) // stdin fmt.Println() if err != nil { return nil, err } return string(data), nil }
func readpass(prompt string) string { fmt.Printf(prompt) bs, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return "" } fmt.Println() return string(bs) }
func setPassword(vault *onepass.Vault, currentPwd string) { // TODO - Prompt for hint and save that to the .password.hint file fmt.Printf("New master password: "******"\nRe-enter new master password: "******"Passwords do not match") } err = vault.SetMasterPassword(currentPwd, string(newPwd)) if err != nil { fatalErr(err, "Failed to change master password") } fmt.Printf("The master password has been updated.\n\n") fmt.Printf(setPasswordSyncNote) }
func getPassphrase(prompt string) []byte { var h hash.Hash = sha512.New384() fmt.Fprintf(os.Stdout, prompt) phrase, err := terminal.ReadPassword(int(os.Stdin.Fd())) fmt.Fprintf(os.Stdout, "\n") if err != nil { log.Fatal(err) } io.Copy(h, bytes.NewReader(phrase)) return h.Sum(nil) }
func readNewPassword(passType string) (string, error) { fmt.Printf("%s (or '-' for a random new %s): ", passType, passType) pwd, _ := terminal.ReadPassword(0) if len(pwd) == 0 { fmt.Println() return "", nil } if string(pwd) == "-" { pwd = []byte(genDefaultPassword()) fmt.Printf("(Random new password generated)") } else { fmt.Printf("\nRe-enter %s: ", passType) pwd2, _ := terminal.ReadPassword(0) if string(pwd) != string(pwd2) { return "", fmt.Errorf("Passwords do not match") } } fmt.Println() return string(pwd), nil }
func main() { if len(os.Args) != 3 { fmt.Fprintf(os.Stderr, "Usage: %s <path to private key> <encrypted password>\n", os.Args[0]) os.Exit(1) } pemPath := os.Args[1] encryptedPasswdB64 := os.Args[2] encryptedPasswd, err := base64.StdEncoding.DecodeString(encryptedPasswdB64) if err != nil { panic(err) } pemBytes, err := ioutil.ReadFile(pemPath) if err != nil { panic(err) } block, _ := pem.Decode(pemBytes) var asn1Bytes []byte if _, ok := block.Headers["DEK-Info"]; ok { fmt.Printf("Encrypted private key. Please enter passphrase: ") password, err := terminal.ReadPassword(0) fmt.Printf("\n") if err != nil { panic(err) } asn1Bytes, err = x509.DecryptPEMBlock(block, password) if err != nil { panic(err) } } else { asn1Bytes = block.Bytes } key, err := x509.ParsePKCS1PrivateKey(asn1Bytes) if err != nil { panic(err) } out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd) if err != nil { panic(err) } fmt.Printf("Decrypted password: %s\n", string(out)) }
func changePasswd() { fmt.Printf("current password :"******"\n") if string(currentPass) != password { fmt.Fprintf(os.Stderr, "password error\n") return } createPasswd() buf, _ := ioutil.ReadFile(KEY_ROOT_DB) data := decryptFromBase64(string(buf), string(currentPass)) k := encryptToBase64(data, password) ioutil.WriteFile(KEY_ROOT_DB, []byte(k), 0600) fmt.Printf("password changed\n") }
func verifyPasswd() (p string, e error) { buf, _ := ioutil.ReadFile(KEY_ROOT_PASSWD) fmt.Printf("Password :"******"\n") pass2 := string(pass) + "--salt add by zzkey--" h := sha1.New() io.WriteString(h, pass2) pass2 = fmt.Sprintf("%x", h.Sum(nil)) if pass2 == string(buf) { p, e = pass2, nil password = string(pass) return } p, e = "", errors.New("Wrong Password") return }
func main() { input, err := terminal.ReadPassword(0) if err != nil { panic(err) } secret := string(input) parts := EasySplit(secret, 6, 3) fmt.Println(parts) newshares := []string{parts[1], parts[2], parts[5]} result := EasyJoin(newshares) fmt.Println(result) }
func passwordFromReader(reader io.Reader) (string, error) { var ( password []byte err error ) if file, ok := reader.(*os.File); ok && terminal.IsTerminal(int(file.Fd())) { password, err = terminal.ReadPassword(int(file.Fd())) if err != nil { return "", err } } else { fmt.Fscanf(reader, "%s\n", &password) } if len(password) == 0 { msg := "You must provide the password!" return "", errors.New(msg) } return string(password), err }
// Load the TLS certificate from the speciified files. The key file can be an encryped // PEM so long as it carries the appropriate headers (Proc-Type and Dek-Info) and the // password will be requested interactively. func LoadCertificate(crtFile, keyFile string) (tls.Certificate, error) { crtBytes, err := ioutil.ReadFile(crtFile) if err != nil { return tls.Certificate{}, err } keyBytes, err := ioutil.ReadFile(keyFile) if err != nil { return tls.Certificate{}, err } keyDer, _ := pem.Decode(keyBytes) if keyDer == nil { return tls.Certificate{}, fmt.Errorf("%s cannot be decoded.", keyFile) } // http://www.ietf.org/rfc/rfc1421.txt if !strings.HasPrefix(keyDer.Headers["Proc-Type"], "4,ENCRYPTED") { return tls.X509KeyPair(crtBytes, keyBytes) } fmt.Printf("%s\nPassword: "******"RSA PRIVATE KEY", Headers: map[string]string{}, Bytes: keyDec, })) }
func login(reauth bool) { if reauth { type arg struct { Eauth string `json:"eauth"` Username string `json:"username"` Password string `json:"password"` } type ret struct { Token string Start float64 Expire float64 User string Eauth string Perms []string } var req *http.Request var res *http.Response c := &http.Client{Jar: jar} fmt.Fprintf(os.Stdout, "Password: "******"\n") // prompt for pass b, err := json.Marshal(&arg{*eauth, *user, string(pass)}) req = mkReq("POST", "login", &b) res, err = c.Do(req) if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } if res.StatusCode == http.StatusUnauthorized { fmt.Fprintf(os.Stderr, "Authentication failed.\n") os.Exit(2) } //fmt.Fprintf(os.Stderr, "debug: %+v\n", res) //fmt.Fprintf(os.Stderr, "debug: %+v\n", res.Body) d := json.NewDecoder(res.Body) var resp map[string][]ret err = d.Decode(&resp) if err != nil { fmt.Fprintf(os.Stderr, "error: %+v\n", err) } //fmt.Fprintf(os.Stderr, "debug: login response: %+v\n", resp) auth = resp["return"][0].Token } else { var token string = fmt.Sprintf("%s/token", *configDir) // Look for an existing token fi, err := os.Stat(*configDir) if err != nil || !fi.IsDir() { os.MkdirAll(*configDir, 0700) } _, err = os.Stat(token) if err != nil { fmt.Fprintf(os.Stderr, "info: no token found\n") } else { f, err := os.Open(token) if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } d := json.NewDecoder(f) d.Decode(&auth) f.Close() } jar.SetCookies(serverUrl, []*http.Cookie{&http.Cookie{Name: "session_id", Value: auth}}) } //fmt.Fprintf(os.Stderr, "info: token: %s\n", auth) }
func xreadPassword(fd int) ([]byte, error) { return terminal.ReadPassword(fd) }
func do() bool { if err := system.IsSafe(); err != nil { fmt.Fprintf(os.Stderr, "System checks failed: %s\n", err) return false } editor := os.Getenv("EDITOR") if len(editor) == 0 { fmt.Fprintf(os.Stderr, "$EDITOR is not set\n") return false } stateFile := &disk.StateFile{ Path: *stateFileName, Rand: crypto_rand.Reader, Log: func(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) }, } stateLock, err := stateFile.Lock(false /* don't create */) if err != nil { fmt.Fprintf(os.Stderr, "Cannot open state file: %s\n", err) return false } if stateLock == nil { fmt.Fprintf(os.Stderr, "Cannot obtain lock on state file\n") return false } defer stateLock.Close() var state *disk.State var passphrase string for { state, err = stateFile.Read(passphrase) if err == nil { break } if err != disk.BadPasswordError { fmt.Fprintf(os.Stderr, "Failed to decrypt state file: %s\n", err) return false } fmt.Fprintf(os.Stderr, "Passphrase: ") passphraseBytes, err := terminal.ReadPassword(0) fmt.Fprintf(os.Stderr, "\n") if err != nil { fmt.Fprintf(os.Stderr, "Failed to read password\n") return false } passphrase = string(passphraseBytes) } tempDir, err := system.SafeTempDir() if err != nil { fmt.Fprintf(os.Stderr, "Failed to get safe temp directory: %s\n", err) return false } tempFile, err := ioutil.TempFile(tempDir, "pond-editstate-") if err != nil { fmt.Fprintf(os.Stderr, "Failed to create temp file: %s\n", err) return false } tempFileName := tempFile.Name() defer func() { os.Remove(tempFileName) }() signals := make(chan os.Signal, 8) signal.Notify(signals, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) go func() { <-signals println("Caught signal: removing", tempFileName) os.Remove(tempFileName) os.Exit(1) }() entities := serialise(tempFile, state) var newStateSerialized []byte for { cmd := exec.Command(editor, tempFileName) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintf(os.Stderr, "Failed to run editor: %s\n", err) return false } tempFile.Close() tempFile, err := os.Open(tempFileName) if err != nil { fmt.Fprintf(os.Stderr, "Failed to open temp file: %s\n", err) return false } newState := new(disk.State) err = parse(newState, tempFile, entities) if err == nil { newStateSerialized, err = proto.Marshal(newState) } if err == nil { break } fmt.Fprintf(os.Stderr, "Error parsing: %s\n", err) fmt.Fprintf(os.Stderr, "Hit enter to edit again, or Ctrl-C to abort\n") var buf [100]byte os.Stdin.Read(buf[:]) } states := make(chan disk.NewState) done := make(chan struct{}) go stateFile.StartWriter(states, done) states <- disk.NewState{newStateSerialized, false} close(states) <-done return true }
func ReadPassword() (string, error) { fd := os.Stdin.Fd() pass, err := terminal.ReadPassword(int(fd)) return string(pass), err }
func do() bool { if err := system.IsSafe(); err != nil { fmt.Fprintf(os.Stderr, "System checks failed: %s\n", err) return false } editor := os.Getenv("EDITOR") if len(editor) == 0 { fmt.Fprintf(os.Stderr, "$EDITOR is not set\n") return false } stateFile, err := os.Open(*stateFileName) if err != nil { fmt.Fprintf(os.Stderr, "Failed to open state file: %s\n", err) return false } defer stateFile.Close() stateLock, ok := disk.LockStateFile(stateFile) if !ok { fmt.Fprintf(os.Stderr, "Cannot obtain lock on state file\n") return false } defer stateLock.Close() encrypted, err := ioutil.ReadAll(stateFile) if err != nil { fmt.Fprintf(os.Stderr, "Failed to read state file: %s\n", err) return false } salt, ok := disk.GetSCryptSaltFromState(encrypted) if !ok { fmt.Fprintf(os.Stderr, "State file is too short to be valid\n") return false } var state *disk.State var key [32]byte for { state, err = disk.LoadState(encrypted, &key) if err == nil { break } if err != disk.BadPasswordError { fmt.Fprintf(os.Stderr, "Failed to decrypt state file: %s\n", err) return false } fmt.Fprintf(os.Stderr, "Passphrase: ") password, err := terminal.ReadPassword(0) fmt.Fprintf(os.Stderr, "\n") if err != nil { fmt.Fprintf(os.Stderr, "Failed to read password\n") return false } keySlice, err := disk.DeriveKey(string(password), &salt) copy(key[:], keySlice) } tempDir, err := system.SafeTempDir() if err != nil { fmt.Fprintf(os.Stderr, "Failed to get safe temp directory: %s\n", err) return false } tempFile, err := ioutil.TempFile(tempDir, "pond-editstate-") if err != nil { fmt.Fprintf(os.Stderr, "Failed to create temp file: %s\n", err) return false } tempFileName := tempFile.Name() defer func() { os.Remove(tempFileName) }() signals := make(chan os.Signal, 8) signal.Notify(signals, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) go func() { <-signals println("Caught signal: removing", tempFileName) os.Remove(tempFileName) os.Exit(1) }() entities := serialise(tempFile, state) var newStateSerialized []byte for { cmd := exec.Command(editor, tempFileName) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintf(os.Stderr, "Failed to run editor: %s\n", err) return false } tempFile.Close() tempFile, err := os.Open(tempFileName) if err != nil { fmt.Fprintf(os.Stderr, "Failed to open temp file: %s\n", err) return false } newState := new(disk.State) err = parse(newState, tempFile, entities) if err == nil { newStateSerialized, err = proto.Marshal(newState) } if err == nil { break } fmt.Fprintf(os.Stderr, "Error parsing: %s\n", err) fmt.Fprintf(os.Stderr, "Hit enter to edit again, or Ctrl-C to abort\n") var buf [100]byte os.Stdin.Read(buf[:]) } states := make(chan []byte) done := make(chan bool) go disk.StateWriter(*stateFileName, &key, &salt, states, done) states <- newStateSerialized close(states) <-done return true }
func main() { banner := fmt.Sprintf("%s is a tool for managing 1Password vaults.", os.Args[0]) parser := cmdmodes.NewParser(commandModes) agentFlag := flag.Bool("agent", false, "Start 1pass in agent mode") vaultPathFlag := flag.String("vault", "", "Custom vault path") lowSecFlag := flag.Bool("low-security", false, "Use lower security but faster encryption for the master password") flag.Usage = func() { parser.PrintHelp(banner, "") } flag.Parse() if *agentFlag { agent := NewAgent() err := agent.Serve() if err != nil { fatalErr(err, "") } return } config := readConfig() if *vaultPathFlag != "" { config.VaultDir = *vaultPathFlag } if len(flag.Args()) < 1 || flag.Args()[0] == "help" { command := "" if len(flag.Args()) > 1 { command = flag.Args()[1] } parser.PrintHelp(banner, command) os.Exit(1) } mode := flag.Args()[0] cmdArgs := flag.Args()[1:] // handle commands which do not require // an existing vault handled := true switch mode { case "new": var path string if *vaultPathFlag != "" { path = *vaultPathFlag } else { _ = parser.ParseCmdArgs(mode, cmdArgs, &path) if len(path) == 0 { path = os.Getenv("HOME") + "/Dropbox/1Password/1Password.agilekeychain" } } createNewVault(path, *lowSecFlag) case "gen-password": fmt.Printf("%s\n", genDefaultPassword()) case "set-vault": var newPath string _ = parser.ParseCmdArgs(mode, cmdArgs, &newPath) config.VaultDir = newPath writeConfig(&config) default: handled = false } if handled { return } // handle commands which require a connected but not // unlocked vault if config.VaultDir == "" { initVaultConfig(&config) } vault, err := onepass.OpenVault(config.VaultDir) if err != nil { fatalErr(err, "Unable to setup vault") } if mode == "info" { fmt.Printf("Vault path: %s\n", config.VaultDir) return } // remaining commands require an unlocked vault // connect to the 1pass agent daemon. Start it automatically // if not already running or the agent/client version do not // match agentClient, err := DialAgent(config.VaultDir) if err == nil && agentClient.Info.BinaryVersion != appBinaryVersion() { if agentClient.Info.Pid != 0 { fmt.Fprintf(os.Stderr, "Agent/client version mismatch. Restarting agent.\n") // kill the existing agent err = syscall.Kill(agentClient.Info.Pid, syscall.SIGINT) if err != nil { fatalErr(err, "Failed to shut down existing agent") } agentClient = OnePassAgentClient{} } } if agentClient.Info.Pid == 0 { err = startAgent() if err != nil { fatalErr(err, "Unable to start 1pass keychain agent") } maxWait := time.Now().Add(1 * time.Second) for time.Now().Before(maxWait) { agentClient, err = DialAgent(config.VaultDir) if err == nil { break } else { fmt.Errorf("Error starting agent: %v\n", err) } time.Sleep(10 * time.Millisecond) } if err != nil { fatalErr(err, "Unable to connect to 1pass keychain agent") } } if mode == "lock" { err = agentClient.Lock() if err != nil { fatalErr(err, "Failed to lock keychain") } return } if mode == "set-password" { fmt.Printf("Current master password: "******"Failed to check lock status") } if locked { fmt.Printf("Master password: "******"Unable to read password hint: %v\n", err) } fmt.Fprintf(os.Stderr, "Incorrect password (hint: %s)\n", hint) os.Exit(1) } else { fatalErr(err, "Unable to unlock vault") } } } err = agentClient.RefreshAccess() if err != nil { fatalErr(err, "Unable to refresh vault access") } vault.CryptoAgent = &agentClient handleVaultCmd(&vault, mode, cmdArgs) }