Skeleton, mnemonic input, derivation, and the ssh pub and priv commands (closes #1)
All checks were successful
check / check (push) Successful in 5s

The module, the script entrypoints and Makefile, Docker-only linting, the mnemonic sources in the specified order with their refusals, the BIP-85 derivation, and keyfunc ssh pub and priv with the README test vectors as tests. Two review rounds; the second passed with no findings.

Model: opus-5 (implementation and review); fable-5-1 (landing)
This commit was merged in pull request #5.
This commit is contained in:
2026-09-07 17:34:54 +02:00
parent c3fd26a1de
commit 279cba6bcf
34 changed files with 1786 additions and 0 deletions

48
internal/cli/cli.go Normal file
View File

@@ -0,0 +1,48 @@
// Package cli builds the command tree and runs it.
package cli
import (
"fmt"
"os"
"git.eeqj.de/sneak/keyfunc/internal/cli/options"
"git.eeqj.de/sneak/keyfunc/internal/cli/ssh"
"github.com/spf13/cobra"
)
// Version is what --version prints. The build sets it.
//
//nolint:gochecknoglobals // set at build time with -ldflags
var Version = "dev"
// Root returns the whole command tree.
func Root() *cobra.Command {
root := &cobra.Command{
Use: "keyfunc",
Short: "derive key pairs from a BIP-39 mnemonic",
Long: "keyfunc turns a BIP-39 mnemonic into key pairs that can " +
"be recreated from that mnemonic at any time. The same " +
"mnemonic, key type and index always give the same key.",
Version: Version,
SilenceUsage: true,
SilenceErrors: true,
}
options.Add(root)
root.AddCommand(ssh.Command())
return root
}
// Main runs the tool and returns the status the process should exit
// with.
func Main() int {
err := Root().Execute()
if err != nil {
fmt.Fprintln(os.Stderr, "keyfunc: "+err.Error())
return 1
}
return 0
}

110
internal/cli/cli_test.go Normal file
View File

@@ -0,0 +1,110 @@
package cli_test
import (
"bytes"
"strings"
"testing"
"git.eeqj.de/sneak/keyfunc/internal/cli"
"git.eeqj.de/sneak/keyfunc/internal/derive"
"git.eeqj.de/sneak/keyfunc/internal/mnemonic"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)
// The two lines the README says the example mnemonic produces.
const (
vectorZero = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJZOtOczrc/7CQytc" +
"uFwt7s4r8KjkZWkwjLZWBaFKD+7"
vectorOne = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOEWY8+/gmHYVC4u0Y" +
"0I4FKs+eVUulTPHfk9VtXw1tMF"
)
// example returns the mnemonic the README gives its test vectors for:
// eleven abandons and about.
func example() string {
return strings.Repeat("abandon ", 11) + "about"
}
func TestTheReadmeTestVectors(t *testing.T) {
t.Setenv(mnemonic.Variable, example())
require.Equal(t,
vectorZero+" keyfunc/ssh/0",
strings.TrimSpace(run(t, "ssh", "pub", "-n", "0")),
)
require.Equal(t,
vectorOne+" keyfunc/ssh/1",
strings.TrimSpace(run(t, "ssh", "pub", "-n", "1")),
)
}
func TestTheCommentCanBeChosen(t *testing.T) {
t.Setenv(mnemonic.Variable, example())
line := strings.TrimSpace(run(t, "ssh", "pub", "--comment", "mine"))
require.Equal(t, vectorZero+" mine", line)
}
func TestThePrivateKeyMatchesThePublicOne(t *testing.T) {
t.Setenv(mnemonic.Variable, example())
block := run(t, "ssh", "priv", "-n", "1")
require.True(t,
strings.HasPrefix(block, "-----BEGIN OPENSSH PRIVATE KEY-----"),
)
parsed, err := ssh.ParsePrivateKey([]byte(block))
require.NoError(t, err)
back := strings.TrimSpace(
string(ssh.MarshalAuthorizedKey(parsed.PublicKey())),
)
require.Equal(t, vectorOne, back)
}
func TestAnIndexWithNoHardenedChildIsRefused(t *testing.T) {
t.Setenv(mnemonic.Variable, example())
out, err := execute(t, "ssh", "pub", "-n", "2147483648")
require.ErrorIs(t, err, derive.ErrIndexTooLarge)
require.Empty(t, out)
}
func TestTheMnemonicCommandIsUsed(t *testing.T) {
t.Setenv(mnemonic.Variable, "")
line := strings.TrimSpace(run(t,
"ssh", "pub",
"--mnemonic-command", "printf '%s\\n' '"+example()+"'",
))
require.Equal(t, vectorZero+" keyfunc/ssh/0", line)
}
// run executes the tool with the given arguments and returns what it
// wrote to standard output.
func run(t *testing.T, args ...string) string {
t.Helper()
out, err := execute(t, args...)
require.NoError(t, err)
return out
}
// execute runs the tool and returns both what it wrote and how it
// ended.
func execute(t *testing.T, args ...string) (string, error) {
t.Helper()
var out bytes.Buffer
root := cli.Root()
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs(args)
err := root.ExecuteContext(t.Context())
return out.String(), err
}

View File

@@ -0,0 +1,43 @@
// Package options holds the flags that every command has and reads
// them back.
package options
import (
"fmt"
"git.eeqj.de/sneak/keyfunc/internal/mnemonic"
"github.com/spf13/cobra"
)
// Add gives a command the flags that every command has. They are
// persistent, so every command below it has them too.
func Add(cmd *cobra.Command) {
cmd.PersistentFlags().String(
"mnemonic-command", "",
"shell command whose output is the mnemonic",
)
cmd.PersistentFlags().Uint32P(
"index", "n", 0,
"which key to derive",
)
}
// Index returns the key index the user asked for.
func Index(cmd *cobra.Command) (uint32, error) {
index, err := cmd.Flags().GetUint32("index")
if err != nil {
return 0, fmt.Errorf("reading the index: %w", err)
}
return index, nil
}
// Mnemonic returns the mnemonic, from the first source that has one.
func Mnemonic(cmd *cobra.Command) (string, error) {
command, err := cmd.Flags().GetString("mnemonic-command")
if err != nil {
return "", fmt.Errorf("reading the mnemonic command: %w", err)
}
return mnemonic.Read(cmd.Context(), command)
}

127
internal/cli/ssh/ssh.go Normal file
View File

@@ -0,0 +1,127 @@
// Package ssh groups the commands that derive ed25519 SSH keys.
package ssh
import (
"fmt"
"git.eeqj.de/sneak/keyfunc/internal/cli/options"
"git.eeqj.de/sneak/keyfunc/internal/derive"
"git.eeqj.de/sneak/keyfunc/internal/sshkey"
"github.com/spf13/cobra"
)
// Command returns the ssh command and everything under it.
func Command() *cobra.Command {
group := &cobra.Command{
Use: "ssh",
Short: "derive ed25519 SSH keys",
}
group.AddCommand(public(), private())
return group
}
// public returns the command that prints the authorized_keys line.
func public() *cobra.Command {
cmd := &cobra.Command{
Use: "pub",
Short: "print the public key as an authorized_keys line",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
key, comment, err := derived(cmd)
if err != nil {
return err
}
line, err := key.Line(comment)
if err != nil {
return err
}
return write(cmd, line+"\n")
},
}
addComment(cmd)
return cmd
}
// private returns the command that prints the private key.
func private() *cobra.Command {
cmd := &cobra.Command{
Use: "priv",
Short: "print the unencrypted private key in OpenSSH format",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
key, comment, err := derived(cmd)
if err != nil {
return err
}
block, err := key.Block(comment)
if err != nil {
return err
}
return write(cmd, block)
},
}
addComment(cmd)
return cmd
}
// write sends the text to wherever the command's output goes.
func write(cmd *cobra.Command, text string) error {
_, err := fmt.Fprint(cmd.OutOrStdout(), text)
if err != nil {
return fmt.Errorf("writing the key: %w", err)
}
return nil
}
// addComment gives a command its comment flag.
func addComment(cmd *cobra.Command) {
cmd.Flags().String(
"comment", "",
"comment on the key; keyfunc/ssh/<index> when not given",
)
}
// derived returns the key for this run and the comment to put on it.
func derived(cmd *cobra.Command) (*sshkey.Key, string, error) {
index, err := options.Index(cmd)
if err != nil {
return nil, "", err
}
words, err := options.Mnemonic(cmd)
if err != nil {
return nil, "", err
}
material, err := derive.Bytes(words, sshkey.Application, index)
if err != nil {
return nil, "", err
}
key, err := sshkey.New(material)
if err != nil {
return nil, "", err
}
comment, err := cmd.Flags().GetString("comment")
if err != nil {
return nil, "", fmt.Errorf("reading the comment: %w", err)
}
if comment == "" {
comment = fmt.Sprintf("keyfunc/ssh/%d", index)
}
return key, comment, nil
}

