main
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
5package ssh
6
7import (
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.
19type 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.
32func (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.
53func 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.
71func 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.
93func (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 return c.clientAuthenticate(config)
114}
115
116// verifyHostKeySignature verifies the host key obtained in the key exchange.
117// algo is the negotiated algorithm, and may be a certificate type.
118func verifyHostKeySignature(hostKey PublicKey, algo string, result *kexResult) error {
119 sig, rest, ok := parseSignatureBody(result.Signature)
120 if len(rest) > 0 || !ok {
121 return errors.New("ssh: signature parse error")
122 }
123
124 if a := underlyingAlgo(algo); sig.Format != a {
125 return fmt.Errorf("ssh: invalid signature algorithm %q, expected %q", sig.Format, a)
126 }
127
128 return hostKey.Verify(result.H, sig)
129}
130
131// NewSession opens a new Session for this client. (A session is a remote
132// execution of a program.)
133func (c *Client) NewSession() (*Session, error) {
134 ch, in, err := c.OpenChannel("session", nil)
135 if err != nil {
136 return nil, err
137 }
138 return newSession(ch, in)
139}
140
141func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
142 for r := range incoming {
143 // This handles keepalive messages and matches
144 // the behaviour of OpenSSH.
145 r.Reply(false, nil)
146 }
147}
148
149// handleChannelOpens channel open messages from the remote side.
150func (c *Client) handleChannelOpens(in <-chan NewChannel) {
151 for ch := range in {
152 c.mu.Lock()
153 handler := c.channelHandlers[ch.ChannelType()]
154 c.mu.Unlock()
155
156 if handler != nil {
157 handler <- ch
158 } else {
159 ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
160 }
161 }
162
163 c.mu.Lock()
164 for _, ch := range c.channelHandlers {
165 close(ch)
166 }
167 c.channelHandlers = nil
168 c.mu.Unlock()
169}
170
171// Dial starts a client connection to the given SSH server. It is a
172// convenience function that connects to the given network address,
173// initiates the SSH handshake, and then sets up a Client. For access
174// to incoming channels and requests, use net.Dial with NewClientConn
175// instead.
176func Dial(network, addr string, config *ClientConfig) (*Client, error) {
177 conn, err := net.DialTimeout(network, addr, config.Timeout)
178 if err != nil {
179 return nil, err
180 }
181 c, chans, reqs, err := NewClientConn(conn, addr, config)
182 if err != nil {
183 return nil, err
184 }
185 return NewClient(c, chans, reqs), nil
186}
187
188// HostKeyCallback is the function type used for verifying server
189// keys. A HostKeyCallback must return nil if the host key is OK, or
190// an error to reject it. It receives the hostname as passed to Dial
191// or NewClientConn. The remote address is the RemoteAddr of the
192// net.Conn underlying the SSH connection.
193type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
194
195// BannerCallback is the function type used for treat the banner sent by
196// the server. A BannerCallback receives the message sent by the remote server.
197type BannerCallback func(message string) error
198
199// A ClientConfig structure is used to configure a Client. It must not be
200// modified after having been passed to an SSH function.
201type ClientConfig struct {
202 // Config contains configuration that is shared between clients and
203 // servers.
204 Config
205
206 // User contains the username to authenticate as.
207 User string
208
209 // Auth contains possible authentication methods to use with the
210 // server. Only the first instance of a particular RFC 4252 method will
211 // be used during authentication.
212 Auth []AuthMethod
213
214 // HostKeyCallback is called during the cryptographic
215 // handshake to validate the server's host key. The client
216 // configuration must supply this callback for the connection
217 // to succeed. The functions InsecureIgnoreHostKey or
218 // FixedHostKey can be used for simplistic host key checks.
219 HostKeyCallback HostKeyCallback
220
221 // BannerCallback is called during the SSH dance to display a custom
222 // server's message. The client configuration can supply this callback to
223 // handle it as wished. The function BannerDisplayStderr can be used for
224 // simplistic display on Stderr.
225 BannerCallback BannerCallback
226
227 // ClientVersion contains the version identification string that will
228 // be used for the connection. If empty, a reasonable default is used.
229 ClientVersion string
230
231 // HostKeyAlgorithms lists the public key algorithms that the client will
232 // accept from the server for host key authentication, in order of
233 // preference. If empty, a reasonable default is used. Any
234 // string returned from a PublicKey.Type method may be used, or
235 // any of the CertAlgo and KeyAlgo constants.
236 HostKeyAlgorithms []string
237
238 // Timeout is the maximum amount of time for the TCP connection to establish.
239 //
240 // A Timeout of zero means no timeout.
241 Timeout time.Duration
242}
243
244// InsecureIgnoreHostKey returns a function that can be used for
245// ClientConfig.HostKeyCallback to accept any host key. It should
246// not be used for production code.
247func InsecureIgnoreHostKey() HostKeyCallback {
248 return func(hostname string, remote net.Addr, key PublicKey) error {
249 return nil
250 }
251}
252
253type fixedHostKey struct {
254 key PublicKey
255}
256
257func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error {
258 if f.key == nil {
259 return fmt.Errorf("ssh: required host key was nil")
260 }
261 if !bytes.Equal(key.Marshal(), f.key.Marshal()) {
262 return fmt.Errorf("ssh: host key mismatch")
263 }
264 return nil
265}
266
267// FixedHostKey returns a function for use in
268// ClientConfig.HostKeyCallback to accept only a specific host key.
269func FixedHostKey(key PublicKey) HostKeyCallback {
270 hk := &fixedHostKey{key}
271 return hk.check
272}
273
274// BannerDisplayStderr returns a function that can be used for
275// ClientConfig.BannerCallback to display banners on os.Stderr.
276func BannerDisplayStderr() BannerCallback {
277 return func(banner string) error {
278 _, err := os.Stderr.WriteString(banner)
279
280 return err
281 }
282}