-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathserver.go
194 lines (171 loc) · 6.88 KB
/
server.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
package ssh3
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"sync"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/rs/zerolog/log"
"github.com/francoismichel/ssh3/util"
)
type ServerConversationHandler func(authenticatedUsername string, conversation *Conversation) error
type Server struct {
maxPacketSize uint64
h3Server *http3.Server
conversations map[http3.StreamCreator]*conversationsManager
conversationHandler ServerConversationHandler
lock sync.Mutex
// conversations map[]
}
// Creates a new server handling http requests for SSH conversations
func NewServer(maxPacketSize uint64, defaultDatagramQueueSize uint64, h3Server *http3.Server, conversationHandler ServerConversationHandler) *Server {
ssh3Server := &Server{
maxPacketSize: maxPacketSize,
h3Server: h3Server,
conversations: make(map[http3.StreamCreator]*conversationsManager),
conversationHandler: conversationHandler,
}
h3Server.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 {
log.Error().Msgf("bad HTTP frame type: %d", frameType)
return false, nil
}
conversationsManager, ok := ssh3Server.getConversationsManager(qconn)
if !ok {
err := fmt.Errorf("could not find SSH3 conversation for new channel %d on conn %+v", stream.StreamID(), qconn)
log.Error().Msgf("%s", err)
return false, err
}
conversationControlStreamID, channelType, maxPacketSize, err := parseHeader(uint64(stream.StreamID()), &StreamByteReader{stream})
if err != nil {
return false, err
}
conversation, ok := conversationsManager.getConversation(conversationControlStreamID)
if !ok {
err := fmt.Errorf("could not find SSH3 conversation with control stream id %d for new channel %d", conversationControlStreamID,
uint64(stream.StreamID()))
log.Error().Msgf("%s", err)
return false, err
}
channelInfo := &ChannelInfo{
ConversationID: conversation.conversationID,
ConversationStreamID: conversationControlStreamID,
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, conversation.channelsManager, false, false, true, defaultDatagramQueueSize, nil)
switch channelInfo.ChannelType {
case "direct-udp":
udpAddr, err := parseUDPForwardingHeader(channelInfo.ChannelID, &StreamByteReader{stream})
if err != nil {
return false, err
}
newChannel.setDatagramSender(conversation.getDatagramSenderForChannel(channelInfo.ChannelID))
newChannel = &UDPForwardingChannelImpl{Channel: newChannel, RemoteAddr: udpAddr}
case "direct-tcp":
tcpAddr, err := parseTCPForwardingHeader(channelInfo.ChannelID, &StreamByteReader{stream})
if err != nil {
return false, err
}
newChannel = &TCPForwardingChannelImpl{Channel: newChannel, RemoteAddr: tcpAddr}
}
conversation.channelsAcceptQueue.Add(newChannel)
return true, nil
}
return ssh3Server
}
func (s *Server) getConversationsManager(streamCreator http3.StreamCreator) (*conversationsManager, bool) {
s.lock.Lock()
defer s.lock.Unlock()
conversations, ok := s.conversations[streamCreator]
return conversations, ok
}
func (s *Server) getOrCreateConversationsManager(streamCreator http3.StreamCreator) *conversationsManager {
s.lock.Lock()
defer s.lock.Unlock()
conversationsManager, ok := s.conversations[streamCreator]
if !ok {
s.conversations[streamCreator] = newConversationManager(streamCreator)
conversationsManager = s.conversations[streamCreator]
}
return conversationsManager
}
func (s *Server) removeConnection(streamCreator http3.StreamCreator) {
s.lock.Lock()
defer s.lock.Unlock()
delete(s.conversations, streamCreator)
}
type AuthenticatedHandlerFunc func(authenticatedUserName string, newConv *Conversation, w http.ResponseWriter, r *http.Request)
type UnauthenticatedBearerFunc func(unauthenticatedBearerString string, base64ConversationID string, w http.ResponseWriter, r *http.Request)
func (s *Server) GetHTTPHandlerFunc(ctx context.Context) AuthenticatedHandlerFunc {
return func(authenticatedUsername string, newConv *Conversation, w http.ResponseWriter, r *http.Request) {
log.Info().Msgf("got request: method: %s, URL: %s", r.Method, r.URL.String())
if r.Method == http.MethodConnect && r.Proto == "ssh3" {
hijacker, ok := w.(http3.Hijacker)
if !ok { // should never happen, unless quic-go change their API
log.Error().Msg("failed to hijack HTTP conversation: is it an HTTP/3 conversation ?")
return
}
streamCreator := hijacker.StreamCreator()
qconn := streamCreator.(quic.Connection)
conversationsManager := s.getOrCreateConversationsManager(streamCreator)
conversationsManager.addConversation(newConv)
w.WriteHeader(200)
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.ReceiveDatagram(ctx)
if err != nil {
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
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", newConv.controlStream.StreamID(), err)
return
}
if convID == uint64(newConv.controlStream.StreamID()) {
err = newConv.AddDatagram(ctx, dgram[buf.Size()-int64(buf.Len()):])
if err != nil {
switch e := err.(type) {
case util.ChannelNotFound:
log.Warn().Msgf("could not find channel %d, queue datagram in the meantime", e.ChannelID)
default:
log.Error().Msgf("could not add datagram to conv id %d: %s", newConv.controlStream.StreamID(), err)
return
}
}
} else {
log.Error().Msgf("discarding datagram with invalid conv id %d", convID)
}
}
}()
go func() {
defer newConv.Close()
defer conversationsManager.removeConversation(newConv)
defer s.removeConnection(streamCreator)
if err := s.conversationHandler(authenticatedUsername, newConv); err != nil {
if errors.Is(err, context.Canceled) {
log.Info().Msgf("conversation canceled for conversation id %s, user %s", newConv.ConversationID(), authenticatedUsername)
} else {
log.Error().Msgf("error while handing new conversation: %s for user %s: %s", newConv.ConversationID(), authenticatedUsername, err)
}
return
}
}()
}
}
}