71
internal/derive/derive.go Normal file
View File

@@ -0,0 +1,71 @@
// Package derive turns a mnemonic into the bytes a key is made from.
package derive
import (
"errors"
"fmt"
"git.eeqj.de/sneak/secret/pkg/bip85"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg"
bip39 "github.com/tyler-smith/go-bip39"
)
const (
// purpose is the number BIP-85 reserves for itself.
purpose = 83696968
// Size is how many bytes every key type is given.
Size = 32
// MaxIndex is the largest key index there is. Every element of
// the path is hardened, and a hardened BIP-32 child index stops
// here.
MaxIndex = 1<<31 - 1
)
// ErrIndexTooLarge is returned for a key index above MaxIndex. Such an
// index has no hardened child to derive, so there is no key to give
// back rather than a key nobody else would reproduce.
var ErrIndexTooLarge = errors.New("the key index is too large")
// Path returns the derivation path for an application number and a key
// index.
func Path(application, index uint32) string {
return fmt.Sprintf("m/%d'/%d'/%d'", purpose, application, index)
}
// Bytes returns the bytes for an application number and a key index.
// The mnemonic becomes a seed with an empty passphrase, the seed
// becomes a master key, the master key gives BIP-85 entropy at the
// path, and the entropy seeds the generator the bytes are read from.
// An index above MaxIndex is refused before any of that happens.
func Bytes(words string, application, index uint32) ([]byte, error) {
if index > MaxIndex {
return nil, fmt.Errorf(
"%w: %d is above %d",
ErrIndexTooLarge, index, MaxIndex,
)
}
seed := bip39.NewSeed(words, "")
master, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
if err != nil {
return nil, fmt.Errorf("making the master key: %w", err)
}
entropy, err := bip85.DeriveBIP85Entropy(master, Path(application, index))
if err != nil {
return nil, fmt.Errorf("deriving entropy: %w", err)
}
out := make([]byte, Size)
_, err = bip85.NewBIP85DRNG(entropy).Read(out)
if err != nil {
return nil, fmt.Errorf("reading derived bytes: %w", err)
}
return out, nil
}

