Debian Codegraph @

sshkey/sshkey.go

raw
1 // Package sshkey provides utilities for parsing SSH private keys with passphrase support.
2 package sshkey
3
4 import (
5 "errors"
6 "fmt"
7 "os"
8
9 "github.com/charmbracelet/huh"
10 "golang.org/x/crypto/ssh"
11 )
12
13 // Open reads the path, and parses the key.
14 func Open(keyPath string) (ssh.Signer, error) {
15 pemBytes, err := os.ReadFile(keyPath)
16 if err != nil {
17 return nil, fmt.Errorf("sshkey: %w", err)
18 }
19 return Parse(keyPath, pemBytes)
20 }
21
22 // Parse tries to parse the given PEM into a ssh.Signer.
23 // If the key is encrypted, it will ask for the passphrase.
24 // The 'identifier' is used to identify the key to the user when asking for the
25 // passphrase.
26 func Parse(identifier string, pemBytes []byte) (ssh.Signer, error) {
27 return doParse(identifier, pemBytes, ssh.ParsePrivateKey, ssh.ParsePrivateKeyWithPassphrase)
28 }
29
30 // ParseRaw tries to parse the given PEM into a private key.
31 // If the key is encrypted, it will ask for the passphrase.
32 // The 'identifier' is used to identify the key to the user when asking for the
33 // passphrase.
34 func ParseRaw(identifier string, pemBytes []byte) (any, error) {
35 return doParse(identifier, pemBytes, ssh.ParseRawPrivateKey, ssh.ParseRawPrivateKeyWithPassphrase)
36 }
37
38 func doParse[T any](
39 identifier string,
40 pemBytes []byte,
41 parse func(pemBytes []byte) (T, error),
42 parseWithPass func(pemBytes, passphrase []byte) (T, error),
43 ) (T, error) {
44 result, err := parse(pemBytes)
45 if isPassphraseMissing(err) {
46 passphrase, err := ask(identifier)
47 if err != nil {
48 return result, fmt.Errorf("sshkey: %w", err)
49 }
50 result, err := parseWithPass(pemBytes, passphrase)
51 if err != nil {
52 return result, fmt.Errorf("sshkey: %w", err)
53 }
54 return result, nil
55 }
56 if err != nil {
57 return result, fmt.Errorf("sshkey: %w", err)
58 }
59 return result, nil
60 }
61
62 func isPassphraseMissing(err error) bool {
63 var kerr *ssh.PassphraseMissingError
64 return errors.As(err, &kerr)
65 }
66
67 func ask(path string) ([]byte, error) {
68 var pass string
69 if err := huh.Run(
70 huh.NewInput().
71 Inline(true).
72 Value(&pass).
73 Title(fmt.Sprintf("Enter the passphrase to unlock %q: ", path)).
74 EchoMode(huh.EchoModePassword),
75 ); err != nil {
76 return nil, fmt.Errorf("sshkey: %w", err)
77 }
78 return []byte(pass), nil
79 }