forked from francoismichel/ssh3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conversation.go
298 lines (263 loc) · 10.3 KB
/
conversation.go
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package ssh3
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"net"
"net/http"
"ssh3/util"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/rs/zerolog/log"
)
const SSH_FRAME_TYPE = 0xaf3627e6
type ConversationID [32]byte
func (cid ConversationID) String() string {
return base64.StdEncoding.EncodeToString(cid[:])
}
type Conversation struct {
controlStream http3.Stream
maxPacketSize uint64
defaultDatagramsQueueSize uint64
streamCreator http3.StreamCreator
messageSender util.MessageSender
channelsManager *channelsManager
context context.Context
cancelContext context.CancelCauseFunc
conversationID ConversationID // generated using TLS exporters
channelsAcceptQueue *util.AcceptQueue[Channel]
}
func GenerateConversationID(tls *tls.ConnectionState) (convID ConversationID, err error) {
ret, err := tls.ExportKeyingMaterial("EXPORTER-SSH3", nil, 32)
if err != nil {
return convID, err
}
if len(ret) != len(convID) {
return convID, fmt.Errorf("TLS returned a tls-exporter with the wrong length (%d instead of %d)", len(ret), len(convID))
}
copy(convID[:], ret)
return convID, err
}
func NewClientConversation(maxPacketsize uint64, defaultDatagramsQueueSize uint64, tls *tls.ConnectionState) (*Conversation, error) {
convID, err := GenerateConversationID(tls)
if err != nil {
log.Error().Msgf("could not generate conversation ID: %s", err)
return nil, err
}
backgroundCtx, backgroundCancelCauseFunc := context.WithCancelCause(context.Background())
conv := &Conversation{
controlStream: nil,
channelsAcceptQueue: util.NewAcceptQueue[Channel](),
streamCreator: nil,
maxPacketSize: maxPacketsize,
defaultDatagramsQueueSize: defaultDatagramsQueueSize,
channelsManager: newChannelsManager(),
context: backgroundCtx,
cancelContext: backgroundCancelCauseFunc,
conversationID: convID,
}
return conv, nil
}
func (c *Conversation) EstablishClientConversation(req *http.Request, roundTripper *http3.RoundTripper) error {
roundTripper.StreamHijacker = func(frameType http3.FrameType, qconn quic.Connection, stream quic.Stream, err error) (bool, error) {
if err != nil {
return false, err
}
if frameType != SSH_FRAME_TYPE {
return false, nil
}
controlStreamID, channelType, maxPacketSize, err := parseHeader(uint64(stream.StreamID()), &StreamByteReader{stream})
if err != nil {
return false, err
}
// todo: handle several conversations for the same client on the same connection ?
// This can be done by defining the conversation ID as a combination between the control stream ID
// and the tls exporter value, or computing the exporter value depending on the stream ID
if controlStreamID != uint64(c.controlStream.StreamID()) {
err := fmt.Errorf("wrong conversation control stream ID: %d instead of expected %d", controlStreamID, c.controlStream.StreamID())
log.Error().Msgf("%s", err)
return false, err
}
channelInfo := &ChannelInfo{
ConversationID: c.ConversationID(),
ConversationStreamID: controlStreamID,
ChannelID: uint64(stream.StreamID()),
ChannelType: channelType,
MaxPacketSize: maxPacketSize,
}
newChannel := NewChannel(channelInfo.ConversationStreamID, channelInfo.ConversationID, uint64(stream.StreamID()), channelInfo.ChannelType, channelInfo.MaxPacketSize, &StreamByteReader{stream}, stream, nil, c.channelsManager, false, false, true, c.defaultDatagramsQueueSize, nil)
newChannel.setDatagramSender(c.getDatagramSenderForChannel(newChannel.ChannelID()))
c.channelsAcceptQueue.Add(newChannel)
return true, nil
}
rsp, err := roundTripper.RoundTripOpt(req, http3.RoundTripOpt{DontCloseRequestStream: true})
if err != nil {
return err
}
serverVersion := rsp.Header.Get("Server")
major, minor, patch, err := ParseVersion(serverVersion)
if err != nil {
log.Error().Msgf("Could not parse server version: \"%s\"", serverVersion)
if rsp.StatusCode == 200 {
return InvalidSSHVersion{ versionString: serverVersion }
}
} else if major > MAJOR || minor > MINOR {
log.Warn().Msgf("The server runs a higher SSH version (%d.%d.%d), you may want to consider to update the client (currently %d.%d.%d)",
major, minor, patch, MAJOR, MINOR, PATCH)
}
if rsp.StatusCode == 200 {
c.controlStream = rsp.Body.(http3.HTTPStreamer).HTTPStream()
c.streamCreator = rsp.Body.(http3.Hijacker).StreamCreator()
qconn := c.streamCreator.(quic.Connection)
c.messageSender = qconn
c.context, c.cancelContext = context.WithCancelCause(qconn.Context())
go func() {
// TODO: this hijacks the datagrams for the whole quic connection, so the server
// currently does not work for several conversations in the same QUIC connection
for {
dgram, err := qconn.ReceiveMessage(c.Context())
if err != nil {
if err != context.Canceled {
log.Error().Msgf("could not receive message from conn: %s", err)
}
return
}
buf := &util.BytesReadCloser{Reader: bytes.NewReader(dgram)}
convID, err := util.ReadVarInt(buf)
if err != nil {
log.Error().Msgf("could not read conv id from datagram on conv %d: %s", c.controlStream.StreamID(), err)
return
}
if convID == uint64(c.controlStream.StreamID()) {
err = c.AddDatagram(c.Context(), dgram[buf.Size()-int64(buf.Len()):])
if err != nil {
log.Error().Msgf("could not add datagram to conv id %d: %s", c.controlStream.StreamID(), err)
return
}
} else {
log.Error().Msgf("discarding datagram with invalid conv id %d", convID)
}
}
}()
return nil
} else if rsp.StatusCode == http.StatusUnauthorized {
return util.Unauthorized{}
} else {
return fmt.Errorf("returned non-200 and non-401 status code: %d", rsp.StatusCode)
}
}
func NewServerConversation(ctx context.Context, controlStream http3.Stream, qconn quic.Connection, messageSender util.MessageSender, maxPacketsize uint64) (*Conversation, error) {
backgroundContext, backgroundCancelFunc := context.WithCancelCause(ctx)
tls := qconn.ConnectionState().TLS
convID, err := GenerateConversationID(&tls)
if err != nil {
log.Error().Msgf("could not generate conversation ID on server")
return nil, err
}
conv := &Conversation{
controlStream: controlStream,
channelsAcceptQueue: util.NewAcceptQueue[Channel](),
streamCreator: qconn,
maxPacketSize: maxPacketsize,
messageSender: messageSender,
channelsManager: newChannelsManager(),
context: backgroundContext,
cancelContext: backgroundCancelFunc,
conversationID: convID,
}
return conv, nil
}
type StreamByteReader struct {
http3.Stream
}
func (r *StreamByteReader) ReadByte() (byte, error) {
buf := [1]byte{0}
_, err := r.Stream.Read(buf[:])
if err != nil {
return 0, err
}
return buf[0], nil
}
func (c *Conversation) OpenChannel(channelType string, maxPacketSize uint64, datagramsQueueSize uint64) (Channel, error) {
str, err := c.streamCreator.OpenStream()
if err != nil {
return nil, err
}
channel := NewChannel(uint64(c.controlStream.StreamID()), c.conversationID, uint64(str.StreamID()), channelType, maxPacketSize, &StreamByteReader{str}, str, nil, c.channelsManager, true, true, false, datagramsQueueSize, nil)
c.channelsManager.addChannel(channel)
return channel, nil
}
func (c *Conversation) OpenUDPForwardingChannel(maxPacketSize uint64, datagramsQueueSize uint64, localAddr *net.UDPAddr, remoteAddr *net.UDPAddr) (Channel, error) {
str, err := c.streamCreator.OpenStream()
if err != nil {
return nil, err
}
additionalBytes := buildForwardingChannelAdditionalBytes(remoteAddr.IP, uint16(remoteAddr.Port))
channel := NewChannel(uint64(c.controlStream.StreamID()), c.conversationID, uint64(str.StreamID()), "direct-udp", maxPacketSize, &StreamByteReader{str}, str, nil, c.channelsManager, true, true, false, datagramsQueueSize, additionalBytes)
channel.setDatagramSender(c.getDatagramSenderForChannel(channel.ChannelID()))
channel.maybeSendHeader()
c.channelsManager.addChannel(channel)
return &UDPForwardingChannelImpl{Channel: channel, RemoteAddr: remoteAddr}, nil
}
func (c *Conversation) OpenTCPForwardingChannel(maxPacketSize uint64, datagramsQueueSize uint64, localAddr *net.TCPAddr, remoteAddr *net.TCPAddr) (Channel, error) {
str, err := c.streamCreator.OpenStream()
if err != nil {
return nil, err
}
additionalBytes := buildForwardingChannelAdditionalBytes(remoteAddr.IP, uint16(remoteAddr.Port))
channel := NewChannel(uint64(c.controlStream.StreamID()), c.conversationID, uint64(str.StreamID()), "direct-tcp", maxPacketSize, &StreamByteReader{str}, str, nil, c.channelsManager, true, true, false, datagramsQueueSize, additionalBytes)
channel.maybeSendHeader()
c.channelsManager.addChannel(channel)
return &TCPForwardingChannelImpl{Channel: channel, RemoteAddr: remoteAddr}, nil
}
func (c *Conversation) AcceptChannel(ctx context.Context) (Channel, error) {
for {
if channel := c.channelsAcceptQueue.Next(); channel != nil {
channel.confirmChannel(c.maxPacketSize)
c.channelsManager.addChannel(channel)
return channel, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-c.channelsAcceptQueue.Chan():
}
}
}
// blocks until the datagram is added
// the first field must be the channel ID
func (c *Conversation) AddDatagram(ctx context.Context, datagram []byte) error {
buf := &util.BytesReadCloser{Reader: bytes.NewReader(datagram)}
channelID, err := util.ReadVarInt(buf)
if err != nil {
return err
}
channel, ok := c.channelsManager.getChannel(channelID)
if !ok {
dgramQueue := util.NewDatagramsQueue(10)
dgramQueue.Add(datagram[buf.Size()-int64(buf.Len()):])
c.channelsManager.addDanglingDatagramsQueue(channelID, dgramQueue)
return util.ChannelNotFound{ChannelID: channelID}
}
return channel.waitAddDatagram(ctx, datagram[buf.Size()-int64(buf.Len()):])
}
func (c *Conversation) Close() {
c.controlStream.Close()
c.cancelContext(nil)
}
func (c *Conversation) Context() context.Context {
return c.context
}
func (c *Conversation) getDatagramSenderForChannel(channelID util.ChannelID) func(datagram []byte) error {
return func(datagram []byte) error {
buf := util.AppendVarInt(nil, uint64(c.controlStream.StreamID()))
buf = util.AppendVarInt(buf, channelID)
buf = append(buf, datagram...)
return c.messageSender.SendMessage(buf)
}
}
func (c *Conversation) ConversationID() ConversationID {
return c.conversationID
}