View File

@@ -0,0 +1,61 @@
package derive_test
import (
"bytes"
"strings"
"testing"
"git.eeqj.de/sneak/keyfunc/internal/derive"
"github.com/stretchr/testify/require"
)
// application is the number the SSH key type uses.
const application = 838372
// example returns the mnemonic every BIP-39 document uses to show its
// test vectors: eleven abandons and about.
func example() string {
return strings.Repeat("abandon ", 11) + "about"
}
func TestPathIsTheOneTheSpecificationGives(t *testing.T) {
t.Parallel()
require.Equal(t, "m/83696968'/838372'/3'", derive.Path(application, 3))
}
func TestEveryIndexGivesItsOwnBytes(t *testing.T) {
t.Parallel()
first, err := derive.Bytes(example(), application, 0)
require.NoError(t, err)
require.Len(t, first, derive.Size)
second, err := derive.Bytes(example(), application, 1)
require.NoError(t, err)
require.Len(t, second, derive.Size)
require.False(t, bytes.Equal(first, second))
}
func TestAnIndexWithNoHardenedChildIsRefused(t *testing.T) {
t.Parallel()
_, err := derive.Bytes(example(), application, derive.MaxIndex+1)
require.ErrorIs(t, err, derive.ErrIndexTooLarge)
_, err = derive.Bytes(example(), application, derive.MaxIndex)
require.NoError(t, err)
}
func TestTheSameInputAlwaysGivesTheSameBytes(t *testing.T) {
t.Parallel()
once, err := derive.Bytes(example(), application, 7)
require.NoError(t, err)
again, err := derive.Bytes(example(), application, 7)
require.NoError(t, err)
require.Equal(t, once, again)
}

View File

