client.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. package ssh
  5. import (
  6. "errors"
  7. "fmt"
  8. "net"
  9. "sync"
  10. "time"
  11. )
  12. // Client implements a traditional SSH client that supports shells,
  13. // subprocesses, port forwarding and tunneled dialing.
  14. type Client struct {
  15. Conn
  16. forwards forwardList // forwarded tcpip connections from the remote side
  17. mu sync.Mutex
  18. channelHandlers map[string]chan NewChannel
  19. }
  20. // HandleChannelOpen returns a channel on which NewChannel requests
  21. // for the given type are sent. If the type already is being handled,
  22. // nil is returned. The channel is closed when the connection is closed.
  23. func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
  24. c.mu.Lock()
  25. defer c.mu.Unlock()
  26. if c.channelHandlers == nil {
  27. // The SSH channel has been closed.
  28. c := make(chan NewChannel)
  29. close(c)
  30. return c
  31. }
  32. ch := c.channelHandlers[channelType]
  33. if ch != nil {
  34. return nil
  35. }
  36. ch = make(chan NewChannel, chanSize)
  37. c.channelHandlers[channelType] = ch
  38. return ch
  39. }
  40. // NewClient creates a Client on top of the given connection.
  41. func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
  42. conn := &Client{
  43. Conn: c,
  44. channelHandlers: make(map[string]chan NewChannel, 1),
  45. }
  46. go conn.handleGlobalRequests(reqs)
  47. go conn.handleChannelOpens(chans)
  48. go func() {
  49. conn.Wait()
  50. conn.forwards.closeAll()
  51. }()
  52. go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip"))
  53. return conn
  54. }
  55. // NewClientConn establishes an authenticated SSH connection using c
  56. // as the underlying transport. The Request and NewChannel channels
  57. // must be serviced or the connection will hang.
  58. func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) {
  59. fullConf := *config
  60. fullConf.SetDefaults()
  61. conn := &connection{
  62. sshConn: sshConn{conn: c},
  63. }
  64. if err := conn.clientHandshake(addr, &fullConf); err != nil {
  65. c.Close()
  66. return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err)
  67. }
  68. conn.mux = newMux(conn.transport)
  69. return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
  70. }
  71. // clientHandshake performs the client side key exchange. See RFC 4253 Section
  72. // 7.
  73. func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
  74. if config.ClientVersion != "" {
  75. c.clientVersion = []byte(config.ClientVersion)
  76. } else {
  77. c.clientVersion = []byte(packageVersion)
  78. }
  79. var err error
  80. c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
  81. if err != nil {
  82. return err
  83. }
  84. c.transport = newClientTransport(
  85. newTransport(c.sshConn.conn, config.Rand, true /* is client */),
  86. c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
  87. if err := c.transport.waitSession(); err != nil {
  88. return err
  89. }
  90. c.sessionID = c.transport.getSessionID()
  91. return c.clientAuthenticate(config)
  92. }
  93. // verifyHostKeySignature verifies the host key obtained in the key
  94. // exchange.
  95. func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
  96. sig, rest, ok := parseSignatureBody(result.Signature)
  97. if len(rest) > 0 || !ok {
  98. return errors.New("ssh: signature parse error")
  99. }
  100. return hostKey.Verify(result.H, sig)
  101. }
  102. // NewSession opens a new Session for this client. (A session is a remote
  103. // execution of a program.)
  104. func (c *Client) NewSession() (*Session, error) {
  105. ch, in, err := c.OpenChannel("session", nil)
  106. if err != nil {
  107. return nil, err
  108. }
  109. return newSession(ch, in)
  110. }
  111. func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
  112. for r := range incoming {
  113. // This handles keepalive messages and matches
  114. // the behaviour of OpenSSH.
  115. r.Reply(false, nil)
  116. }
  117. }
  118. // handleChannelOpens channel open messages from the remote side.
  119. func (c *Client) handleChannelOpens(in <-chan NewChannel) {
  120. for ch := range in {
  121. c.mu.Lock()
  122. handler := c.channelHandlers[ch.ChannelType()]
  123. c.mu.Unlock()
  124. if handler != nil {
  125. handler <- ch
  126. } else {
  127. ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
  128. }
  129. }
  130. c.mu.Lock()
  131. for _, ch := range c.channelHandlers {
  132. close(ch)
  133. }
  134. c.channelHandlers = nil
  135. c.mu.Unlock()
  136. }
  137. // Dial starts a client connection to the given SSH server. It is a
  138. // convenience function that connects to the given network address,
  139. // initiates the SSH handshake, and then sets up a Client. For access
  140. // to incoming channels and requests, use net.Dial with NewClientConn
  141. // instead.
  142. func Dial(network, addr string, config *ClientConfig) (*Client, error) {
  143. conn, err := net.DialTimeout(network, addr, config.Timeout)
  144. if err != nil {
  145. return nil, err
  146. }
  147. c, chans, reqs, err := NewClientConn(conn, addr, config)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return NewClient(c, chans, reqs), nil
  152. }
  153. // A ClientConfig structure is used to configure a Client. It must not be
  154. // modified after having been passed to an SSH function.
  155. type ClientConfig struct {
  156. // Config contains configuration that is shared between clients and
  157. // servers.
  158. Config
  159. // User contains the username to authenticate as.
  160. User string
  161. // Auth contains possible authentication methods to use with the
  162. // server. Only the first instance of a particular RFC 4252 method will
  163. // be used during authentication.
  164. Auth []AuthMethod
  165. // HostKeyCallback, if not nil, is called during the cryptographic
  166. // handshake to validate the server's host key. A nil HostKeyCallback
  167. // implies that all host keys are accepted.
  168. HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  169. // ClientVersion contains the version identification string that will
  170. // be used for the connection. If empty, a reasonable default is used.
  171. ClientVersion string
  172. // HostKeyAlgorithms lists the key types that the client will
  173. // accept from the server as host key, in order of
  174. // preference. If empty, a reasonable default is used. Any
  175. // string returned from PublicKey.Type method may be used, or
  176. // any of the CertAlgoXxxx and KeyAlgoXxxx constants.
  177. HostKeyAlgorithms []string
  178. // Timeout is the maximum amount of time for the TCP connection to establish.
  179. //
  180. // A Timeout of zero means no timeout.
  181. Timeout time.Duration
  182. }