File: conn.go

package info (click to toggle)
golang-github-jaksi-sshutils 0.0.15-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 180 kB
  • sloc: makefile: 2
file content (246 lines) | stat: -rw-r--r-- 6,143 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
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
241
242
243
244
245
246
package sshutils

import (
	"encoding/hex"
	"errors"
	"fmt"
	"net"

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

var (
	ErrEstablishSSH = errors.New("failed to establish SSH connection")
	ErrSendRequest  = errors.New("failed to send request")
	ErrChannelOpen  = errors.New("failed to open channel")
)

type Listener struct {
	net.Listener
	config ssh.ServerConfig
}

func (listener *Listener) Accept() (*Conn, error) {
	conn, err := listener.Listener.Accept()
	if err != nil {
		return nil, fmt.Errorf("failed to accept connection: %w", err)
	}
	sshConn, sshNewChannels, sshRequests, err := ssh.NewServerConn(conn, &listener.config)
	if err != nil {
		conn.Close()
		return nil, fmt.Errorf("%w: %v", ErrEstablishSSH, err)
	}
	return handleConn(sshConn, sshNewChannels, sshRequests), nil
}

func Listen(address string, config *ssh.ServerConfig) (*Listener, error) {
	l, err := net.Listen("tcp", address)
	if err != nil {
		return nil, fmt.Errorf("failed to listen: %w", err)
	}
	return &Listener{l, *config}, nil
}

type Conn struct {
	ssh.Conn
	NewChannels   <-chan *NewChannel
	Requests      <-chan *GlobalRequest
	nextChannelID int
}

func (conn *Conn) RawChannel(name string, payload []byte) (*Channel, error) {
	sshChannel, sshRequests, err := conn.Conn.OpenChannel(name, payload)
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrChannelOpen, err)
	}
	return handleChannel(sshChannel, sshRequests, conn, name), nil
}

func (conn *Conn) Channel(name string, payload Payload) (*Channel, error) {
	var data []byte
	if payload != nil {
		data = payload.Marshal()
	}
	return conn.RawChannel(name, data)
}

func (conn *Conn) RawRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) {
	accepted, reply, err := conn.SendRequest(name, wantReply, payload)
	if err != nil {
		return false, nil, fmt.Errorf("%w: %v", ErrSendRequest, err)
	}
	return accepted, reply, nil
}

func (conn *Conn) Request(name string, wantReply bool, payload Payload) (bool, []byte, error) {
	var data []byte
	if payload != nil {
		data = payload.Marshal()
	}
	return conn.RawRequest(name, wantReply, data)
}

func (conn *Conn) String() string {
	return hex.EncodeToString(conn.SessionID())
}

func Dial(address string, config *ssh.ClientConfig) (*Conn, error) {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return nil, fmt.Errorf("failed to dial: %w", err)
	}
	sshConn, sshNewChannels, sshRequests, err := ssh.NewClientConn(conn, address, config)
	if err != nil {
		conn.Close()
		return nil, fmt.Errorf("%w: %v", ErrEstablishSSH, err)
	}
	return handleConn(sshConn, sshNewChannels, sshRequests), nil
}

func handleConn(sshConn ssh.Conn, sshNewChannels <-chan ssh.NewChannel, sshRequests <-chan *ssh.Request) *Conn {
	newChannels := make(chan *NewChannel)
	requests := make(chan *GlobalRequest)
	connection := &Conn{
		Conn:          sshConn,
		NewChannels:   newChannels,
		Requests:      requests,
		nextChannelID: 0,
	}
	go func() {
		for sshNewChannels != nil || sshRequests != nil {
			select {
			case newChannel, ok := <-sshNewChannels:
				if !ok {
					close(newChannels)
					sshNewChannels = nil
					continue
				}
				newChannels <- &NewChannel{newChannel, connection}
			case request, ok := <-sshRequests:
				if !ok {
					close(requests)
					sshRequests = nil
					continue
				}
				requests <- &GlobalRequest{request, connection}
			}
		}
	}()
	return connection
}

type NewChannel struct {
	ssh.NewChannel
	conn *Conn
}

func (newChannel *NewChannel) AcceptChannel() (*Channel, error) {
	sshChannel, sshRequests, err := newChannel.Accept()
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrChannelOpen, err)
	}
	return handleChannel(sshChannel, sshRequests, newChannel.conn, newChannel.ChannelType()), nil
}

func (newChannel *NewChannel) UnmarshalPayload() (Payload, error) {
	return UnmarshalNewChannelPayload(newChannel)
}

func (newChannel *NewChannel) ConnMetadata() ssh.ConnMetadata {
	return newChannel.conn
}

func (newChannel *NewChannel) String() string {
	return newChannel.ChannelType()
}

type Channel struct {
	ssh.Channel
	Requests    <-chan *ChannelRequest
	channelID   string
	channelType string
	conn        *Conn
}

func (channel *Channel) ChannelID() string {
	return channel.channelID
}

func (channel *Channel) ChannelType() string {
	return channel.channelType
}

func (channel *Channel) ConnMetadata() ssh.ConnMetadata {
	return channel.conn
}

func (channel *Channel) RawRequest(name string, wantReply bool, payload []byte) (bool, error) {
	accepted, err := channel.SendRequest(name, wantReply, payload)
	if err != nil {
		return false, fmt.Errorf("%w: %v", ErrSendRequest, err)
	}
	return accepted, nil
}

func (channel *Channel) Request(name string, wantReply bool, payload Payload) (bool, error) {
	var data []byte
	if payload != nil {
		data = payload.Marshal()
	}
	return channel.RawRequest(name, wantReply, data)
}

func (channel *Channel) String() string {
	return channel.channelID
}

func handleChannel(sshChannel ssh.Channel, sshRequests <-chan *ssh.Request, conn *Conn, name string) *Channel {
	requests := make(chan *ChannelRequest)
	channel := &Channel{sshChannel, requests, fmt.Sprint(conn.nextChannelID), name, conn}
	go func() {
		for request := range sshRequests {
			requests <- &ChannelRequest{request, channel}
		}
		close(requests)
	}()
	conn.nextChannelID++
	return channel
}

type GlobalRequest struct {
	*ssh.Request
	conn *Conn
}

func (request *GlobalRequest) UnmarshalPayload() (Payload, error) {
	return UnmarshalGlobalRequestPayload(request.Request)
}

func (request *GlobalRequest) ConnMetadata() ssh.ConnMetadata {
	return request.conn
}

func (request *GlobalRequest) String() string {
	return request.Request.Type
}

type ChannelRequest struct {
	*ssh.Request
	channel *Channel
}

func (request *ChannelRequest) UnmarshalPayload() (Payload, error) {
	return UnmarshalChannelRequestPayload(request.Request)
}

func (request *ChannelRequest) Channel() *Channel {
	return request.channel
}

func (request *ChannelRequest) ConnMetadata() ssh.ConnMetadata {
	return request.channel.conn
}

func (request *ChannelRequest) String() string {
	return request.Request.Type
}