@@ -0,0 +1,117 @@
// Package mnemonic finds the mnemonic the keys are derived from.
package mnemonic
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
bip39 "github.com/tyler-smith/go-bip39"
"golang.org/x/term"
)
const (
// CommandVariable holds a shell command whose output is the
// mnemonic.
CommandVariable = "KEYFUNC_MNEMONIC_COMMAND"
// Variable holds the mnemonic itself.
Variable = "KEYFUNC_MNEMONIC"
)
// ErrMissing is returned when there is nowhere left to look and
// standard input is not a terminal, so there is nobody to ask.
var ErrMissing = errors.New(
"no mnemonic given and standard input is not a terminal",
)
// ErrChecksum is returned for a mnemonic that fails the BIP-39
// checksum.
var ErrChecksum = errors.New("the mnemonic fails its BIP-39 checksum")
// Read returns the mnemonic. The command given on the command line is
// used first; then the command in KEYFUNC_MNEMONIC_COMMAND; then the
// mnemonic in KEYFUNC_MNEMONIC; then a prompt on the terminal with
// echo turned off. The first source that has one wins.
func Read(ctx context.Context, command string) (string, error) {
if command == "" {
command = os.Getenv(CommandVariable)
}
if command != "" {
words, err := run(ctx, command)
if err != nil {
return "", err
}
return checked(words)
}
if words := os.Getenv(Variable); words != "" {
return checked(words)
}
return ask()
}
// run executes the command with sh and returns its standard output.
// If the command fails, its standard error becomes part of the error.
func run(ctx context.Context, command string) (string, error) {
//nolint:gosec // running the user's own command is the point
shell := exec.CommandContext(ctx, "sh", "-c", command)
var complaint bytes.Buffer
shell.Stderr = &complaint
out, err := shell.Output()
if err != nil {
said := strings.TrimSpace(complaint.String())
if said == "" {
return "", fmt.Errorf("the mnemonic command failed: %w", err)
}
return "", fmt.Errorf(
"the mnemonic command failed: %w: %s", err, said,
)
}
return string(out), nil
}
// ask prompts on the terminal with echo turned off.
func ask() (string, error) {
fd := int(os.Stdin.Fd())
if !term.IsTerminal(fd) {
return "", ErrMissing
}
fmt.Fprint(os.Stderr, "mnemonic: ")
typed, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
if err != nil {
return "", fmt.Errorf("reading the mnemonic: %w", err)
}
return checked(string(typed))
}
// checked drops the surrounding whitespace and refuses a mnemonic that
// does not pass the BIP-39 checksum.
func checked(words string) (string, error) {
words = strings.TrimSpace(words)
if !bip39.IsMnemonicValid(words) {
return "", ErrChecksum
}
return words, nil
}

View File

@@ -0,0 +1,87 @@
package mnemonic_test
import (
"strings"
"testing"
"git.eeqj.de/sneak/keyfunc/internal/mnemonic"
"github.com/stretchr/testify/require"
)
// Two more mnemonics that pass the checksum, so a test can tell which
// source an answer came from.
const (
fromCommandVariable = "legal winner thank year wave sausage worth " +
"useful legal winner thank yellow"
fromVariable = "letter advice cage absurd amount doctor acoustic " +
"avoid letter advice cage above"
)
// example returns the mnemonic every BIP-39 document uses to show its
// test vectors: eleven abandons and about.
func example() string {
return strings.Repeat("abandon ", 11) + "about"
}
// broken returns a mnemonic whose last word does not match the rest.
func broken() string {
return strings.TrimSpace(strings.Repeat("abandon ", 12))
}
// prints builds a shell command that writes the given words padded
// with spaces, so the test also shows that the padding is dropped.
func prints(words string) string {
return "printf ' %s \\n' '" + words + "'"
}
func TestTheCommandOnTheCommandLineWins(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, prints(fromCommandVariable))
t.Setenv(mnemonic.Variable, fromVariable)
words, err := mnemonic.Read(t.Context(), prints(example()))
require.NoError(t, err)
require.Equal(t, example(), words)
}
func TestTheCommandInTheEnvironmentComesNext(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, prints(fromCommandVariable))
t.Setenv(mnemonic.Variable, fromVariable)
words, err := mnemonic.Read(t.Context(), "")
require.NoError(t, err)
require.Equal(t, fromCommandVariable, words)
}
func TestTheMnemonicInTheEnvironmentComesLast(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, "")
t.Setenv(mnemonic.Variable, " "+fromVariable+" ")
words, err := mnemonic.Read(t.Context(), "")
require.NoError(t, err)
require.Equal(t, fromVariable, words)
}
func TestAFailingCommandSaysWhatWentWrong(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, "")
t.Setenv(mnemonic.Variable, "")
_, err := mnemonic.Read(t.Context(), "echo nothing here >&2; exit 3")
require.Error(t, err)
require.Contains(t, err.Error(), "nothing here")
}
func TestABadChecksumIsRefused(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, "")
t.Setenv(mnemonic.Variable, broken())
_, err := mnemonic.Read(t.Context(), "")
require.ErrorIs(t, err, mnemonic.ErrChecksum)
}
func TestNothingToReadAndNobodyToAsk(t *testing.T) {
t.Setenv(mnemonic.CommandVariable, "")
t.Setenv(mnemonic.Variable, "")
_, err := mnemonic.Read(t.Context(), "")
require.ErrorIs(t, err, mnemonic.ErrMissing)
}

