Example #1
1
func main() {
	t, err := pam.StartFunc("", "", func(s pam.Style, msg string) (string, error) {
		switch s {
		case pam.PromptEchoOff:
			return gopass.GetPass(msg)
		case pam.PromptEchoOn:
			fmt.Print(msg + " ")
			input, err := bufio.NewReader(os.Stdin).ReadString('\n')
			if err != nil {
				return "", err
			}
			return input[:len(input)-1], nil
		case pam.ErrorMsg:
			log.Print(msg)
			return "", nil
		case pam.TextInfo:
			fmt.Println(msg)
			return "", nil
		}
		return "", errors.New("Unrecognized message style")
	})
	if err != nil {
		log.Fatalf("Start: %s", err.Error())
	}
	err = t.Authenticate(0)
	if err != nil {
		log.Fatalf("Authenticate: %s", err.Error())
	}
	log.Print("Authentication succeeded!")
}
Example #2
0
func (s *PasswordStore) newMasterPass() error {

	pass1, err := gopass.GetPass("New Password for PasswordStore: ")
	if err != nil {
		return fmt.Errorf("Error in GetPass", err)
	}
	pass2, err := gopass.GetPass("Again: ")
	if err != nil {
		return fmt.Errorf("Error in GetPass", err)
	}

	if pass1 == pass2 {
		key, err := PaddingKey(pass1)
		if err != nil {
			return fmt.Errorf("Error in key creation", err)
		}
		cipher, err := encrypt(key, pass1)
		if err != nil {
			return fmt.Errorf("Error in encryption", err)
		}
		record1 := Newrecord("self", "", []byte(cipher))
		if err = s.Set(record1.Name, record1); err != nil {
			return fmt.Errorf("Error for self entry", err)
		}
	} else {
		return fmt.Errorf("Passwords doesn't match")
	}
	return nil
}
Example #3
0
func changePassword(args []string) {
	if passwd == nil {
		pw, err := gopass.GetPass("   Current password: "******"" {
			fmt.Fprintln(os.Stderr, "Invalid password")
			return
		}
	}
	services, err := loadServices(getPasswd())
	gobro.CheckErr(err, "Password invalid")
	pw2, err := gopass.GetPass("   New Password: "******"" {
		fmt.Fprintln(os.Stderr, "Invalid password")
		return
	}
	pw3, err := gopass.GetPass("   Repeat Password: "******"" {
		fmt.Fprintln(os.Stderr, "Invalid password")
		return
	}
	if pw2 != pw3 {
		fmt.Fprintln(os.Stderr, "Passwords don't match")
		return
	}
	saveServices(pw2, services)
	passwd = &pw2
}
Example #4
0
File: scan.go Project: niku4i/mypwd
func (s *Scanner) Input() string {
	passwd, err := gopass.GetPass(s.Ask)
	handleErr(err)
	if s.Validation {
		passwd_c, err := gopass.GetPass("Confirm: ")
		handleErr(err)
		if passwd != passwd_c {
			os.Exit(1)
		}
	}
	return passwd
}
Example #5
0
func getPassword(context *cli.Context) (password string, err error) {
	password = context.String("password")
	if len(password) > 0 {
		return password, nil
	}
	return gopass.GetPass("Plex password: ")
}
Example #6
0
func getUserJwt(userid string, baseUrl string, insecureSkipVerify bool) (*string, error) {

	if cachedToken := getCachedToken(); cachedToken != "" {
		return &cachedToken, nil
	}

	fmt.Fprintf(os.Stderr, "Enter password for "+userid+": ")
	pass, err := gopass.GetPass("")
	if err != nil {
		fmt.Println("*** No password provided ***")
		os.Exit(1)
	}
	url := baseUrl + "/auth/token"
	data := map[string]string{"userid": userid, "passwd": pass}
	body, code, err := DialHttp(url, "POST", data, "", "", insecureSkipVerify)
	if err != nil {
		return nil, err
	}
	if code == http.StatusOK {
		res := JwtResponse{}
		json.Unmarshal(body, &res)
		fmt.Println("Using token: " + res.Token)
		cacheToken(res.Token)
		return &res.Token, nil
	} else {
		err = fmt.Errorf("Invalid credentials")
		return nil, err
	}
}
Example #7
0
// ReadPrivateKey attempts to read your private key and possibly decrypt it if it
// requires a passphrase.
// This function will prompt for a passphrase on STDIN if the environment variable (`IDENTITY_PASSPHRASE`),
// is not set.
func ReadPrivateKey(path string) ([]byte, error) {
	privateKey, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to load identity: %v", err)
	}

	block, rest := pem.Decode(privateKey)
	if len(rest) > 0 {
		return nil, fmt.Errorf("extra data when decoding private key")
	}
	if !x509.IsEncryptedPEMBlock(block) {
		return privateKey, nil
	}

	passphrase := os.Getenv("IDENTITY_PASSPHRASE")
	if passphrase == "" {
		passphrase, err = gopass.GetPass("Enter passphrase: ")
		if err != nil {
			return nil, fmt.Errorf("couldn't read passphrase: %v", err)
		}
	}
	der, err := x509.DecryptPEMBlock(block, []byte(passphrase))
	if err != nil {
		return nil, fmt.Errorf("decrypt failed: %v", err)
	}

	privateKey = pem.EncodeToMemory(&pem.Block{
		Type:  block.Type,
		Bytes: der,
	})

	return privateKey, nil
}
Example #8
0
func decryptPEM(pemblock *pem.Block, filename string) ([]byte, error) {
	var err error
	if _, err = fmt.Fprintf(os.Stderr, "Enter passphrase for %s: ", filename); err != nil {
		return []byte(""), err
	}

	// we already emit the prompt to stderr; GetPass only emits to stdout
	var passwd string
	passwd, err = gopass.GetPass("")
	fmt.Fprintln(os.Stderr, "")
	if err != nil {
		return []byte(""), err
	}

	var decryptedBytes []byte
	if decryptedBytes, err = x509.DecryptPEMBlock(pemblock, []byte(passwd)); err != nil {
		return []byte(""), err
	}

	pemBytes := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: decryptedBytes,
	}
	decryptedPEM := pem.EncodeToMemory(&pemBytes)
	return decryptedPEM, nil
}
Example #9
0
func main() {
	if pw, err := keyring.Get("keyring_example", "jack"); err == nil {
		fmt.Println("current stored password:"******"no password stored yet")
	} else {
		fmt.Println("got unexpected error:", err)
		os.Exit(1)
	}
	pw, err := gopass.GetPass("enter new password: "******"setting keyring_example/jack to..", pw)
	err = keyring.Set("keyring_example", "jack", pw)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("fetching keyring_example/jack..")
	if pw, err := keyring.Get("keyring_example", "jack"); err == nil {
		fmt.Println("got", pw)
	} else {
		fmt.Println("error:", err)
	}
}
Example #10
0
File: setup.go Project: nlf/gh
func Setup(c *cli.Context) {
	client := github.Client{}
	user := Prompt("Username: "******"Password: "******""
	if c.Bool("two-factor") {
		token = Prompt("Token: ")
	}

	client.BaseURL = c.String("url")

	generatedToken, err := client.CreateToken(user, password, token)
	if err != nil {
		log.Fatal(err)
	}

	client.Token = generatedToken.Token
	client.SaveConfig()

	os.Exit(0)
}
Example #11
0
// Hiding user text input requires a linux system using gopass.
func AskForPass() string {
	pass, err := gopass.GetPass("Enter passphrase> ")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	return pass
}
Example #12
0
func init() {
	files := flag.String("f", "", "one or list of files")
	dir := flag.String("d", "", "dir with files")
	text := flag.String("t", "", "text")
	subject := flag.String("s", "", "subject")
	flag.Parse()

	if _, err := os.Stat(config); os.IsNotExist(err) {
		if _, err := os.Stat("~/.mailer.json"); os.IsNotExist(err) {
			config = "~/.mailer.json"
		}
	}
	conf, err := ioutil.ReadFile(config)
	if err != nil {
		fmt.Println("eror read " + config)
		fmt.Println(err.Error())
		usage()
	}
	err = json.Unmarshal(conf, &Conf)
	if err != nil {
		fmt.Println("eror read " + config)
		fmt.Println(err.Error())
		usage()
	}

	if len(flag.Args()) >= 1 {
		args := flag.Args()
		Conf.To = args[0]
	}

	//////

	if len(Conf.To) == 0 {
		usage()
	}

	if len(*files) > 0 {
		Conf.Attach = strings.Split(*files, ",")
	}

	if len(*dir) > 0 {
		Conf.Attach = []string{*dir}
	}

	if len(*text) > 0 {
		Conf.Text = *text
	}

	if len(*subject) > 0 {
		Conf.Subject = *subject
	}

	if len(Conf.Pass) == 0 {
		Conf.Pass, err = gopass.GetPass("pass:")
		checkerr(err)
	}

}
Example #13
0
func UserAdd(args []string) {
	flags := flag.NewFlagSet("useradd", flag.ExitOnError)
	admin := flags.Bool("admin", false, "User should be an administrator")
	rpcSocket := flags.String("sock", rpcSocketDefault, rpcSocketDescription)
	flags.Parse(args)

	if flags.NArg() != 1 {
		fmt.Println("Error: please supply a username (and only one)")
		os.Exit(1)
	}

	passwordOne, err := gopass.GetPass("Enter password for new user: "******"Enter the same password again: ")
	if err != nil {
		panic(err)
	}

	if passwordOne != passwordTwo {
		fmt.Println("Error: Passwords do not match. Please try again.")
		os.Exit(1)
	}

	user := new(User)

	if *admin {
		user.Role = ADMIN
	} else {
		user.Role = NORMAL
	}
	user.Username = flags.Arg(0)
	user.PWHash = HashPassword(passwordOne)

	i := 99
	err = asink.RPCCall(*rpcSocket, "UserModifier.AddUser", user, &i)
	if err != nil {
		if _, ok := err.(rpc.ServerError); ok && err.Error() == DuplicateUsernameErr.Error() {
			fmt.Println("Error: " + err.Error())
			return
		}
		panic(err)
	}
}
Example #14
0
func main() {
	password, err := gopass.GetPass("Enter password to be hashed: ")
	if err != nil {
		error("Could not read password:"******"Repeat password: "******"Could not read password:"******"Passwords do not match.")
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(password), 0)
	if err != nil {
		error("Could not hash password:"******"%s\n", hash)
}
Example #15
0
func (c *SSHConn) Password(user string) (string, error) {
	pass, err := gopass.GetPass("Password for " + user + ": ")

	if err != nil {
		return "", errors.New("Failed to collect password: " + err.Error())
	}

	return pass, err
}
Example #16
0
func push(c *config.Config, q *registry.Queue) error {
	scriptsPath := utils.PackagePath(selfPkg)
	host := c.GetRequired("push")

	// FTP User & password
	user := q.NextTask()
	if user == "" {
		return fmt.Errorf("ftp user required as the first argument")
	}
	q.RemoveNextTask()

	password, err := gopass.GetPass(fmt.Sprintf("Enter \"%s\" password: "******"cannot read password: %s", err)
	}
	if password == "" {
		return fmt.Errorf("ftp password is required")
	}

	// Hash local files
	log.Printf("Hashing local files... ")
	localHashes, err := hashLocalFiles()
	if err != nil {
		return fmt.Errorf("hash local files failed: %s", err)
	}
	log.Printf("Hashing local files... %s[SUCCESS]%s\n", colors.Green, colors.Reset)

	// Hash remote files
	log.Printf("Hashing remote files... ")
	remoteHashes, err := retrieveRemoteHashes(scriptsPath, user, password, host)
	if err != nil {
		return fmt.Errorf("retrieve remote hashes failed: %s", err)
	}
	log.Printf("Hashing remote files... %s[SUCCESS]%s\n", colors.Green, colors.Reset)

	if err := saveLocalHashes(localHashes); err != nil {
		return fmt.Errorf("save local hashes failed: %s", err)
	}

	// Prepare FTP commands
	log.Printf("Preparing FTP commands... ")
	if err := prepareFTPCommands(localHashes, remoteHashes); err != nil {
		return fmt.Errorf("prepare FTP commands failed: %s", err)
	}
	log.Printf("Preparing FTP commands... %s[SUCCESS]%s\n", colors.Green, colors.Reset)

	// Upload files
	log.Printf("Uploading files... ")
	if err := uploadFiles(scriptsPath, user, password, host); err != nil {
		return fmt.Errorf("uploading files failed: %s", err)
	}
	log.Printf("Uploading files... %s[SUCCESS]%s\n", colors.Green, colors.Reset)

	return nil
}
Example #17
0
File: gpws.go Project: devsmt/gpws
func MasterKeys() (masterKey []byte, masterPass string, err error) {
	masterPass, err = gopass.GetPass("Gimme MasterPassword: "******"Error in Password input:", err)
	}
	masterKey, err = PaddingKey(masterPass)
	if err != nil {
		return masterKey, masterPass, fmt.Errorf("Error in Password input:", err)
	}
	return masterKey, masterPass, nil
}
Example #18
0
// getAuthInfo get smtp authentication username and password
// from command line using gopass
func getAuthInfo() (string, string) {
	username := oneLiner("Enter username: "******"Enter password: "******"get password error\n")
		panic(passerr)
	}

	return username, password
}
Example #19
0
func main() {
	usr, _ := user.Current()
	file = filepath.Join(usr.HomeDir, PASSWORD_DB)

	var operation, name, pass_ string
	var length int
	var pass []byte

	flag.StringVar(&operation, "o", "read", "operations: read / add / listkeys")
	flag.StringVar(&name, "n", "name", "key name")
	flag.IntVar(&length, "l", 16, "key length")
	flag.StringVar(&pass_, "p", "", "password to add")
	flag.Parse()

	if pass_ == "" {
		pass = randBytes(length)

	} else {
		pass = []byte(pass_)
	}

	key_, err := gopass.GetPass("Session Key ")
	if err != nil {
		panic(err)
	}
	key = []byte(key_)

	err = readdb()
	if err != nil {
		panic(err)
	}

	if operation == READ {
		err := read(name)
		if err != nil {
			panic(err)
		}
	}
	if operation == ADD {
		err := add(name, pass)
		if err != nil {
			panic(err)
		}

		err = savedb()
		if err != nil {
			panic(err)
		}
	}
	if operation == LISTKEYS {
		listkeys()
	}
}
Example #20
0
func main() {
	if len(os.Args) < 2 {
		printUsage()
		return
	}

	if parseFlags() {
		return
	}

	master_key, err := gopass.GetPass(
		"Enter master key (recommended shorter than 16 bytes): ")
	if err != nil {
		panic(err)
	}

	c := cblib.Init(master_key)
	command := os.Args[1]
	website := []byte(os.Args[2])

	switch command {
	case "get":
		if bytes.Equal(website, []byte("all")) {
			c.PrintPlain()
			return
		}
		if pwd, err := c.Get(website); err == nil {
			fmt.Println(string(pwd))
			cblib.CopyToClipBoard(string(pwd))
		} else {
			panic(err)
		}
	case "new":
		var y_or_n string
		if pwd, err := c.Get(website); err == nil {
			fmt.Println(pwd)
			fmt.Println("Password already exists for", string(website))
		} else {
			new_code := cblib.NewPasscodeHard(15)
			fmt.Println(
				"The password for", string(website),
				"is", string(new_code),
				"\nAccept? (y/N):")
			_, _ = fmt.Scanf("%s", &y_or_n)
			if y_or_n != "N" || y_or_n != "n" {
				// when we add, it's encrypted
				c.Add(website, new_code)
				c.Save()
				cblib.CopyToClipBoard(string(new_code))
			}
		}
	}
}
Example #21
0
func getPasswd() string {
	if passwd == nil {
		pw, err := gopass.GetPass("Password: "******"" {
			fmt.Fprintln(os.Stderr, "Invalid password")
			os.Exit(1)
		}
		passwd = &pw
	}
	return *passwd
}
func promptForEmailAndPassword() {
	reader := bufio.NewReader(os.Stdin)

	// get username and password
	fmt.Print("Enter email: ")
	user, _ := reader.ReadString('\n')

	pass, _ := gopass.GetPass("Enter Password: "******"\n")
	pass = strings.TrimSuffix(pass, "\n")

	lp.Login(user, pass)
}
Example #23
0
func newMasterPw(pwFileName string) (pwList, string, error) {
	f, err := os.Create(pwFileName)
	if err != nil {
		return nil, "", err
	}
	defer f.Close()

	var masterPw string
	for {
		pw0, _ := gopass.GetPass("Enter new master password: "******"Verify new master password: "******"\n")

	return make(map[string]string), masterPw, nil
}
Example #24
0
func (c *LoginCommand) Run(args []string) int {
	if len(args) > 0 {
		c.Ui.Error("Please enter username and password at the prompt.")
		c.Ui.Error("")
		c.Ui.Error(c.Help())
		return 1
	}

	username, err := c.Ui.Ask("Username: "******"Error reading username from prompt: %s", err))
		return 1
	}

	password, err := gopass.GetPass("Password: "******"Error reading password from prompt: %s", err))
		return 1
	}

	client, err := AuthenticatedSparkClient(false)

	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error connecting to spark cloud: %s", err))
		return 1
	}
	// defer client.Close()

	token, _, err := client.Tokens.Login(username, password)

	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error retrieving token: %s", err))
		return 1
	}

	err = ioutil.WriteFile(SettingsFileName, []byte(token.Value), 0755)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error persisting token to file: %s", err))
		return 1
	}

	c.Ui.Info(fmt.Sprintf("Successfully logged in. Access token persisted to: ~/%s", SettingsFileName))
	return 0
}
Example #25
0
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s <site_address>\n", os.Args[0])
		os.Exit(1)
	}
	passwd := ""
	for passwd == "" {
		if passwd, err := gopass.GetPass(os.Args[1] + " password: "******"" {
				clipboard.WriteAll(generate(passwd, os.Args[1]))
				break
			}
		} else {
			panic(err)
		}
	}
}
Example #26
0
File: gpws.go Project: devsmt/gpws
func RecordInput(masterKey []byte, name string) (record record, err error) {
	user, err := UserInput("User: "******"Password: "******"Error in GetPass: %s", err)
	}

	ciphertext, err := encrypt(masterKey, plainpass)
	if err != nil {
		return record, fmt.Errorf("Error in encrypt Password: %s", err)
	}
	record = Newrecord(name, user, []byte(ciphertext))
	return record, nil
}
Example #27
0
func (c *InvalidateCommand) Run(args []string) int {
	if len(args) != 1 {
		c.Ui.Error("An access token must be specified.")
		c.Ui.Error("")
		c.Ui.Error(c.Help())
		return 1
	}

	token := args[0]
	username, err := c.Ui.Ask("Username: "******"Failed reading username from prompt.")
		return 1
	}

	password, err := gopass.GetPass("Password: "******"Error reading password from prompt: %s", err))
		return 1
	}

	client, err := AuthenticatedSparkClient(false)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error connecting to Spark cloud: %s", err))
		return 1
	}

	resp, err := client.Tokens.Delete(token, username, password)

	if err != nil {
		if resp != nil && resp.StatusCode == 401 {
			c.Ui.Error("HTTP 401. Wrong password maybe?")
			return 1
		}

		c.Ui.Error(fmt.Sprintf("Error invalidate token: %s", err))
		return 1
	}

	c.Ui.Info("Access token successfully invalidated.")
	return 0
}
Example #28
0
func add(args []string) {
	if len(args) == 0 {
		fmt.Fprintln(os.Stderr, "Usage: passman add <service> [<options>]\n"+
			"  -g: Generate password\n  "+
			"    Additional options:\n"+
			"      l: include lowercase characters\n"+
			"      u: include uppercase characters\n"+
			"      n: include numbers\n"+
			"      c: include special characters\n"+
			"      w: generate a password using random words from the dictionary\n"+
			"      \\d+$: password must be at least this long."+
			"      example: add -glun24 will produce a password using, lowercase, characters,\n"+
			"      uppercase characters, and numbers, and will be 24 characters long"+
			"  -p: Enter password\n  "+
			"  -m: attach metadata\n")
		return
	}

	name := args[0]
	services, err := loadServices(getPasswd())
	gobro.CheckErr(err, "Password invalid")
	service := services.Get(name)
	service.Name = name

	generateParams, _ := strarr.FindMatchWithRegex(args, "-g.*")
	if generateParams != "" {
		service.Password = NewPasswordGenerator(generateParams).generate()
	}

	if strarr.Contains(args, "-p") {
		prompt := fmt.Sprintf("   Password for %s: ", service.Name)
		password, err := gopass.GetPass(prompt)
		gobro.CheckErr(err)
		service.Password = password
	}

	if strarr.Contains(args, "-m") {
		service.Meta, _ = commander.Prompt(fmt.Sprintf("   Meta for %s: ", service.Name))
	}

	services.Add(service)
	saveServices(getPasswd(), services)
}
Example #29
0
func getPwDb(pwFileName string) (pwList, string, error) {
	if _, err := os.Stat(pwFileName); os.IsNotExist(err) {
		pws, mpw, err := newMasterPw(pwFileName)
		if err != nil {
			return nil, "", err
		}
		return pws, mpw, nil
	}

	pwFile, err := os.Open(pwFileName)
	if err != nil {
		return nil, "", errors.New(fmt.Sprintf("Error opening %s\n", pwFileName))
	}
	defer pwFile.Close()

	pws := make(map[string]string)

	scan := bufio.NewScanner(pwFile)
	scan.Scan()

	masterPwHash := scan.Text()

	var mpw string
	for {
		pw, _ := gopass.GetPass("Enter master password: "******" ")

		pws[line[0]] = line[1]
	}

	return pws, mpw, nil
}
Example #30
0
func (c *Cli) CmdLogin() error {
	uri := fmt.Sprintf("%s/rest/auth/1/session", c.endpoint)
	for true {
		req, _ := http.NewRequest("GET", uri, nil)
		user, _ := c.opts["user"].(string)

		prompt := fmt.Sprintf("Enter Password for %s: ", user)
		passwd, _ := gopass.GetPass(prompt)

		req.SetBasicAuth(user, passwd)
		if resp, err := c.makeRequest(req); err != nil {
			return err
		} else {
			if resp.StatusCode == 403 {
				// probably got this, need to redirect the user to login manually
				// X-Authentication-Denied-Reason: CAPTCHA_CHALLENGE; login-url=https://jira/login.jsp
				if reason := resp.Header.Get("X-Authentication-Denied-Reason"); reason != "" {
					err := fmt.Errorf("Authenticaion Failed: %s", reason)
					log.Error("%s", err)
					return err
				}
				err := fmt.Errorf("Authentication Failed: Unknown Reason")
				log.Error("%s", err)
				return err

			} else if resp.StatusCode == 200 {
				// https://confluence.atlassian.com/display/JIRA043/JIRA+REST+API+%28Alpha%29+Tutorial#JIRARESTAPI%28Alpha%29Tutorial-CAPTCHAs
				// probably bad password, try again
				if reason := resp.Header.Get("X-Seraph-Loginreason"); reason == "AUTHENTICATION_DENIED" {
					log.Warning("Authentication Failed: %s", reason)
					continue
				}
			} else {
				log.Warning("Login failed")
				continue
			}
		}
		return nil
	}
	return nil
}