summaryrefslogtreecommitdiff
path: root/cmd/client/client.go
blob: 1115673c7a297481495321ba30c395bf8d6381f2 (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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package client

import (
	"bytes"
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"

	"code.crute.us/mcrute/ssh-proxy/app"
	"code.crute.us/mcrute/ssh-proxy/proxy"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/agent"

	"code.crute.us/mcrute/golib/cli"
	"github.com/gorilla/websocket"
	"github.com/mdp/qrterminal"
	"github.com/spf13/cobra"
)

// This should be compiled into the binary
var clientId string

func NewClientCommand(appVersion string) *cobra.Command {
	clientCmd := &cobra.Command{
		Use:   "client proxy-host ssh-to-host ssh-port username",
		Short: fmt.Sprintf("Run websocket client (version %s)", appVersion),
		Args:  cobra.ExactArgs(3),
		Run: func(c *cobra.Command, args []string) {
			cfg := app.Config{}
			cli.MustGetConfig(c, &cfg)
			clientMain(cfg, args[0], args[1], args[2])
		},
	}
	cli.AddFlags(clientCmd, &app.Config{}, app.DefaultConfig, "client")
	return clientCmd
}

func Register(root *cobra.Command, appVersion string) {
	root.AddCommand(NewClientCommand(appVersion))
}

func generateCertificateRequest(username, host string) (ed25519.PrivateKey, []byte, error) {
	pub, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	pubKey, err := ssh.NewPublicKey(pub)
	if err != nil {
		return nil, nil, err
	}

	cert := &ssh.Certificate{
		Key:             pubKey,
		CertType:        ssh.UserCert,
		ValidPrincipals: []string{username},
		Permissions: ssh.Permissions{
			Extensions: map[string]string{
				// Used for CA policy checks, removed by the CA server
				// Server supports a comma separated list without spaces
				"allowed-hosts": host,
			},
		},
	}

	signer, err := ssh.NewSignerFromKey(priv)
	if err != nil {
		return nil, nil, err
	}

	// Signatures are required to un/marshal to ASCII. The server will
	// discard this anyhow and replace it with its own signature.
	if err := cert.SignCert(rand.Reader, signer); err != nil {
		return nil, nil, err
	}

	return priv, ssh.MarshalAuthorizedKey(cert), nil
}

func getCertificateFromCA(ctx context.Context, oauthToken string, certRequest []byte, host string) (*ssh.Certificate, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("https://%s/ca/issue", host), bytes.NewReader(certRequest))
	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/x-ssh-certificate")
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", oauthToken))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	res, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("CA returned error: %s", res)
	}

	pubkey, _, _, _, err := ssh.ParseAuthorizedKey(res)
	if err != nil {
		return nil, err
	}

	cert, ok := pubkey.(*ssh.Certificate)
	if !ok {
		return nil, fmt.Errorf("Parsed certificate is of incorrect type")
	}

	return cert, nil
}

func connectToAgent() (agent.ExtendedAgent, error) {
	socket := os.Getenv("SSH_AUTH_SOCK")
	conn, err := net.Dial("unix", socket)
	if err != nil {
		return nil, err
	}

	return agent.NewClient(conn), nil
}

func addCertificateToAgent(conn agent.ExtendedAgent, private any, cert *ssh.Certificate) error {
	return conn.Add(agent.AddedKey{
		PrivateKey:   private,
		Certificate:  cert,
		LifetimeSecs: 10,
	})
}

func dialProxyHost(ctx context.Context, oauthToken, proxyHost, host, port string) (io.ReadWriteCloser, error) {
	addr := fmt.Sprintf("wss://%s/proxy-to/%s/%s", proxyHost, host, port)

	hdr := http.Header{}
	hdr.Add("Authorization", fmt.Sprintf("Bearer %s", oauthToken))

	conn, _, err := websocket.DefaultDialer.DialContext(ctx, addr, hdr)
	if err != nil {
		return nil, err
	}

	return &proxy.WebsocketReadWriter{W: conn}, nil
}

func fetchOauthToken(ctx context.Context, clientId, proxyHost string) (string, error) {
	client := &Oauth2PKCEDeviceClient{
		Host:     proxyHost,
		ClientId: clientId,
		Scope:    "ssh:proxy ca:issue",
	}

	authResponse, err := client.Authorize(ctx)
	if err != nil {
		return "", err
	}

	fmt.Fprintf(os.Stderr,
		"To authenticate, please visit: \n\n\t%s \n\nEnter code: %s\n\n",
		authResponse.VerificationUri, authResponse.UserCode)

	if authResponse.VerificationUriComplete != "" {
		qrterminal.GenerateWithConfig(authResponse.VerificationUriComplete, qrterminal.Config{
			Level:     qrterminal.M,
			Writer:    os.Stderr,
			BlackChar: "\033[7m  \033[0m", // White
			WhiteChar: "\033[0m  \033[0m", // Black
			QuietZone: 1,
		})
		fmt.Fprintf(os.Stderr, "\n")
	}

	tokenResponse, err := client.AwaitToken(ctx, authResponse.DeviceCode)
	if err != nil {
		return "", err
	}

	return tokenResponse.AccessToken, nil
}

func clientMain(cfg app.Config, host, port, username string) {
	log.SetOutput(os.Stderr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	agentConn, err := connectToAgent()
	if err != nil {
		log.Fatalf("Error connecting to agent, is it started?")
	}

	oauthToken, err := fetchOauthToken(ctx, clientId, cfg.ClientHost)
	if err != nil {
		log.Fatalf("Error fetching oauth token: %s", err)
	}

	privateKey, certRequest, err := generateCertificateRequest(username, host)
	if err != nil {
		log.Fatalf("Error generating certificate request: %s", err)
	}

	certificate, err := getCertificateFromCA(ctx, oauthToken, certRequest, cfg.ClientHost)
	if err != nil {
		log.Fatalf("Error fetching certificate: %s", err)
	}

	if err := addCertificateToAgent(agentConn, privateKey, certificate); err != nil {
		log.Fatalf("Error adding certificate to agent: %s", err)
	}

	ws, err := dialProxyHost(ctx, oauthToken, cfg.ClientHost, host, port)
	if err != nil {
		log.Fatalf("Error dialing proxy host: %s", err)
	}
	defer ws.Close()

	// Clear the terminal screen
	fmt.Fprintf(os.Stderr, "\033c")

	errc := make(chan error)

	go proxy.CopyWithErrors(os.Stdout, ws, errc)
	go proxy.CopyWithErrors(ws, os.Stdin, errc)

	err = <-errc
	if err != nil {
		log.Printf("Closing client connection: %s", <-errc)
	} else {
		log.Printf("Closing client connection")
	}
}