client.go 6.2 KB

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