client.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. return c.clientAuthenticate(config)
  95. }
  96. // verifyHostKeySignature verifies the host key obtained in the key
  97. // exchange.
  98. func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
  99. sig, rest, ok := parseSignatureBody(result.Signature)
  100. if len(rest) > 0 || !ok {
  101. return errors.New("ssh: signature parse error")
  102. }
  103. return hostKey.Verify(result.H, sig)
  104. }
  105. // NewSession opens a new Session for this client. (A session is a remote
  106. // execution of a program.)
  107. func (c *Client) NewSession() (*Session, error) {
  108. ch, in, err := c.OpenChannel("session", nil)
  109. if err != nil {
  110. return nil, err
  111. }
  112. return newSession(ch, in)
  113. }
  114. func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
  115. for r := range incoming {
  116. // This handles keepalive messages and matches
  117. // the behaviour of OpenSSH.
  118. r.Reply(false, nil)
  119. }
  120. }
  121. // handleChannelOpens channel open messages from the remote side.
  122. func (c *Client) handleChannelOpens(in <-chan NewChannel) {
  123. for ch := range in {
  124. c.mu.Lock()
  125. handler := c.channelHandlers[ch.ChannelType()]
  126. c.mu.Unlock()
  127. if handler != nil {
  128. handler <- ch
  129. } else {
  130. ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
  131. }
  132. }
  133. c.mu.Lock()
  134. for _, ch := range c.channelHandlers {
  135. close(ch)
  136. }
  137. c.channelHandlers = nil
  138. c.mu.Unlock()
  139. }
  140. // Dial starts a client connection to the given SSH server. It is a
  141. // convenience function that connects to the given network address,
  142. // initiates the SSH handshake, and then sets up a Client. For access
  143. // to incoming channels and requests, use net.Dial with NewClientConn
  144. // instead.
  145. func Dial(network, addr string, config *ClientConfig) (*Client, error) {
  146. conn, err := net.Dial(network, addr)
  147. if err != nil {
  148. return nil, err
  149. }
  150. c, chans, reqs, err := NewClientConn(conn, addr, config)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return NewClient(c, chans, reqs), nil
  155. }
  156. // A ClientConfig structure is used to configure a Client. It must not be
  157. // modified after having been passed to an SSH function.
  158. type ClientConfig struct {
  159. // Config contains configuration that is shared between clients and
  160. // servers.
  161. Config
  162. // User contains the username to authenticate as.
  163. User string
  164. // Auth contains possible authentication methods to use with the
  165. // server. Only the first instance of a particular RFC 4252 method will
  166. // be used during authentication.
  167. Auth []AuthMethod
  168. // HostKeyCallback, if not nil, is called during the cryptographic
  169. // handshake to validate the server's host key. A nil HostKeyCallback
  170. // implies that all host keys are accepted.
  171. HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  172. // ClientVersion contains the version identification string that will
  173. // be used for the connection. If empty, a reasonable default is used.
  174. ClientVersion string
  175. }