Initial independent gopass implementation

This commit is contained in:
waozi committed 2026-08-17 11:17:58 -03:00
commit 609449eba7
17 files changed
+940

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# Changelog
## [0.1.0] - 2026-08-17
- Generate deterministic, LessPass-compatible passwords from site, login, and
master password inputs.
- Configure length, counter, character classes, and excluded characters.
- Read a master password without terminal echo or from an environment variable.
- Copy generated passwords with common desktop clipboard tools.
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2026, Waozi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+66
View File
@@ -0,0 +1,66 @@
# gopass
`gopass` is a stateless password generator: the same site, login, master
password, and settings produce the same result without a password database.
It is a new, independently written implementation of the LessPass generation
algorithm. Compatibility does not imply endorsement by or affiliation with the
LessPass project.
## Install
With Go 1.24 or newer:
```sh
go install github.com/waozixyz/gopass/cmd/gopass@latest
```
Or build the command from a checkout:
```sh
go build ./cmd/gopass
```
## Use
```text
gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
```
The default password has 16 characters and includes lowercase letters,
uppercase letters, digits, and symbols. The default counter is 1.
Passing a master password as an argument can expose it to process inspection
and shell history. Omitting it is safer: `gopass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads from the controlling terminal or console
with echo disabled. Use `--prompt` to bypass the environment and always ask. For
example:
```sh
gopass --prompt example.com alice
gopass --length 24 --counter 2 example.com alice
gopass --no-symbols --exclude '0O1Il' example.com alice
```
`--copy` sends the result through standard input to an available clipboard
program (`wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe`) and does not print
the generated password. The command reports an error if no supported clipboard
tool can be used.
Run `gopass --help` for all flags.
## Library
```go
settings := gopass.DefaultOptions()
result, err := gopass.Generate("example.com", "alice", master, settings)
```
All inputs are interpreted as UTF-8 strings. Excluded characters are removed
from every enabled character class; generation fails if a class becomes empty,
all classes are disabled, or the requested length cannot include one character
from each class.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
[`LICENSE`](LICENSE).
+53
View File
@@ -0,0 +1,53 @@
package main
import (
"errors"
"fmt"
"os/exec"
"runtime"
"strings"
)
type clipboardCommand struct {
program string
args []string
}
func copyToClipboard(value string) error {
commands := clipboardCommands()
var failures []error
for _, candidate := range commands {
path, err := exec.LookPath(candidate.program)
if err != nil {
continue
}
command := exec.Command(path, candidate.args...)
command.Stdin = strings.NewReader(value)
if output, err := command.CombinedOutput(); err == nil {
return nil
} else if len(output) > 0 {
failures = append(failures, fmt.Errorf("%s: %w: %s", candidate.program, err, output))
} else {
failures = append(failures, fmt.Errorf("%s: %w", candidate.program, err))
}
}
if len(failures) > 0 {
return fmt.Errorf("clipboard command failed: %w", errors.Join(failures...))
}
return errors.New("clipboard unavailable: install wl-copy, xclip, xsel, pbcopy, or clip.exe")
}
func clipboardCommands() []clipboardCommand {
switch runtime.GOOS {
case "darwin":
return []clipboardCommand{{program: "pbcopy"}}
case "windows":
return []clipboardCommand{{program: "clip.exe"}}
default:
return []clipboardCommand{
{program: "wl-copy"},
{program: "xclip", args: []string{"-selection", "clipboard", "-in"}},
{program: "xsel", args: []string{"--clipboard", "--input"}},
}
}
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
password "github.com/waozixyz/gopass"
)
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
func main() {
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "gopass: %v\n", err)
os.Exit(1)
}
}
func run(arguments []string, stdout, stderr io.Writer) error {
options := password.DefaultOptions()
flags := flag.NewFlagSet("gopass", flag.ContinueOnError)
flags.SetOutput(stderr)
flags.Usage = func() { printHelp(stderr) }
flags.IntVar(&options.Length, "L", options.Length, "password length")
flags.IntVar(&options.Length, "length", options.Length, "password length")
flags.Uint64Var(&options.Counter, "C", options.Counter, "generation counter")
flags.Uint64Var(&options.Counter, "counter", options.Counter, "generation counter")
flags.BoolVar(&options.Lowercase, "l", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Lowercase, "lowercase", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Uppercase, "u", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Uppercase, "uppercase", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Digits, "d", options.Digits, "include digits")
flags.BoolVar(&options.Digits, "digits", options.Digits, "include digits")
flags.BoolVar(&options.Symbols, "s", options.Symbols, "include symbols")
flags.BoolVar(&options.Symbols, "symbols", options.Symbols, "include symbols")
var noLowercase, noUppercase, noDigits, noSymbols bool
flags.BoolVar(&noLowercase, "no-lowercase", false, "exclude lowercase letters")
flags.BoolVar(&noUppercase, "no-uppercase", false, "exclude uppercase letters")
flags.BoolVar(&noDigits, "no-digits", false, "exclude digits")
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
var forcePrompt, copyPassword, showVersion bool
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
flags.BoolVar(&copyPassword, "c", false, "copy the password to the clipboard")
flags.BoolVar(&copyPassword, "copy", false, "copy the password to the clipboard")
flags.BoolVar(&showVersion, "v", false, "show version")
flags.BoolVar(&showVersion, "version", false, "show version")
if err := flags.Parse(arguments); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
if noLowercase {
options.Lowercase = false
}
if noUppercase {
options.Uppercase = false
}
if noDigits {
options.Digits = false
}
if noSymbols {
options.Symbols = false
}
if showVersion {
fmt.Fprintf(stdout, "gopass %s\n", password.Version)
return nil
}
positional := flags.Args()
if len(positional) < 2 || len(positional) > 3 {
printHelp(stderr)
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
}
if forcePrompt && len(positional) == 3 {
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
}
master, err := masterPassword(positional, forcePrompt)
if err != nil {
return err
}
generated, err := password.Generate(positional[0], positional[1], master, options)
if err != nil {
return err
}
if copyPassword {
if err := copyToClipboard(generated); err != nil {
return err
}
fmt.Fprintln(stderr, "Password copied to the clipboard.")
return nil
}
fmt.Fprintln(stdout, generated)
return nil
}
func masterPassword(positional []string, forcePrompt bool) (string, error) {
if !forcePrompt && len(positional) == 3 {
return positional[2], nil
}
if !forcePrompt {
if value, exists := os.LookupEnv(environmentVariable); exists {
return value, nil
}
}
return readPassword("Master password: ")
}
func printHelp(output io.Writer) {
fmt.Fprintln(output, `Usage: gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
Derive a site-specific password. If MASTER_PASSWORD is omitted, gopass reads
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal.
Options:
-L, --length N password length (default 16)
-C, --counter N generation counter (default 1)
-l, --lowercase include lowercase letters
-u, --uppercase include uppercase letters
-d, --digits include digits
-s, --symbols include symbols
--no-lowercase exclude lowercase letters
--no-uppercase exclude uppercase letters
--no-digits exclude digits
--no-symbols exclude symbols
--exclude CHARS remove characters from all enabled classes
-p, --prompt always ask for the master password
-c, --copy copy result without printing it
-v, --version show version
-h, --help show this help`)
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"bytes"
"strings"
"testing"
)
func TestRunWithArgument(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "correct horse battery staple"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got, want := output.String(), "&vLf44D'/cSkP-_8\n"; got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestRunUsesEnvironmentAndFlags(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"--length", "10", "--no-symbols", "--exclude", "aA0", "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(output.String())
if len(got) != 10 {
t.Fatalf("output length = %d, want 10", len(got))
}
if strings.ContainsAny(got, "aA0"+"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
t.Fatalf("output %q contains a disabled character", got)
}
}
func TestRunInformationOptions(t *testing.T) {
for _, test := range []struct {
argument string
want string
}{
{"--version", "gopass 0.1.0"},
{"--help", "Usage: gopass"},
} {
var output, diagnostics bytes.Buffer
if err := run([]string{test.argument}, &output, &diagnostics); err != nil {
t.Errorf("run(%s): %v", test.argument, err)
}
combined := output.String() + diagnostics.String()
if !strings.Contains(combined, test.want) {
t.Errorf("run(%s) output %q does not contain %q", test.argument, combined, test.want)
}
}
}
func TestRunRejectsConflictingPasswordSources(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"--prompt", "example.com", "alice", "master"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "cannot be supplied") {
t.Fatalf("error = %v, want source conflict", err)
}
}
func TestClipboardCommandsDoNotCarryPasswordData(t *testing.T) {
secret := "this must travel only over standard input"
for _, command := range clipboardCommands() {
if command.program == secret {
t.Fatal("secret appeared as clipboard executable")
}
for _, argument := range command.args {
if strings.Contains(argument, secret) {
t.Fatal("secret appeared in clipboard command arguments")
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
//go:build linux
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
state, err := terminalState(terminal.Fd(), syscall.TCGETS, nil)
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
noEcho := *state
noEcho.Lflag &^= syscall.ECHO
if _, err := terminalState(terminal.Fd(), syscall.TCSETS, &noEcho); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = terminalState(terminal.Fd(), syscall.TCSETS, state) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func terminalState(fd uintptr, request uintptr, replacement *syscall.Termios) (*syscall.Termios, error) {
state := replacement
if state == nil {
state = new(syscall.Termios)
}
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, uintptr(unsafe.Pointer(state)))
if errno != 0 {
return nil, errno
}
return state, nil
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !windows
package main
import "errors"
func readPassword(_ string) (string, error) {
return "", errors.New("secure terminal prompting is not supported on this operating system; use LESSPASS_MASTER_PASSWORD")
}
+50
View File
@@ -0,0 +1,50 @@
//go:build darwin || dragonfly || freebsd || netbsd || openbsd || solaris
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
stty, err := exec.LookPath("stty")
if err != nil {
return "", fmt.Errorf("cannot securely prompt because stty is unavailable: %w", err)
}
original, err := runStty(stty, terminal, "-g")
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
if _, err := runStty(stty, terminal, "-echo"); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = runStty(stty, terminal, strings.TrimSpace(original)) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func runStty(path string, terminal *os.File, argument string) (string, error) {
command := exec.Command(path, argument)
command.Stdin = terminal
command.Stderr = terminal
output, err := command.Output()
return string(output), err
}
+63
View File
@@ -0,0 +1,63 @@
//go:build windows
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
const enableEchoInput = 0x0004
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getConsoleMode = kernel32.NewProc("GetConsoleMode")
setConsoleMode = kernel32.NewProc("SetConsoleMode")
)
func readPassword(label string) (string, error) {
input, err := os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a console: %w", err)
}
defer input.Close()
output, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0)
if err != nil {
return "", fmt.Errorf("cannot open the console for prompting: %w", err)
}
defer output.Close()
var original uint32
if err := windowsCall(getConsoleMode, input.Fd(), uintptr(unsafe.Pointer(&original))); err != nil {
return "", fmt.Errorf("cannot read console settings: %w", err)
}
if err := windowsCall(setConsoleMode, input.Fd(), uintptr(original&^enableEchoInput)); err != nil {
return "", fmt.Errorf("cannot disable console echo: %w", err)
}
defer func() { _ = windowsCall(setConsoleMode, input.Fd(), uintptr(original)) }()
if _, err := fmt.Fprint(output, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(input).ReadString('\n')
fmt.Fprintln(output)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func windowsCall(procedure *syscall.LazyProc, arguments ...uintptr) error {
result, _, callErr := procedure.Call(arguments...)
if result != 0 {
return nil
}
if callErr != nil && callErr != syscall.Errno(0) {
return callErr
}
return syscall.EINVAL
}
+3
View File
@@ -0,0 +1,3 @@
module github.com/waozixyz/gopass
go 1.24
+125
View File
@@ -0,0 +1,125 @@
// Package gopass derives site-specific passwords without storing them.
package gopass
import (
"errors"
"fmt"
"math/big"
"strconv"
)
const (
LowercaseCharacters = "abcdefghijklmnopqrstuvwxyz"
UppercaseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DigitCharacters = "0123456789"
SymbolCharacters = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
)
// Options controls the shape of a generated password.
type Options struct {
Length int
Counter uint64
Lowercase bool
Uppercase bool
Digits bool
Symbols bool
Exclude string
}
// DefaultOptions returns the standard generator settings.
func DefaultOptions() Options {
return Options{
Length: 16,
Counter: 1,
Lowercase: true,
Uppercase: true,
Digits: true,
Symbols: true,
}
}
// Generate derives a password from site, login, master password, and options.
func Generate(site, login, master string, options Options) (string, error) {
classes, alphabet, err := availableCharacters(options)
if err != nil {
return "", err
}
if options.Length < len(classes) {
return "", fmt.Errorf("password length %d is smaller than the %d enabled character classes", options.Length, len(classes))
}
salt := []byte(site + login + strconv.FormatUint(options.Counter, 10))
entropy := new(big.Int).SetBytes(deriveKey([]byte(master), salt))
password := make([]byte, 0, options.Length)
for range options.Length - len(classes) {
password = append(password, alphabet[takeRemainder(entropy, len(alphabet))])
}
required := make([]byte, len(classes))
for i, class := range classes {
required[i] = class[takeRemainder(entropy, len(class))]
}
for _, character := range required {
position := takeRemainder(entropy, len(password)+1)
password = append(password, 0)
copy(password[position+1:], password[position:])
password[position] = character
}
return string(password), nil
}
func availableCharacters(options Options) ([][]byte, []byte, error) {
if options.Length < 1 {
return nil, nil, errors.New("password length must be positive")
}
excluded := make(map[byte]bool, len(options.Exclude))
for _, character := range []byte(options.Exclude) {
excluded[character] = true
}
configured := []struct {
enabled bool
name string
value string
}{
{options.Lowercase, "lowercase", LowercaseCharacters},
{options.Uppercase, "uppercase", UppercaseCharacters},
{options.Digits, "digits", DigitCharacters},
{options.Symbols, "symbols", SymbolCharacters},
}
var classes [][]byte
var alphabet []byte
for _, candidate := range configured {
if !candidate.enabled {
continue
}
filtered := make([]byte, 0, len(candidate.value))
for i := range len(candidate.value) {
if !excluded[candidate.value[i]] {
filtered = append(filtered, candidate.value[i])
}
}
if len(filtered) == 0 {
return nil, nil, fmt.Errorf("enabled %s character class is empty after exclusions", candidate.name)
}
classes = append(classes, filtered)
alphabet = append(alphabet, filtered...)
}
if len(classes) == 0 {
return nil, nil, errors.New("at least one character class must be enabled")
}
return classes, alphabet, nil
}
func takeRemainder(entropy *big.Int, divisor int) int {
quotient := new(big.Int)
remainder := new(big.Int)
quotient.QuoRem(entropy, big.NewInt(int64(divisor)), remainder)
entropy.Set(quotient)
return int(remainder.Int64())
}
+141
View File
@@ -0,0 +1,141 @@
package gopass
import (
"encoding/hex"
"strings"
"testing"
)
func TestDeriveKeyKnownResults(t *testing.T) {
tests := []struct {
password string
salt string
want string
}{
{"password", "salt", "0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5"},
{"", "examplealice1", "caa46554f5a676b76c15b368c655b0b24eaaad8595ef919999785c68e60fd5f5"},
}
for _, test := range tests {
got := hex.EncodeToString(deriveKey([]byte(test.password), []byte(test.salt)))
if got != test.want {
t.Errorf("deriveKey(%q, %q) = %s, want %s", test.password, test.salt, got, test.want)
}
}
}
func TestGenerateKnownResults(t *testing.T) {
tests := []struct {
name string
site, login, key string
options Options
want string
}{
{
name: "defaults",
site: "example.com", login: "alice", key: "correct horse battery staple",
options: DefaultOptions(), want: "&vLf44D'/cSkP-_8",
},
{
name: "counter and length",
site: "service.test", login: "[email protected]", key: "master",
options: Options{Length: 20, Counter: 2, Lowercase: true, Uppercase: true, Digits: true, Symbols: true},
want: "j:x_Lo5X_jL0w%ez`1be",
},
{
name: "utf8 inputs and two classes",
site: "δοκιμή.example", login: "ユーザー", key: "pässword",
options: Options{Length: 12, Counter: 7, Lowercase: true, Digits: true},
want: "ioh5o2mhyghv",
},
{
name: "excluded characters",
site: "example.com", login: "alice", key: "correct horse battery staple",
options: Options{Length: 24, Counter: 1, Lowercase: true, Uppercase: true, Digits: true, Symbols: true, Exclude: "0Ool1I!|"},
want: "7,a.Cp}YnF'ee7HqbX#PQhgH",
},
{
name: "empty master and zero counter",
site: "x", login: "y", key: "",
options: Options{Length: 4, Counter: 0, Uppercase: true, Digits: true},
want: "9O7C",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := Generate(test.site, test.login, test.key, test.options)
if err != nil {
t.Fatal(err)
}
if got != test.want {
t.Fatalf("Generate() = %q, want %q", got, test.want)
}
independent := referenceGenerate(test.site, test.login, test.key, test.options)
if got != independent {
t.Fatalf("Generate() = %q, separate reference = %q", got, independent)
}
})
}
}
func TestGeneratedPasswordMeetsRequestedShape(t *testing.T) {
options := Options{
Length: 40,
Counter: 3,
Lowercase: true,
Uppercase: true,
Digits: true,
Symbols: true,
Exclude: "abcXYZ019!@",
}
got, err := Generate("host", "account", "secret", options)
if err != nil {
t.Fatal(err)
}
if len(got) != options.Length {
t.Fatalf("length = %d, want %d", len(got), options.Length)
}
for _, excluded := range options.Exclude {
if strings.ContainsRune(got, excluded) {
t.Errorf("result contains excluded character %q", excluded)
}
}
for name, set := range map[string]string{
"lowercase": removeCharacters(LowercaseCharacters, options.Exclude),
"uppercase": removeCharacters(UppercaseCharacters, options.Exclude),
"digits": removeCharacters(DigitCharacters, options.Exclude),
"symbols": removeCharacters(SymbolCharacters, options.Exclude),
} {
if !strings.ContainsAny(got, set) {
t.Errorf("result has no %s character", name)
}
}
}
func removeCharacters(value, excluded string) string {
return strings.Map(func(character rune) rune {
if strings.ContainsRune(excluded, character) {
return -1
}
return character
}, value)
}
func TestRejectsInvalidOptions(t *testing.T) {
tests := []struct {
name string
options Options
}{
{"nonpositive length", Options{Length: 0, Lowercase: true}},
{"no class", Options{Length: 8}},
{"too few positions", Options{Length: 2, Lowercase: true, Uppercase: true, Digits: true}},
{"emptied class", Options{Length: 8, Digits: true, Exclude: DigitCharacters}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := Generate("site", "login", "master", test.options); err == nil {
t.Fatal("Generate() succeeded for invalid options")
}
})
}
}
+30
View File
@@ -0,0 +1,30 @@
package gopass
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
)
const derivationRounds = 100_000
func deriveKey(password, salt []byte) []byte {
blockInput := make([]byte, len(salt)+4)
copy(blockInput, salt)
binary.BigEndian.PutUint32(blockInput[len(salt):], 1)
mac := hmac.New(sha256.New, password)
_, _ = mac.Write(blockInput)
previous := mac.Sum(nil)
key := append([]byte(nil), previous...)
for round := 1; round < derivationRounds; round++ {
mac.Reset()
_, _ = mac.Write(previous)
previous = mac.Sum(previous[:0])
for i := range key {
key[i] ^= previous[i]
}
}
return key
}
+79
View File
@@ -0,0 +1,79 @@
package gopass
import (
"crypto/hmac"
"crypto/sha256"
"math/big"
"strconv"
"strings"
)
// referenceGenerate is intentionally self-contained so the examples exercise
// the public generator against a second implementation of the specification.
func referenceGenerate(site, login, master string, options Options) string {
definitions := []struct {
on bool
set string
}{
{options.Lowercase, "abcdefghijklmnopqrstuvwxyz"},
{options.Uppercase, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{options.Digits, "0123456789"},
{options.Symbols, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"},
}
classes := make([]string, 0, 4)
pool := ""
for _, definition := range definitions {
if !definition.on {
continue
}
filtered := ""
for _, character := range definition.set {
if !strings.ContainsRune(options.Exclude, character) {
filtered += string(character)
}
}
classes = append(classes, filtered)
pool += filtered
}
salt := []byte(site + login + strconv.FormatUint(options.Counter, 10))
message := append(append([]byte(nil), salt...), 0, 0, 0, 1)
mac := hmac.New(sha256.New, []byte(master))
_, _ = mac.Write(message)
last := mac.Sum(nil)
derived := append([]byte(nil), last...)
for iteration := 2; iteration <= 100_000; iteration++ {
mac.Reset()
_, _ = mac.Write(last)
last = mac.Sum(nil)
for i, value := range last {
derived[i] ^= value
}
}
value := new(big.Int).SetBytes(derived)
draw := func(size int) int {
base := big.NewInt(int64(size))
remainder := new(big.Int)
value.DivMod(value, base, remainder)
return int(remainder.Int64())
}
result := make([]byte, options.Length-len(classes))
for i := range result {
result[i] = pool[draw(len(pool))]
}
required := make([]byte, len(classes))
for i, class := range classes {
required[i] = class[draw(len(class))]
}
for _, character := range required {
at := draw(len(result) + 1)
next := make([]byte, 0, len(result)+1)
next = append(next, result[:at]...)
next = append(next, character)
next = append(next, result[at:]...)
result = next
}
return string(result)
}
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
release_version=$(sed -n 's/^## \[\([0-9][0-9.]*\)\].*/\1/p' CHANGELOG.md | head -n 1)
if [ -z "$release_version" ]; then
echo "No numeric release entry found in CHANGELOG.md" >&2
exit 1
fi
sed -E -i "s/^const Version = \"[^\"]+\"$/const Version = \"$release_version\"/" version.go
grep -F "const Version = \"$release_version\"" version.go >/dev/null
+4
View File
@@ -0,0 +1,4 @@
package gopass
// Version is the current application version.
const Version = "0.1.0"