2017-12-03 00:24:05 +00:00
|
|
|
package sshd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/shazow/rateio"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
)
|
|
|
|
|
2019-11-17 20:42:41 +00:00
|
|
|
// SSHListener is the container for the connection and ssh-related configuration
|
2017-12-03 00:24:05 +00:00
|
|
|
type SSHListener struct {
|
|
|
|
net.Listener
|
|
|
|
config *ssh.ServerConfig
|
|
|
|
|
|
|
|
RateLimit func() rateio.Limiter
|
|
|
|
HandlerFunc func(term *Terminal)
|
|
|
|
}
|
|
|
|
|
2019-11-17 20:42:41 +00:00
|
|
|
// ListenSSH makes an SSH listener socket
|
2017-12-03 00:24:05 +00:00
|
|
|
func ListenSSH(laddr string, config *ssh.ServerConfig) (*SSHListener, error) {
|
|
|
|
socket, err := net.Listen("tcp", laddr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
l := SSHListener{Listener: socket, config: config}
|
|
|
|
return &l, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *SSHListener) handleConn(conn net.Conn) (*Terminal, error) {
|
|
|
|
if l.RateLimit != nil {
|
|
|
|
// TODO: Configurable Limiter?
|
|
|
|
conn = ReadLimitConn(conn, l.RateLimit())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Upgrade TCP connection to SSH connection
|
|
|
|
sshConn, channels, requests, err := ssh.NewServerConn(conn, l.config)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME: Disconnect if too many faulty requests? (Avoid DoS.)
|
|
|
|
go ssh.DiscardRequests(requests)
|
|
|
|
return NewSession(sshConn, channels)
|
|
|
|
}
|
|
|
|
|
2019-11-17 20:42:41 +00:00
|
|
|
// Serve Accepts incoming connections as terminal requests and yield them
|
2017-12-03 00:24:05 +00:00
|
|
|
func (l *SSHListener) Serve() {
|
|
|
|
defer l.Close()
|
|
|
|
for {
|
|
|
|
conn, err := l.Accept()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
logger.Printf("Failed to accept connection: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Goroutineify to resume accepting sockets early
|
|
|
|
go func() {
|
|
|
|
term, err := l.handleConn(conn)
|
|
|
|
if err != nil {
|
|
|
|
logger.Printf("[%s] Failed to handshake: %s", conn.RemoteAddr(), err)
|
2019-11-17 20:42:41 +00:00
|
|
|
conn.Close() // Must be closed to avoid a leak
|
2017-12-03 00:24:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
l.HandlerFunc(term)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|