File: session.go

package info (click to toggle)
golang-github-microsoft-dev-tunnels 0.0.25-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,988 kB
  • sloc: cs: 9,969; java: 2,767; javascript: 328; xml: 186; makefile: 5
file content (170 lines) | stat: -rw-r--r-- 4,279 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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

package tunnelssh

import (
	"context"
	"fmt"
	"io"
	"log"
	"net"
	"sync"
	"time"

	"golang.org/x/crypto/ssh"
)

type channelHandlerFunc func(ctx context.Context, channel ssh.NewChannel)
type requestHandlerFunc func(ctx context.Context, req SSHRequest)

// Session is a wrapper around an SSH session designed for communicating
// with a remote tunnels SSH server. It supports the activation of services
// via the activator interface.
type Session struct {
	*ssh.Session

	socket net.Conn
	conn   ssh.Conn

	channelHandlersMu sync.RWMutex
	channelHandlers   map[string]channelHandlerFunc

	requestHandlersMu sync.RWMutex
	requestHandlers   map[string]requestHandlerFunc
}

// NewSession creates a new session.
func NewSession(socket net.Conn) *Session {
	return &Session{socket: socket}
}

// Connect connects to the remote tunnel SSH server.
func (s *Session) Connect(ctx context.Context) (err error) {
	clientConfig := ssh.ClientConfig{
		// For now, the client is allowed to skip SSH authentication;
		// they must have a valid tunnel access token already to get this far.
		User:    "tunnel",
		Timeout: 10 * time.Second,

		// TODO: Validate host public keys match those published to the service?
		// For now, the assumption is only a host with access to the tunnel can get a token
		// that enables listening for tunnel connections.
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	conn, chans, reqs, err := ssh.NewClientConn(s.socket, "", &clientConfig)
	if err != nil {
		return fmt.Errorf("error creating SSH client connection: %w", err)
	}
	s.conn = conn

	go s.handleChannels(ctx, chans)
	go s.handleRequests(ctx, s.convertRequests(reqs))

	sshClient := ssh.NewClient(s.conn, nil, nil)
	s.Session, err = sshClient.NewSession()
	if err != nil {
		return fmt.Errorf("error creating ssh client session: %w", err)
	}

	return nil
}

type activator interface {
	Activate(ctx context.Context, session *Session) error
}

// Active calls the Activate method on the activator interface and passes
// the session to it.
func (s *Session) Activate(ctx context.Context, a activator) error {
	return a.Activate(ctx, s)
}

// AddChannelHandler adds a handler for a channel type.
func (s *Session) AddChannelHandler(channelType string, handler channelHandlerFunc) {
	s.channelHandlersMu.Lock()
	defer s.channelHandlersMu.Unlock()

	if s.channelHandlers == nil {
		s.channelHandlers = make(map[string]channelHandlerFunc)
	}

	s.channelHandlers[channelType] = handler
}

// AddRequestHandler adds a handler for a request type.
func (s *Session) AddRequestHandler(requestType string, handler requestHandlerFunc) {
	s.requestHandlersMu.Lock()
	defer s.requestHandlersMu.Unlock()

	if s.requestHandlers == nil {
		s.requestHandlers = make(map[string]requestHandlerFunc)
	}

	s.requestHandlers[requestType] = handler
}

func (s *Session) handleChannels(ctx context.Context, chans <-chan ssh.NewChannel) {
	for {
		select {
		case <-ctx.Done():
			return
		case newChannel := <-chans:
			s.channelHandlersMu.RLock()
			handler, ok := s.channelHandlers[newChannel.ChannelType()]
			s.channelHandlersMu.RUnlock()

			if !ok {
				newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
				continue
			}

			handler(ctx, newChannel)
		}
	}
}

func (s *Session) handleRequests(ctx context.Context, reqs <-chan SSHRequest) {
	for {
		select {
		case <-ctx.Done():
			return
		case req, ok := <-reqs:
			s.requestHandlersMu.RLock()
			handler, ok := s.requestHandlers[req.Type()]
			s.requestHandlersMu.RUnlock()

			if !ok {
				// Preserve OpenSSH behavior: if the request type is unknown,
				// reject it.
				req.Reply(false, nil)
				continue
			}

			handler(ctx, req)
		}
	}
}

// TODO(josebalius): Deprecate SSHSession struct.
type SSHSession struct {
	*ssh.Session
	socket net.Conn
	conn   ssh.Conn
	reader io.Reader
	writer io.Writer
	logger *log.Logger
}

func (s *SSHSession) Read(p []byte) (n int, err error) {
	return s.reader.Read(p)
}

func (s *SSHSession) Write(p []byte) (n int, err error) {
	return s.writer.Write(p)
}

func (s *SSHSession) SendSessionRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) {
	return s.conn.SendRequest(name, wantReply, payload)
}