/
listener.go
220 lines (191 loc) · 5.23 KB
/
listener.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
package ssh
import (
"context"
"fmt"
"net"
"strconv"
"time"
"github.com/go-gost/core/listener"
"github.com/go-gost/core/logger"
md "github.com/go-gost/core/metadata"
admission "github.com/goxpx/x/admission/wrapper"
xnet "github.com/goxpx/x/internal/net"
"github.com/goxpx/x/internal/net/proxyproto"
ssh_util "github.com/goxpx/x/internal/util/ssh"
sshd_util "github.com/goxpx/x/internal/util/sshd"
climiter "github.com/goxpx/x/limiter/conn/wrapper"
limiter "github.com/goxpx/x/limiter/traffic/wrapper"
metrics "github.com/goxpx/x/metrics/wrapper"
"github.com/goxpx/x/registry"
stats "github.com/goxpx/x/stats/wrapper"
"golang.org/x/crypto/ssh"
)
// Applicable SSH Request types for Port Forwarding - RFC 4254 7.X
const (
DirectForwardRequest = "direct-tcpip" // RFC 4254 7.2
RemoteForwardRequest = "tcpip-forward" // RFC 4254 7.1
)
func init() {
registry.ListenerRegistry().Register("sshd", NewListener)
}
type sshdListener struct {
net.Listener
config *ssh.ServerConfig
cqueue chan net.Conn
errChan chan error
logger logger.Logger
md metadata
options listener.Options
}
func NewListener(opts ...listener.Option) listener.Listener {
options := listener.Options{}
for _, opt := range opts {
opt(&options)
}
return &sshdListener{
logger: options.Logger,
options: options,
}
}
func (l *sshdListener) Init(md md.Metadata) (err error) {
if err = l.parseMetadata(md); err != nil {
return
}
network := "tcp"
if xnet.IsIPv4(l.options.Addr) {
network = "tcp4"
}
lc := net.ListenConfig{}
if l.md.mptcp {
lc.SetMultipathTCP(true)
l.logger.Debugf("mptcp enabled: %v", lc.MultipathTCP())
}
ln, err := lc.Listen(context.Background(), network, l.options.Addr)
if err != nil {
return err
}
ln = proxyproto.WrapListener(l.options.ProxyProtocol, ln, 10*time.Second)
ln = metrics.WrapListener(l.options.Service, ln)
ln = stats.WrapListener(ln, l.options.Stats)
ln = admission.WrapListener(l.options.Admission, ln)
ln = limiter.WrapListener(l.options.TrafficLimiter, ln)
ln = climiter.WrapListener(l.options.ConnLimiter, ln)
l.Listener = ln
config := &ssh.ServerConfig{
PasswordCallback: ssh_util.PasswordCallback(l.options.Auther),
PublicKeyCallback: ssh_util.PublicKeyCallback(l.md.authorizedKeys),
}
config.AddHostKey(l.md.signer)
if l.options.Auther == nil && len(l.md.authorizedKeys) == 0 {
config.NoClientAuth = true
}
l.config = config
l.cqueue = make(chan net.Conn, l.md.backlog)
l.errChan = make(chan error, 1)
go l.listenLoop()
return
}
func (l *sshdListener) Accept() (conn net.Conn, err error) {
var ok bool
select {
case conn = <-l.cqueue:
case err, ok = <-l.errChan:
if !ok {
err = listener.ErrClosed
}
}
return
}
func (l *sshdListener) listenLoop() {
for {
conn, err := l.Listener.Accept()
if err != nil {
l.logger.Error("accept:", err)
l.errChan <- err
close(l.errChan)
return
}
go l.serveConn(conn)
}
}
func (l *sshdListener) serveConn(conn net.Conn) {
start := time.Now()
l.logger.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
defer func() {
l.logger.WithFields(map[string]any{
"duration": time.Since(start),
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
}()
sc, chans, reqs, err := ssh.NewServerConn(conn, l.config)
if err != nil {
l.logger.Error(err)
conn.Close()
return
}
defer sc.Close()
go func() {
for newChannel := range chans {
// Check the type of channel
t := newChannel.ChannelType()
switch t {
case DirectForwardRequest:
channel, requests, err := newChannel.Accept()
if err != nil {
l.logger.Warnf("could not accept channel: %s", err.Error())
continue
}
p := directForward{}
ssh.Unmarshal(newChannel.ExtraData(), &p)
l.logger.Trace(p.String())
if p.Host1 == "<nil>" {
p.Host1 = ""
}
go ssh.DiscardRequests(requests)
cc := sshd_util.NewDirectForwardConn(sc, channel, net.JoinHostPort(p.Host1, strconv.Itoa(int(p.Port1))))
select {
case l.cqueue <- cc:
default:
l.logger.Warnf("connection queue is full, client %s discarded", conn.RemoteAddr())
newChannel.Reject(ssh.ResourceShortage, "connection queue is full")
cc.Close()
}
default:
l.logger.Warnf("unsupported channel type: %s", t)
newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type: %s", t))
}
}
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for req := range reqs {
switch req.Type {
case RemoteForwardRequest:
cc := sshd_util.NewRemoteForwardConn(ctx, sc, req)
select {
case l.cqueue <- cc:
default:
l.logger.Warnf("connection queue is full, client %s discarded", conn.RemoteAddr())
req.Reply(false, []byte("connection queue is full"))
cc.Close()
}
case "ping":
req.Reply(true, []byte("pong"))
default:
l.logger.Warnf("unsupported request type: %s, want reply: %v", req.Type, req.WantReply)
req.Reply(false, nil)
}
}
}()
sc.Wait()
}
// directForward is structure for RFC 4254 7.2 - can be used for "forwarded-tcpip" and "direct-tcpip"
type directForward struct {
Host1 string
Port1 uint32
Host2 string
Port2 uint32
}
func (p directForward) String() string {
return fmt.Sprintf("%s:%d -> %s:%d", p.Host2, p.Port2, p.Host1, p.Port1)
}