63
internal/sshkey/sshkey.go Normal file
View File

@@ -0,0 +1,63 @@
// Package sshkey turns derived bytes into an ed25519 SSH key.
package sshkey
import (
"crypto/ed25519"
"encoding/pem"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/ssh"
)
// Application is the number this key type occupies in the derivation
// path. It spells SSH the way BIP-85 spells RSA, as the ASCII codes of
// the letters written out.
const Application = 838372
// ErrSize is returned when the derived bytes are not the length an
// ed25519 seed has to be.
var ErrSize = errors.New("an ed25519 key needs 32 derived bytes")
// Key is one ed25519 SSH key.
type Key struct {
private ed25519.PrivateKey
}
// New makes a key whose ed25519 seed is the derived bytes.
func New(derived []byte) (*Key, error) {
if len(derived) != ed25519.SeedSize {
return nil, fmt.Errorf("%w, got %d", ErrSize, len(derived))
}
return &Key{private: ed25519.NewKeyFromSeed(derived)}, nil
}
// Line returns the public key as one authorized_keys line, without a
// trailing newline.
func (k *Key) Line(comment string) (string, error) {
public, err := ssh.NewPublicKey(k.private.Public())
if err != nil {
return "", fmt.Errorf("encoding the public key: %w", err)
}
line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(public)))
if comment != "" {
line += " " + comment
}
return line, nil
}
// Block returns the unencrypted private key in the OpenSSH format that
// ssh reads, ending in a newline.
func (k *Key) Block(comment string) (string, error) {
block, err := ssh.MarshalPrivateKey(k.private, comment)
if err != nil {
return "", fmt.Errorf("encoding the private key: %w", err)
}
return string(pem.EncodeToMemory(block)), nil
}

View File

@@ -0,0 +1,68 @@
package sshkey_test
import (
"strings"
"testing"
"git.eeqj.de/sneak/keyfunc/internal/derive"
"git.eeqj.de/sneak/keyfunc/internal/sshkey"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)
// example returns the mnemonic every BIP-39 document uses to show its
// test vectors: eleven abandons and about.
func example() string {
return strings.Repeat("abandon ", 11) + "about"
}
func TestTooFewBytesAreRefused(t *testing.T) {
t.Parallel()
_, err := sshkey.New([]byte("short"))
require.ErrorIs(t, err, sshkey.ErrSize)
}
func TestTheCommentIsPutAtTheEndOfTheLine(t *testing.T) {
t.Parallel()
key := forIndex(t, 0)
line, err := key.Line("hello")
require.NoError(t, err)
require.True(t, strings.HasPrefix(line, "ssh-ed25519 "))
require.True(t, strings.HasSuffix(line, " hello"))
}
func TestThePrivateKeyCarriesTheSamePublicKey(t *testing.T) {
t.Parallel()
key := forIndex(t, 0)
line, err := key.Line("")
require.NoError(t, err)
block, err := key.Block("a comment")
require.NoError(t, err)
parsed, err := ssh.ParsePrivateKey([]byte(block))
require.NoError(t, err)
back := strings.TrimSpace(
string(ssh.MarshalAuthorizedKey(parsed.PublicKey())),
)
require.Equal(t, line, back)
}
// forIndex derives the key for one index.
func forIndex(t *testing.T, index uint32) *sshkey.Key {
t.Helper()
material, err := derive.Bytes(example(), sshkey.Application, index)
require.NoError(t, err)
key, err := sshkey.New(material)
require.NoError(t, err)
return key
}