1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 5 package ssh
6 7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "net"
12 "os"
13 "sync"
14 "time"
15 )
16 17 // Client implements a traditional SSH client that supports shells,
18 // subprocesses, TCP port/streamlocal forwarding and tunneled dialing.
19 type Client struct {
20 Conn
21 22 handleForwardsOnce sync.Once // guards calling (*Client).handleForwards
23 24 forwards forwardList // forwarded tcpip connections from the remote side
25 mu sync.Mutex
26 channelHandlers map[string]chan NewChannel
27 }
28 29 // HandleChannelOpen returns a channel on which NewChannel requests
30 // for the given type are sent. If the type already is being handled,
31 // nil is returned. The channel is closed when the connection is closed.
32 func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
33 c.mu.Lock()
34 defer c.mu.Unlock()
35 if c.channelHandlers == nil {
36 // The SSH channel has been closed.
37 c := make(chan NewChannel)
38 close(c)
39 return c
40 }
41 42 ch := c.channelHandlers[channelType]
43 if ch != nil {
44 return nil
45 }
46 47 ch = make(chan NewChannel, chanSize)
48 c.channelHandlers[channelType] = ch
49 return ch
50 }
51 52 // NewClient creates a Client on top of the given connection.
53 func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
54 conn := &Client{
55 Conn: c,
56 channelHandlers: make(map[string]chan NewChannel, 1),
57 }
58 59 go conn.handleGlobalRequests(reqs)
60 go conn.handleChannelOpens(chans)
61 go func() {
62 conn.Wait()
63 conn.forwards.closeAll()
64 }()
65 return conn
66 }
67 68 // NewClientConn establishes an authenticated SSH connection using c
69 // as the underlying transport. The Request and NewChannel channels
70 // must be serviced or the connection will hang.
71 func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) {
72 fullConf := *config
73 fullConf.SetDefaults()
74 if fullConf.HostKeyCallback == nil {
75 c.Close()
76 return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback")
77 }
78 79 conn := &connection{
80 sshConn: sshConn{conn: c, user: fullConf.User},
81 }
82 83 if err := conn.clientHandshake(addr, &fullConf); err != nil {
84 c.Close()
85 return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %w", err)
86 }
87 conn.mux = newMux(conn.transport)
88 return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
89 }
90 91 // clientHandshake performs the client side key exchange. See RFC 4253 Section
92 // 7.
93 func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
94 if config.ClientVersion != "" {
95 c.clientVersion = []byte(config.ClientVersion)
96 } else {
97 c.clientVersion = []byte(packageVersion)
98 }
99 var err error
100 c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
101 if err != nil {
102 return err
103 }
104 105 c.transport = newClientTransport(
106 newTransport(c.sshConn.conn, config.Rand, true /* is client */),
107 c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
108 if err := c.transport.waitSession(); err != nil {
109 return err
110 }
111 112 c.sessionID = c.transport.getSessionID()
113 c.algorithms = c.transport.getAlgorithms()
114 return c.clientAuthenticate(config)
115 }
116 117 // verifyHostKeySignature verifies the host key obtained in the key exchange.
118 // algo is the negotiated algorithm, and may be a certificate type.
119 func verifyHostKeySignature(hostKey PublicKey, algo string, result *kexResult) error {
120 sig, rest, ok := parseSignatureBody(result.Signature)
121 if len(rest) > 0 || !ok {
122 return errors.New("ssh: signature parse error")
123 }
124 125 if a := underlyingAlgo(algo); sig.Format != a {
126 return fmt.Errorf("ssh: invalid signature algorithm %q, expected %q", sig.Format, a)
127 }
128 129 return hostKey.Verify(result.H, sig)
130 }
131 132 // NewSession opens a new Session for this client. (A session is a remote
133 // execution of a program.)
134 func (c *Client) NewSession() (*Session, error) {
135 ch, in, err := c.OpenChannel("session", nil)
136 if err != nil {
137 return nil, err
138 }
139 return newSession(ch, in)
140 }
141 142 func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
143 for r := range incoming {
144 // This handles keepalive messages and matches
145 // the behaviour of OpenSSH.
146 r.Reply(false, nil)
147 }
148 }
149 150 // handleChannelOpens channel open messages from the remote side.
151 func (c *Client) handleChannelOpens(in <-chan NewChannel) {
152 for ch := range in {
153 c.mu.Lock()
154 handler := c.channelHandlers[ch.ChannelType()]
155 c.mu.Unlock()
156 157 if handler != nil {
158 handler <- ch
159 } else {
160 ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
161 }
162 }
163 164 c.mu.Lock()
165 for _, ch := range c.channelHandlers {
166 close(ch)
167 }
168 c.channelHandlers = nil
169 c.mu.Unlock()
170 }
171 172 // Dial starts a client connection to the given SSH server. It is a
173 // convenience function that connects to the given network address,
174 // initiates the SSH handshake, and then sets up a Client. For access
175 // to incoming channels and requests, use net.Dial with NewClientConn
176 // instead.
177 func Dial(network, addr string, config *ClientConfig) (*Client, error) {
178 conn, err := net.DialTimeout(network, addr, config.Timeout)
179 if err != nil {
180 return nil, err
181 }
182 c, chans, reqs, err := NewClientConn(conn, addr, config)
183 if err != nil {
184 return nil, err
185 }
186 return NewClient(c, chans, reqs), nil
187 }
188 189 // HostKeyCallback is the function type used for verifying server
190 // keys. A HostKeyCallback must return nil if the host key is OK, or
191 // an error to reject it. It receives the hostname as passed to Dial
192 // or NewClientConn. The remote address is the RemoteAddr of the
193 // net.Conn underlying the SSH connection.
194 type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
195 196 // BannerCallback is the function type used for treat the banner sent by
197 // the server. A BannerCallback receives the message sent by the remote server.
198 type BannerCallback func(message string) error
199 200 // A ClientConfig structure is used to configure a Client. It must not be
201 // modified after having been passed to an SSH function.
202 type ClientConfig struct {
203 // Config contains configuration that is shared between clients and
204 // servers.
205 Config
206 207 // User contains the username to authenticate as.
208 User string
209 210 // Auth contains possible authentication methods to use with the
211 // server. Only the first instance of a particular RFC 4252 method will
212 // be used during authentication.
213 Auth []AuthMethod
214 215 // HostKeyCallback is called during the cryptographic
216 // handshake to validate the server's host key. The client
217 // configuration must supply this callback for the connection
218 // to succeed. The functions InsecureIgnoreHostKey or
219 // FixedHostKey can be used for simplistic host key checks.
220 HostKeyCallback HostKeyCallback
221 222 // BannerCallback is called during the SSH dance to display a custom
223 // server's message. The client configuration can supply this callback to
224 // handle it as wished. The function BannerDisplayStderr can be used for
225 // simplistic display on Stderr.
226 BannerCallback BannerCallback
227 228 // ClientVersion contains the version identification string that will
229 // be used for the connection. If empty, a reasonable default is used.
230 ClientVersion string
231 232 // HostKeyAlgorithms lists the public key algorithms that the client will
233 // accept from the server for host key authentication, in order of
234 // preference. If empty, a reasonable default is used. Any
235 // string returned from a PublicKey.Type method may be used, or
236 // any of the CertAlgo and KeyAlgo constants.
237 HostKeyAlgorithms []string
238 239 // Timeout is the maximum amount of time for the TCP connection to establish.
240 //
241 // A Timeout of zero means no timeout.
242 Timeout time.Duration
243 }
244 245 // InsecureIgnoreHostKey returns a function that can be used for
246 // ClientConfig.HostKeyCallback to accept any host key. It should
247 // not be used for production code.
248 func InsecureIgnoreHostKey() HostKeyCallback {
249 return func(hostname string, remote net.Addr, key PublicKey) error {
250 return nil
251 }
252 }
253 254 type fixedHostKey struct {
255 key PublicKey
256 }
257 258 func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error {
259 if f.key == nil {
260 return fmt.Errorf("ssh: required host key was nil")
261 }
262 if !bytes.Equal(key.Marshal(), f.key.Marshal()) {
263 return fmt.Errorf("ssh: host key mismatch")
264 }
265 return nil
266 }
267 268 // FixedHostKey returns a function for use in
269 // ClientConfig.HostKeyCallback to accept only a specific host key.
270 func FixedHostKey(key PublicKey) HostKeyCallback {
271 hk := &fixedHostKey{key}
272 return hk.check
273 }
274 275 // BannerDisplayStderr returns a function that can be used for
276 // ClientConfig.BannerCallback to display banners on os.Stderr.
277 func BannerDisplayStderr() BannerCallback {
278 return func(banner string) error {
279 _, err := os.Stderr.WriteString(banner)
280 281 return err
282 }
283 }
284