add sshd listener
This commit is contained in:
@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/go-gost/gost/pkg/chain"
|
||||
"github.com/go-gost/gost/pkg/handler"
|
||||
"github.com/go-gost/gost/pkg/logger"
|
||||
md "github.com/go-gost/gost/pkg/metadata"
|
||||
"github.com/go-gost/gost/pkg/registry"
|
||||
)
|
||||
@ -22,7 +21,6 @@ func init() {
|
||||
type forwardHandler struct {
|
||||
group *chain.NodeGroup
|
||||
router *chain.Router
|
||||
logger logger.Logger
|
||||
md metadata
|
||||
options handler.Options
|
||||
}
|
||||
@ -55,7 +53,6 @@ func (h *forwardHandler) Init(md md.Metadata) (err error) {
|
||||
Hosts: h.options.Hosts,
|
||||
Logger: h.options.Logger,
|
||||
}
|
||||
h.logger = h.options.Logger
|
||||
|
||||
return
|
||||
}
|
||||
@ -69,21 +66,21 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
start := time.Now()
|
||||
h.logger = h.logger.WithFields(map[string]interface{}{
|
||||
log := h.options.Logger.WithFields(map[string]interface{}{
|
||||
"remote": conn.RemoteAddr().String(),
|
||||
"local": conn.LocalAddr().String(),
|
||||
})
|
||||
|
||||
h.logger.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
log.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
defer func() {
|
||||
h.logger.WithFields(map[string]interface{}{
|
||||
log.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(start),
|
||||
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
}()
|
||||
|
||||
target := h.group.Next()
|
||||
if target == nil {
|
||||
h.logger.Error("no target available")
|
||||
log.Error("no target available")
|
||||
return
|
||||
}
|
||||
|
||||
@ -92,15 +89,15 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
network = "udp"
|
||||
}
|
||||
|
||||
h.logger = h.logger.WithFields(map[string]interface{}{
|
||||
log = log.WithFields(map[string]interface{}{
|
||||
"dst": fmt.Sprintf("%s/%s", target.Addr(), network),
|
||||
})
|
||||
|
||||
h.logger.Infof("%s >> %s", conn.RemoteAddr(), target.Addr())
|
||||
log.Infof("%s >> %s", conn.RemoteAddr(), target.Addr())
|
||||
|
||||
cc, err := h.router.Dial(ctx, network, target.Addr())
|
||||
if err != nil {
|
||||
h.logger.Error(err)
|
||||
log.Error(err)
|
||||
// TODO: the router itself may be failed due to the failed node in the router,
|
||||
// the dead marker may be a wrong operation.
|
||||
target.Marker().Mark()
|
||||
@ -110,11 +107,9 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
target.Marker().Reset()
|
||||
|
||||
t := time.Now()
|
||||
h.logger.Infof("%s <-> %s", conn.RemoteAddr(), target.Addr())
|
||||
log.Infof("%s <-> %s", conn.RemoteAddr(), target.Addr())
|
||||
handler.Transport(conn, cc)
|
||||
h.logger.
|
||||
WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).
|
||||
Infof("%s >-< %s", conn.RemoteAddr(), target.Addr())
|
||||
log.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), target.Addr())
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/go-gost/gost/pkg/chain"
|
||||
"github.com/go-gost/gost/pkg/handler"
|
||||
"github.com/go-gost/gost/pkg/logger"
|
||||
md "github.com/go-gost/gost/pkg/metadata"
|
||||
"github.com/go-gost/gost/pkg/registry"
|
||||
)
|
||||
@ -21,7 +20,6 @@ func init() {
|
||||
type forwardHandler struct {
|
||||
group *chain.NodeGroup
|
||||
router *chain.Router
|
||||
logger logger.Logger
|
||||
md metadata
|
||||
options handler.Options
|
||||
}
|
||||
@ -49,7 +47,6 @@ func (h *forwardHandler) Init(md md.Metadata) (err error) {
|
||||
Hosts: h.options.Hosts,
|
||||
Logger: h.options.Logger,
|
||||
}
|
||||
h.logger = h.options.Logger
|
||||
|
||||
return
|
||||
}
|
||||
@ -63,21 +60,21 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
start := time.Now()
|
||||
h.logger = h.logger.WithFields(map[string]interface{}{
|
||||
log := h.options.Logger.WithFields(map[string]interface{}{
|
||||
"remote": conn.RemoteAddr().String(),
|
||||
"local": conn.LocalAddr().String(),
|
||||
})
|
||||
|
||||
h.logger.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
log.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
defer func() {
|
||||
h.logger.WithFields(map[string]interface{}{
|
||||
log.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(start),
|
||||
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
}()
|
||||
|
||||
target := h.group.Next()
|
||||
if target == nil {
|
||||
h.logger.Error("no target available")
|
||||
log.Error("no target available")
|
||||
return
|
||||
}
|
||||
|
||||
@ -86,15 +83,15 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
network = "udp"
|
||||
}
|
||||
|
||||
h.logger = h.logger.WithFields(map[string]interface{}{
|
||||
log = log.WithFields(map[string]interface{}{
|
||||
"dst": fmt.Sprintf("%s/%s", target.Addr(), network),
|
||||
})
|
||||
|
||||
h.logger.Infof("%s >> %s", conn.RemoteAddr(), target.Addr())
|
||||
log.Infof("%s >> %s", conn.RemoteAddr(), target.Addr())
|
||||
|
||||
cc, err := h.router.Dial(ctx, network, target.Addr())
|
||||
if err != nil {
|
||||
h.logger.Error(err)
|
||||
log.Error(err)
|
||||
// TODO: the router itself may be failed due to the failed node in the router,
|
||||
// the dead marker may be a wrong operation.
|
||||
target.Marker().Mark()
|
||||
@ -104,11 +101,9 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
target.Marker().Reset()
|
||||
|
||||
t := time.Now()
|
||||
h.logger.Infof("%s <-> %s", conn.RemoteAddr(), target.Addr())
|
||||
log.Infof("%s <-> %s", conn.RemoteAddr(), target.Addr())
|
||||
handler.Transport(conn, cc)
|
||||
h.logger.
|
||||
WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).
|
||||
Infof("%s >-< %s", conn.RemoteAddr(), target.Addr())
|
||||
log.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), target.Addr())
|
||||
}
|
||||
|
@ -1,300 +0,0 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-gost/gost/pkg/chain"
|
||||
auth_util "github.com/go-gost/gost/pkg/common/util/auth"
|
||||
"github.com/go-gost/gost/pkg/handler"
|
||||
ssh_util "github.com/go-gost/gost/pkg/internal/util/ssh"
|
||||
"github.com/go-gost/gost/pkg/logger"
|
||||
md "github.com/go-gost/gost/pkg/metadata"
|
||||
"github.com/go-gost/gost/pkg/registry"
|
||||
"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
|
||||
ForwardedTCPReturnRequest = "forwarded-tcpip" // RFC 4254 7.2
|
||||
CancelRemoteForwardRequest = "cancel-tcpip-forward" // RFC 4254 7.1
|
||||
)
|
||||
|
||||
func init() {
|
||||
registry.RegisterHandler("sshd", NewHandler)
|
||||
}
|
||||
|
||||
type forwardHandler struct {
|
||||
config *ssh.ServerConfig
|
||||
router *chain.Router
|
||||
logger logger.Logger
|
||||
md metadata
|
||||
options handler.Options
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.Options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
return &forwardHandler{
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *forwardHandler) Init(md md.Metadata) (err error) {
|
||||
if err = h.parseMetadata(md); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
authenticator := auth_util.AuthFromUsers(h.options.Auths...)
|
||||
|
||||
config := &ssh.ServerConfig{
|
||||
PasswordCallback: ssh_util.PasswordCallback(authenticator),
|
||||
PublicKeyCallback: ssh_util.PublicKeyCallback(h.md.authorizedKeys),
|
||||
}
|
||||
|
||||
config.AddHostKey(h.md.signer)
|
||||
|
||||
if authenticator == nil && len(h.md.authorizedKeys) == 0 {
|
||||
config.NoClientAuth = true
|
||||
}
|
||||
|
||||
h.config = config
|
||||
h.router = &chain.Router{
|
||||
Retries: h.options.Retries,
|
||||
Chain: h.options.Chain,
|
||||
Resolver: h.options.Resolver,
|
||||
Hosts: h.options.Hosts,
|
||||
Logger: h.options.Logger,
|
||||
}
|
||||
h.logger = h.options.Logger
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
start := time.Now()
|
||||
h.logger = h.logger.WithFields(map[string]interface{}{
|
||||
"remote": conn.RemoteAddr().String(),
|
||||
"local": conn.LocalAddr().String(),
|
||||
})
|
||||
|
||||
h.logger.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
defer func() {
|
||||
h.logger.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(start),
|
||||
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
}()
|
||||
|
||||
sshConn, chans, reqs, err := ssh.NewServerConn(conn, h.config)
|
||||
if err != nil {
|
||||
h.logger.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
h.handleForward(ctx, sshConn, chans, reqs)
|
||||
}
|
||||
|
||||
func (h *forwardHandler) handleForward(ctx context.Context, conn ssh.Conn, chans <-chan ssh.NewChannel, reqs <-chan *ssh.Request) {
|
||||
quit := make(chan struct{})
|
||||
defer close(quit) // quit signal
|
||||
|
||||
go func() {
|
||||
for req := range reqs {
|
||||
switch req.Type {
|
||||
case RemoteForwardRequest:
|
||||
go h.tcpipForwardRequest(conn, req, quit)
|
||||
default:
|
||||
h.logger.Warnf("unsupported request type: %s, want reply: %v", req.Type, req.WantReply)
|
||||
if req.WantReply {
|
||||
req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
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 {
|
||||
h.logger.Warnf("could not accept channel: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
p := directForward{}
|
||||
ssh.Unmarshal(newChannel.ExtraData(), &p)
|
||||
|
||||
h.logger.Debug(p.String())
|
||||
|
||||
if p.Host1 == "<nil>" {
|
||||
p.Host1 = ""
|
||||
}
|
||||
|
||||
go ssh.DiscardRequests(requests)
|
||||
go h.directPortForwardChannel(ctx, channel, net.JoinHostPort(p.Host1, strconv.Itoa(int(p.Port1))))
|
||||
default:
|
||||
h.logger.Warnf("unsupported channel type: %s", t)
|
||||
newChannel.Reject(ssh.Prohibited, fmt.Sprintf("unsupported channel type: %s", t))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
conn.Wait()
|
||||
}
|
||||
|
||||
func (h *forwardHandler) directPortForwardChannel(ctx context.Context, channel ssh.Channel, raddr string) {
|
||||
defer channel.Close()
|
||||
|
||||
// log.Logf("[ssh-tcp] %s - %s", h.options.Node.Addr, raddr)
|
||||
|
||||
/*
|
||||
if !Can("tcp", raddr, h.options.Whitelist, h.options.Blacklist) {
|
||||
log.Logf("[ssh-tcp] Unauthorized to tcp connect to %s", raddr)
|
||||
return
|
||||
}
|
||||
*/
|
||||
|
||||
if h.options.Bypass != nil && h.options.Bypass.Contains(raddr) {
|
||||
h.logger.Infof("bypass %s", raddr)
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := h.router.Dial(ctx, "tcp", raddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
t := time.Now()
|
||||
h.logger.Infof("%s <-> %s", conn.LocalAddr(), conn.RemoteAddr())
|
||||
handler.Transport(conn, channel)
|
||||
h.logger.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.LocalAddr(), conn.RemoteAddr())
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
func getHostPortFromAddr(addr net.Addr) (host string, port int, err error) {
|
||||
host, portString, err := net.SplitHostPort(addr.String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
port, err = strconv.Atoi(portString)
|
||||
return
|
||||
}
|
||||
|
||||
// tcpipForward is structure for RFC 4254 7.1 "tcpip-forward" request
|
||||
type tcpipForward struct {
|
||||
Host string
|
||||
Port uint32
|
||||
}
|
||||
|
||||
func (h *forwardHandler) tcpipForwardRequest(sshConn ssh.Conn, req *ssh.Request, quit <-chan struct{}) {
|
||||
t := tcpipForward{}
|
||||
ssh.Unmarshal(req.Payload, &t)
|
||||
|
||||
addr := net.JoinHostPort(t.Host, strconv.Itoa(int(t.Port)))
|
||||
|
||||
/*
|
||||
if !Can("rtcp", addr, h.options.Whitelist, h.options.Blacklist) {
|
||||
log.Logf("[ssh-rtcp] Unauthorized to tcp bind to %s", addr)
|
||||
req.Reply(false, nil)
|
||||
return
|
||||
}
|
||||
*/
|
||||
|
||||
// tie to the client connection
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
h.logger.Error(err)
|
||||
req.Reply(false, nil)
|
||||
return
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
h.logger.Debugf("bind on %s OK", ln.Addr())
|
||||
|
||||
err = func() error {
|
||||
if t.Port == 0 && req.WantReply { // Client sent port 0. let them know which port is actually being used
|
||||
_, port, err := getHostPortFromAddr(ln.Addr())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], uint32(port))
|
||||
t.Port = uint32(port)
|
||||
return req.Reply(true, b[:])
|
||||
}
|
||||
return req.Reply(true, nil)
|
||||
}()
|
||||
if err != nil {
|
||||
h.logger.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil { // Unable to accept new connection - listener is likely closed
|
||||
return
|
||||
}
|
||||
|
||||
go func(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
p := directForward{}
|
||||
var err error
|
||||
|
||||
var portnum int
|
||||
p.Host1 = t.Host
|
||||
p.Port1 = t.Port
|
||||
p.Host2, portnum, err = getHostPortFromAddr(conn.RemoteAddr())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
p.Port2 = uint32(portnum)
|
||||
ch, reqs, err := sshConn.OpenChannel(ForwardedTCPReturnRequest, ssh.Marshal(p))
|
||||
if err != nil {
|
||||
h.logger.Error("open forwarded channel: ", err)
|
||||
return
|
||||
}
|
||||
defer ch.Close()
|
||||
go ssh.DiscardRequests(reqs)
|
||||
|
||||
t := time.Now()
|
||||
h.logger.Infof("%s <-> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
handler.Transport(ch, conn)
|
||||
h.logger.WithFields(map[string]interface{}{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
|
||||
<-quit
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
|
||||
tls_util "github.com/go-gost/gost/pkg/common/util/tls"
|
||||
ssh_util "github.com/go-gost/gost/pkg/internal/util/ssh"
|
||||
mdata "github.com/go-gost/gost/pkg/metadata"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type metadata struct {
|
||||
signer ssh.Signer
|
||||
authorizedKeys map[string]bool
|
||||
}
|
||||
|
||||
func (h *forwardHandler) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
authorizedKeys = "authorizedKeys"
|
||||
privateKeyFile = "privateKeyFile"
|
||||
passphrase = "passphrase"
|
||||
)
|
||||
|
||||
if key := mdata.GetString(md, privateKeyFile); key != "" {
|
||||
data, err := ioutil.ReadFile(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pp := mdata.GetString(md, passphrase)
|
||||
if pp == "" {
|
||||
h.md.signer, err = ssh.ParsePrivateKey(data)
|
||||
} else {
|
||||
h.md.signer, err = ssh.ParsePrivateKeyWithPassphrase(data, []byte(pp))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if h.md.signer == nil {
|
||||
signer, err := ssh.NewSignerFromKey(tls_util.DefaultConfig.Clone().Certificates[0].PrivateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.md.signer = signer
|
||||
}
|
||||
|
||||
if name := mdata.GetString(md, authorizedKeys); name != "" {
|
||||
m, err := ssh_util.ParseAuthorizedKeysFile(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.md.authorizedKeys = m
|
||||
}
|
||||
|
||||
return
|
||||
}
|
Reference in New Issue
Block a user