File: sshkey.go

package info (click to toggle)
golang-github-charmbracelet-x 0.0~git20240809.9ab0ca0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,004 kB
  • sloc: sh: 55; makefile: 5
file content (78 lines) | stat: -rw-r--r-- 2,133 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package sshkey

import (
	"errors"
	"fmt"
	"os"

	"github.com/charmbracelet/huh"
	"golang.org/x/crypto/ssh"
)

// Open reads the path, and parses the key.
func Open(keyPath string) (ssh.Signer, error) {
	pemBytes, err := os.ReadFile(keyPath)
	if err != nil {
		return nil, fmt.Errorf("sshkey: %w", err)
	}
	return Parse(keyPath, pemBytes)
}

// Parse tries to parse the given PEM into a ssh.Signer.
// If the key is encrypted, it will ask for the passphrase.
// The 'identifier' is used to identify the key to the user when asking for the
// passphrase.
func Parse(identifier string, pemBytes []byte) (ssh.Signer, error) {
	return doParse(identifier, pemBytes, ssh.ParsePrivateKey, ssh.ParsePrivateKeyWithPassphrase)
}

// ParseRaw tries to parse the given PEM into a private key.
// If the key is encrypted, it will ask for the passphrase.
// The 'identifier' is used to identify the key to the user when asking for the
// passphrase.
func ParseRaw(identifier string, pemBytes []byte) (interface{}, error) {
	return doParse(identifier, pemBytes, ssh.ParseRawPrivateKey, ssh.ParseRawPrivateKeyWithPassphrase)
}

func doParse[T any](
	identifier string,
	pemBytes []byte,
	parse func(pemBytes []byte) (T, error),
	parseWithPass func(pemBytes, passphrase []byte) (T, error),
) (T, error) {
	result, err := parse(pemBytes)
	if isPassphraseMissing(err) {
		passphrase, err := ask(identifier)
		if err != nil {
			return result, fmt.Errorf("sshkey: %w", err)
		}
		result, err := parseWithPass(pemBytes, passphrase)
		if err != nil {
			return result, fmt.Errorf("sshkey: %w", err)
		}
		return result, nil
	}
	if err != nil {
		return result, fmt.Errorf("sshkey: %w", err)
	}
	return result, nil
}

func isPassphraseMissing(err error) bool {
	var kerr *ssh.PassphraseMissingError
	return errors.As(err, &kerr)
}

func ask(path string) ([]byte, error) {
	var pass string
	if err := huh.Run(
		huh.NewInput().
			Inline(true).
			Value(&pass).
			Title(fmt.Sprintf("Enter the passphrase to unlock %q: ", path)).
			EchoMode(huh.EchoModePassword),
	); err != nil {
		return nil, fmt.Errorf("sshkey: %w", err)
	}
	return []byte(pass), nil
}