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.
17 // Client implements a traditional SSH client that supports shells,
18 // subprocesses, TCP port/streamlocal forwarding and tunneled dialing.
22 handleForwardsOnce sync.Once // guards calling (*Client).handleForwards
24 forwards forwardList // forwarded tcpip connections from the remote side
26 channelHandlers map[string]chan NewChannel
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 {
35 if c.channelHandlers == nil {
36 // The SSH channel has been closed.
37 c := make(chan NewChannel)
42 ch := c.channelHandlers[channelType]
47 ch = make(chan NewChannel, chanSize)
48 c.channelHandlers[channelType] = ch
52 // NewClient creates a Client on top of the given connection.
53 func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
56 channelHandlers: make(map[string]chan NewChannel, 1),
59 go conn.handleGlobalRequests(reqs)
60 go conn.handleChannelOpens(chans)
63 conn.forwards.closeAll()
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) {
73 fullConf.SetDefaults()
74 if fullConf.HostKeyCallback == nil {
76 return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback")
80 sshConn: sshConn{conn: c},
83 if err := conn.clientHandshake(addr, &fullConf); err != nil {
85 return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err)
87 conn.mux = newMux(conn.transport)
88 return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
91 // clientHandshake performs the client side key exchange. See RFC 4253 Section
93 func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
94 if config.ClientVersion != "" {
95 c.clientVersion = []byte(config.ClientVersion)
97 c.clientVersion = []byte(packageVersion)
100 c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
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 {
112 c.sessionID = c.transport.getSessionID()
113 return c.clientAuthenticate(config)
116 // verifyHostKeySignature verifies the host key obtained in the key
118 func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
119 sig, rest, ok := parseSignatureBody(result.Signature)
120 if len(rest) > 0 || !ok {
121 return errors.New("ssh: signature parse error")
124 return hostKey.Verify(result.H, sig)
127 // NewSession opens a new Session for this client. (A session is a remote
128 // execution of a program.)
129 func (c *Client) NewSession() (*Session, error) {
130 ch, in, err := c.OpenChannel("session", nil)
134 return newSession(ch, in)
137 func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
138 for r := range incoming {
139 // This handles keepalive messages and matches
140 // the behaviour of OpenSSH.
145 // handleChannelOpens channel open messages from the remote side.
146 func (c *Client) handleChannelOpens(in <-chan NewChannel) {
149 handler := c.channelHandlers[ch.ChannelType()]
155 ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
160 for _, ch := range c.channelHandlers {
163 c.channelHandlers = nil
167 // Dial starts a client connection to the given SSH server. It is a
168 // convenience function that connects to the given network address,
169 // initiates the SSH handshake, and then sets up a Client. For access
170 // to incoming channels and requests, use net.Dial with NewClientConn
172 func Dial(network, addr string, config *ClientConfig) (*Client, error) {
173 conn, err := net.DialTimeout(network, addr, config.Timeout)
177 c, chans, reqs, err := NewClientConn(conn, addr, config)
181 return NewClient(c, chans, reqs), nil
184 // HostKeyCallback is the function type used for verifying server
185 // keys. A HostKeyCallback must return nil if the host key is OK, or
186 // an error to reject it. It receives the hostname as passed to Dial
187 // or NewClientConn. The remote address is the RemoteAddr of the
188 // net.Conn underlying the SSH connection.
189 type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
191 // BannerCallback is the function type used for treat the banner sent by
192 // the server. A BannerCallback receives the message sent by the remote server.
193 type BannerCallback func(message string) error
195 // A ClientConfig structure is used to configure a Client. It must not be
196 // modified after having been passed to an SSH function.
197 type ClientConfig struct {
198 // Config contains configuration that is shared between clients and
202 // User contains the username to authenticate as.
205 // Auth contains possible authentication methods to use with the
206 // server. Only the first instance of a particular RFC 4252 method will
207 // be used during authentication.
210 // HostKeyCallback is called during the cryptographic
211 // handshake to validate the server's host key. The client
212 // configuration must supply this callback for the connection
213 // to succeed. The functions InsecureIgnoreHostKey or
214 // FixedHostKey can be used for simplistic host key checks.
215 HostKeyCallback HostKeyCallback
217 // BannerCallback is called during the SSH dance to display a custom
218 // server's message. The client configuration can supply this callback to
219 // handle it as wished. The function BannerDisplayStderr can be used for
220 // simplistic display on Stderr.
221 BannerCallback BannerCallback
223 // ClientVersion contains the version identification string that will
224 // be used for the connection. If empty, a reasonable default is used.
227 // HostKeyAlgorithms lists the key types that the client will
228 // accept from the server as host key, in order of
229 // preference. If empty, a reasonable default is used. Any
230 // string returned from PublicKey.Type method may be used, or
231 // any of the CertAlgoXxxx and KeyAlgoXxxx constants.
232 HostKeyAlgorithms []string
234 // Timeout is the maximum amount of time for the TCP connection to establish.
236 // A Timeout of zero means no timeout.
237 Timeout time.Duration
240 // InsecureIgnoreHostKey returns a function that can be used for
241 // ClientConfig.HostKeyCallback to accept any host key. It should
242 // not be used for production code.
243 func InsecureIgnoreHostKey() HostKeyCallback {
244 return func(hostname string, remote net.Addr, key PublicKey) error {
249 type fixedHostKey struct {
253 func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error {
255 return fmt.Errorf("ssh: required host key was nil")
257 if !bytes.Equal(key.Marshal(), f.key.Marshal()) {
258 return fmt.Errorf("ssh: host key mismatch")
263 // FixedHostKey returns a function for use in
264 // ClientConfig.HostKeyCallback to accept only a specific host key.
265 func FixedHostKey(key PublicKey) HostKeyCallback {
266 hk := &fixedHostKey{key}
270 // BannerDisplayStderr returns a function that can be used for
271 // ClientConfig.BannerCallback to display banners on os.Stderr.
272 func BannerDisplayStderr() BannerCallback {
273 return func(banner string) error {
274 _, err := os.Stderr.WriteString(banner)