forked from artyom/mosh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mosh.go
180 lines (169 loc) · 4.57 KB
/
mosh.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
// Command mosh is an alternative wrapper to mosh-client command that plays well with socks proxies.
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/net/proxy"
"github.com/artyom/autoflags"
)
func main() {
defaultUser := os.Getenv("MOSH_USER")
if defaultUser == "" {
defaultUser = os.Getenv("USER")
}
defaultPorts := os.Getenv("MOSH_PORTS")
if defaultPorts == "" {
defaultPorts = "60000:60050"
}
params := struct {
SSHPort int `flag:"sshport,ssh port to use"`
Login string `flag:"l,login"`
MoshPorts string `flag:"p,server-side UDP port or colon-separated range"`
Timeout time.Duration `flag:"timeout,ssh connect timeout"`
}{
SSHPort: 22,
Login: defaultUser,
MoshPorts: defaultPorts,
Timeout: 5 * time.Second,
}
autoflags.Define(¶ms)
flag.Parse()
if len(flag.Args()) != 1 {
flag.Usage()
os.Exit(1)
}
addr := flag.Args()[0]
ips, err := net.LookupIP(addr)
if err != nil {
log.Fatal(err)
}
if len(ips) == 0 {
log.Fatalf("name %q resolved to %v", addr, ips)
}
clientPath, err := exec.LookPath("mosh-client")
if err != nil {
log.Fatal(err)
}
port, key, err := runServer(addr, params.Login, params.MoshPorts, params.SSHPort, params.Timeout)
if err != nil {
log.Fatal(err)
}
newEnv := append([]string{}, os.Environ()...)
newEnv = append(newEnv, "MOSH_KEY="+key)
log.Fatal(syscall.Exec(clientPath, []string{"mosh-client", ips[0].String(), strconv.Itoa(port)}, newEnv))
}
func runServer(addr, login, moshPorts string, port int, tout time.Duration) (int, string, error) {
hostKeyCallback, err := knownhosts.New(os.ExpandEnv("$HOME/.ssh/known_hosts"))
if err != nil {
return 0, "", err
}
var sshAgent agent.Agent
agentConn, err := net.DialTimeout("unix", os.Getenv("SSH_AUTH_SOCK"), tout)
if err != nil {
return 0, "", err
}
sshAgent = agent.NewClient(agentConn)
defer agentConn.Close()
signers, err := sshAgent.Signers()
if err != nil {
return 0, "", err
}
sshConfig := &ssh.ClientConfig{
User: login,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...),
ssh.KeyboardInteractive(keyboardChallenge)},
HostKeyCallback: hostKeyCallback,
}
client, err := sshDial("tcp", net.JoinHostPort(addr, strconv.Itoa(port)), sshConfig)
if err != nil {
return 0, "", err
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return 0, "", err
}
defer session.Close()
width, height := 80, 25
if w, h, err := terminal.GetSize(0); err == nil {
width, height = w, h
}
if err := session.RequestPty(os.Getenv("TERM"), height, width, make(ssh.TerminalModes)); err != nil {
return 0, "", err
}
rdata, err := session.CombinedOutput("mosh-server new -p " + moshPorts)
if err != nil {
os.Stderr.Write(rdata)
return 0, "", err
}
return parsePortKey(rdata)
}
func parsePortKey(b []byte) (port int, key string, err error) {
for s := bufio.NewScanner(bytes.NewReader(b)); s.Scan(); {
if !bytes.HasPrefix(s.Bytes(), []byte("MOSH CONNECT")) {
continue
}
fields := strings.Fields(s.Text())
if len(fields) != 4 {
return 0, "", fmt.Errorf("unexpected response line from mosh-server: %q", s.Text())
}
port, err = strconv.Atoi(fields[2])
if err != nil {
return 0, "", err
}
key = fields[3]
return port, key, nil
}
return 0, "", fmt.Errorf("no 'MOSH CONNECT' line from mosh-server")
}
func sshDial(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
proxyDialer := proxy.FromEnvironment()
conn, err := proxyDialer.Dial(network, addr)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
func init() {
log.SetFlags(0)
log.SetPrefix("mosh: ")
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: mosh [flags] hostname")
flag.PrintDefaults()
}
}
func keyboardChallenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
if len(questions) != 0 {
return nil, fmt.Errorf("keyboard interactive challenge is not supported")
}
// https://godoc.org/golang.org/x/crypto/ssh#KeyboardInteractiveChallenge
//
// After successful authentication, the server may send
// a challenge with no questions, for which the user and
// instruction messages should be printed.
if user != "" {
log.Println(user)
}
if instruction != "" {
log.Println(instruction)
}
return nil, nil
}