-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
301 lines (260 loc) · 7.14 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
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
299
300
301
/*
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sshutils
import (
"crypto/subtle"
"net"
"sync"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/utils"
log "github.com/Sirupsen/logrus"
"github.com/gravitational/trace"
"golang.org/x/crypto/ssh"
)
// Server is a generic implementation of a frame for SSH server
type Server struct {
addr utils.NetAddr
listener net.Listener
closeC chan struct{}
newChanHandler NewChanHandler
reqHandler RequestHandler
cfg ssh.ServerConfig
limiter *limiter.Limiter
}
// ServerOption is a functional argument for server
type ServerOption func(cfg *Server) error
func SetLimiter(limiter *limiter.Limiter) ServerOption {
return func(s *Server) error {
s.limiter = limiter
return nil
}
}
func NewServer(a utils.NetAddr,
h NewChanHandler,
hostSigners []ssh.Signer,
ah AuthMethods,
opts ...ServerOption) (*Server, error) {
err := checkArguments(a, h, hostSigners, ah)
if err != nil {
return nil, err
}
s := &Server{
addr: a,
newChanHandler: h,
closeC: make(chan struct{}),
}
s.limiter, err = limiter.NewLimiter(limiter.LimiterConfig{})
if err != nil {
return nil, trace.Wrap(err)
}
for _, o := range opts {
if err := o(s); err != nil {
return nil, err
}
}
for _, signer := range hostSigners {
(&s.cfg).AddHostKey(signer)
}
s.cfg.PublicKeyCallback = ah.PublicKey
s.cfg.PasswordCallback = ah.Password
s.cfg.NoClientAuth = ah.NoClient
return s, nil
}
func SetSSHConfig(cfg ssh.ServerConfig) ServerOption {
return func(s *Server) error {
s.cfg = cfg
return nil
}
}
func SetRequestHandler(req RequestHandler) ServerOption {
return func(s *Server) error {
s.reqHandler = req
return nil
}
}
func (s *Server) Addr() string {
return s.listener.Addr().String()
}
func (s *Server) Start() error {
socket, err := net.Listen(s.addr.AddrNetwork, s.addr.Addr)
if err != nil {
return err
}
s.listener = socket
log.Infof("created listening socket: %v", socket.Addr())
go s.acceptConnections()
return nil
}
func (s *Server) notifyClosed() {
close(s.closeC)
}
func (s *Server) Wait() {
<-s.closeC
}
// Close closes listening socket and stops accepting connections
func (s *Server) Close() error {
return s.listener.Close()
}
func (s *Server) acceptConnections() {
defer s.notifyClosed()
log.Infof("%v ready to accept connections", s.Addr())
for {
conn, err := s.listener.Accept()
if err != nil {
// our best shot to avoid excessive logging
if op, ok := err.(*net.OpError); ok && !op.Timeout() {
log.Infof("socket closed: %v", op)
return
}
log.Infof("accept error: %T %v", err, err)
return
}
log.Infof("%v accepted connection from %v", s.Addr(), conn.RemoteAddr())
go s.handleConnection(conn)
}
}
func (s *Server) handleConnection(conn net.Conn) {
// initiate an SSH connection, note that we don't need to close the conn here
// in case of error as ssh server takes care of this
remoteAddr, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
log.Errorf(err.Error())
}
if err := s.limiter.AcquireConnection(remoteAddr); err != nil {
log.Errorf(err.Error())
conn.Close()
return
}
defer s.limiter.ReleaseConnection(remoteAddr)
// setting waiting deadline in case of connection freezing
err = conn.SetDeadline(time.Now().Add(5 * time.Minute))
if err != nil {
log.Errorf(err.Error())
return
}
sconn, chans, reqs, err := ssh.NewServerConn(conn, &s.cfg)
if err != nil {
log.Infof("failed to initiate connection, err: %v", err)
conn.SetDeadline(time.Time{})
return
}
err = conn.SetDeadline(time.Time{})
if err != nil {
log.Errorf(err.Error())
return
}
user := sconn.User()
if err := s.limiter.RegisterRequest(user); err != nil {
log.Errorf(err.Error())
sconn.Close()
conn.Close()
return
}
// Connection successfully initiated
log.Infof("new ssh connection %v -> %v vesion: %v",
sconn.RemoteAddr(), sconn.LocalAddr(), string(sconn.ClientVersion()))
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
// Handle incoming out-of-band Requests
s.handleRequests(reqs)
wg.Done()
}()
go func() {
// Handle channel requests on this connections
s.handleChannels(conn, sconn, chans)
wg.Done()
}()
wg.Wait()
}
func (s *Server) handleRequests(reqs <-chan *ssh.Request) {
for req := range reqs {
log.Infof("recieved out-of-band request: %+v", req)
if s.reqHandler != nil {
s.reqHandler.HandleRequest(req)
}
}
}
func (s *Server) handleChannels(conn net.Conn, sconn *ssh.ServerConn, chans <-chan ssh.NewChannel) {
for nch := range chans {
if nch == nil {
log.Warningf("nil channel: %v", nch)
continue
}
s.newChanHandler.HandleNewChan(conn, sconn, nch)
}
}
type RequestHandler interface {
HandleRequest(r *ssh.Request)
}
type RequestHandlerFunc func(*ssh.Request)
func (f RequestHandlerFunc) HandleRequest(r *ssh.Request) {
f(r)
}
type NewChanHandler interface {
HandleNewChan(net.Conn, *ssh.ServerConn, ssh.NewChannel)
}
type NewChanHandlerFunc func(net.Conn, *ssh.ServerConn, ssh.NewChannel)
func (f NewChanHandlerFunc) HandleNewChan(conn net.Conn, sshConn *ssh.ServerConn, ch ssh.NewChannel) {
f(conn, sshConn, ch)
}
type AuthMethods struct {
PublicKey PublicKeyFunc
Password PasswordFunc
NoClient bool
}
func checkArguments(a utils.NetAddr, h NewChanHandler, hostSigners []ssh.Signer, ah AuthMethods) error {
if a.Addr == "" || a.AddrNetwork == "" {
return trace.Wrap(&teleport.BadParameterError{
Param: "addr",
Err: "specify network and the address for listening socket",
})
}
if h == nil {
return trace.Wrap(&teleport.BadParameterError{
Param: "handler",
Err: "missing NewChanHandler",
})
}
if len(hostSigners) == 0 {
return trace.Wrap(&teleport.BadParameterError{
Param: "hostSigners",
Err: "need at least one signer",
})
}
for _, s := range hostSigners {
if s == nil {
return trace.Wrap(&teleport.BadParameterError{
Param: "hostSigners",
Err: "host signer can not be nil",
})
}
}
if ah.PublicKey == nil && ah.Password == nil && ah.NoClient == false {
return trace.Wrap(&teleport.BadParameterError{
Param: "authMethod",
Err: "need at least one auth method",
})
}
return nil
}
type PublicKeyFunc func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error)
type PasswordFunc func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error)
// KeysEqual is constant time compare of the keys to avoid timing attacks
func KeysEqual(ak, bk ssh.PublicKey) bool {
a := ssh.Marshal(ak)
b := ssh.Marshal(bk)
return (len(a) == len(b) && subtle.ConstantTimeCompare(a, b) == 1)
}