| 1 | package ssh |
| 2 | |
| 3 | import ( |
| 4 | "net" |
| 5 | |
| 6 | libio "github.com/fatedier/golib/io" |
| 7 | "golang.org/x/crypto/ssh" |
| 8 | ) |
| 9 | |
| 10 | type TunnelClient struct { |
| 11 | localAddr string |
| 12 | sshServer string |
| 13 | commands string |
| 14 | |
| 15 | sshConn *ssh.Client |
| 16 | ln net.Listener |
| 17 | } |
| 18 | |
| 19 | func NewTunnelClient(localAddr string, sshServer string, commands string) *TunnelClient { |
| 20 | return &TunnelClient{ |
| 21 | localAddr: localAddr, |
| 22 | sshServer: sshServer, |
| 23 | commands: commands, |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | func (c *TunnelClient) Start() error { |
| 28 | config := &ssh.ClientConfig{ |
| 29 | User: "v0", |
| 30 | HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil }, |
| 31 | } |
| 32 | |
| 33 | conn, err := ssh.Dial("tcp", c.sshServer, config) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | c.sshConn = conn |
| 38 | |
| 39 | l, err := conn.Listen("tcp", "0.0.0.0:80") |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | c.ln = l |
| 44 | ch, req, err := conn.OpenChannel("session", []byte("")) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | defer ch.Close() |
| 49 | go ssh.DiscardRequests(req) |
| 50 | |
| 51 | type command struct { |
| 52 | Cmd string |
| 53 | } |
| 54 | _, err = ch.SendRequest("exec", false, ssh.Marshal(command{Cmd: c.commands})) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | |
| 59 | go c.serveListener() |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | func (c *TunnelClient) Close() { |
| 64 | if c.sshConn != nil { |
| 65 | _ = c.sshConn.Close() |
| 66 | } |
| 67 | if c.ln != nil { |
| 68 | _ = c.ln.Close() |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func (c *TunnelClient) serveListener() { |
| 73 | for { |
| 74 | conn, err := c.ln.Accept() |
| 75 | if err != nil { |
| 76 | return |
| 77 | } |
| 78 | go c.handleConn(conn) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func (c *TunnelClient) handleConn(conn net.Conn) { |
| 83 | defer conn.Close() |
| 84 | local, err := net.Dial("tcp", c.localAddr) |
| 85 | if err != nil { |
| 86 | return |
| 87 | } |
| 88 | _, _, _ = libio.Join(local, conn) |
| 89 | } |