aboutsummaryrefslogtreecommitdiff
path: root/cmd/eno/cobra_ssh.go
blob: f684e95c88e0606d7f7697974eb30f5b3f16ae63 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main

import (
	"bufio"
	"crypto"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"gitlab.com/whiteboardguy/eno/internal/crypt"
	"gitlab.com/whiteboardguy/eno/internal/utils"
	"golang.org/x/crypto/ssh"
)

func expandPath(path string) string {
	if strings.HasPrefix(path, "~") {
		home, err := os.UserHomeDir()
		if err == nil {
			rest := strings.TrimPrefix(path[1:], "/")
			path = filepath.Join(home, rest)
		}
	}
	return path
}

var sshCmd = &cobra.Command{
	Use:   "ssh",
	Short: "ssh auth in Eno notes",
	Args:  cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
	},
}

var sshInitCmd = &cobra.Command{
	Use:   "init",
	Short: "setup ssh for Eno notes",
	Args:  cobra.ExactArgs(0),
	Run: func(cmd *cobra.Command, args []string) {
		scanner := bufio.NewScanner(os.Stdin)

		if Conf.SSHInitialized {
			cmd.PrintErrln("SSH is already initialized")
			ok, err := utils.AskUserYesNo("Reinitialize SSH?", false)
			if err != nil {
				cmd.PrintErrln(err)
				os.Exit(1)
			}
			if !ok {
				cmd.PrintErrln("SSH init aborted")
				os.Exit(0)
			}
		}

		privateKeyPath := expandPath("~/.ssh/id_ed25519")
		if _, err := os.Stat(privateKeyPath); err == nil {
			ok, err := utils.AskUserYesNo("Use default SSH key at ~/.ssh/id_ed25519?", true)
			if err != nil {
				cmd.PrintErrln(err)
				os.Exit(1)
			}
			if !ok {
				privateKeyPath = ""
			}
		} else {
			privateKeyPath = ""
		}

		if privateKeyPath == "" {
			fmt.Print("Enter path to SSH private key: ")
			if !scanner.Scan() {
				cmd.PrintErrln("failed to read input")
				os.Exit(1)
			}
			privateKeyPath = expandPath(strings.TrimSpace(scanner.Text()))
		}

		publicKeyPath := privateKeyPath + ".pub"
		if _, err := os.Stat(publicKeyPath); os.IsNotExist(err) {
			cmd.PrintErrln("public key not found at " + publicKeyPath)
			fmt.Print("Enter path to SSH public key: ")
			if !scanner.Scan() {
				cmd.PrintErrln("failed to read input")
				os.Exit(1)
			}
			publicKeyPath = strings.TrimSpace(scanner.Text())
			publicKeyPath = expandPath(publicKeyPath)
		}

		givenPubKeyBytes, err := os.ReadFile(publicKeyPath)
		if err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}

		privKeyBytes, err := os.ReadFile(privateKeyPath)
		if err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}
		crypt.TryMlock(privKeyBytes)
		defer clear(privKeyBytes)

		privKey, err := ssh.ParseRawPrivateKey(privKeyBytes)
		if err != nil {
			if _, ok := errors.AsType[*ssh.PassphraseMissingError](err); ok {
				fmt.Printf("SSH Key Locked!\n")
				fmt.Printf("Enter the ssh key passphrase: ")
				sshPassword, err := utils.TakeSecureUserInput()
				if err != nil {
					cmd.PrintErrln(err)
					os.Exit(1)
				}
				crypt.TryMlock(sshPassword)
				defer clear(sshPassword)

				privKey, err = ssh.ParseRawPrivateKeyWithPassphrase(privKeyBytes, []byte(sshPassword))
			} else {
				cmd.PrintErrln(err)
				os.Exit(1)
			}
		}

		signer, ok := privKey.(crypto.Signer)
		if !ok {
			cmd.PrintErrln("failed to extract public key from private key")
			os.Exit(1)
		}
		extractedPubKeyRaw := signer.Public()

		givenPubKey, _, _, _, err := ssh.ParseAuthorizedKey(givenPubKeyBytes)
		if err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}

		extractedPubKey, err := ssh.NewPublicKey(extractedPubKeyRaw)
		if err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}

		if ssh.FingerprintSHA256(extractedPubKey) != ssh.FingerprintSHA256(givenPubKey) {
			cmd.PrintErrln("public key file does not match private key")
			os.Exit(1)
		}

		if err := updateConfig("DefaultSSHPrivPath", privateKeyPath); err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}
		if err := updateConfig("DefaultSSHPubPath", publicKeyPath); err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}
		if err := updateConfig("SSHInitialized", true); err != nil {
			cmd.PrintErrln(err)
			os.Exit(1)
		}

		cmd.Println("ssh initialized with public key:", publicKeyPath)
	},
}