client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. c.clientVersion = []byte(packageVersion)
  74. if config.ClientVersion != "" {
  75. c.clientVersion = []byte(config.ClientVersion)
  76. }
  77. var err error
  78. c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
  79. if err != nil {
  80. return err
  81. }
  82. c.transport = newClientTransport(
  83. newTransport(c.sshConn.conn, config.Rand, true /* is client */),
  84. c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
  85. if err := c.transport.requestKeyChange(); err != nil {
  86. return err
  87. }
  88. if packet, err := c.transport.readPacket(); err != nil {
  89. return err
  90. } else if packet[0] != msgNewKeys {
  91. return unexpectedMessageError(msgNewKeys, packet[0])
  92. }
  93. return c.clientAuthenticate(config)
  94. }
  95. // verifyHostKeySignature verifies the host key obtained in the key
  96. // exchange.
  97. func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
  98. sig, rest, ok := parseSignatureBody(result.Signature)
  99. if len(rest) > 0 || !ok {
  100. return errors.New("ssh: signature parse error")
  101. }
  102. return hostKey.Verify(result.H, sig)
  103. }
  104. // NewSession opens a new Session for this client. (A session is a remote
  105. // execution of a program.)
  106. func (c *Client) NewSession() (*Session, error) {
  107. ch, in, err := c.OpenChannel("session", nil)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return newSession(ch, in)
  112. }
  113. func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
  114. for r := range incoming {
  115. // This handles keepalive messages and matches
  116. // the behaviour of OpenSSH.
  117. r.Reply(false, nil)
  118. }
  119. }
  120. // handleChannelOpens channel open messages from the remote side.
  121. func (c *Client) handleChannelOpens(in <-chan NewChannel) {
  122. for ch := range in {
  123. c.mu.Lock()
  124. handler := c.channelHandlers[ch.ChannelType()]
  125. c.mu.Unlock()
  126. if handler != nil {
  127. handler <- ch
  128. } else {
  129. ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
  130. }
  131. }
  132. c.mu.Lock()
  133. for _, ch := range c.channelHandlers {
  134. close(ch)
  135. }
  136. c.channelHandlers = nil
  137. c.mu.Unlock()
  138. }
  139. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  140. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  141. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  142. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  143. addr, b, ok := parseString(b)
  144. if !ok {
  145. return nil, b, false
  146. }
  147. port, b, ok := parseUint32(b)
  148. if !ok || port == 0 || port > 65535 {
  149. return nil, b, false
  150. }
  151. ip := net.ParseIP(string(addr))
  152. if ip == nil {
  153. return nil, b, false
  154. }
  155. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  156. }
  157. // Dial starts a client connection to the given SSH server. It is a
  158. // convenience function that connects to the given network address,
  159. // initiates the SSH handshake, and then sets up a Client. For access
  160. // to incoming channels and requests, use net.Dial with NewClientConn
  161. // instead.
  162. func Dial(network, addr string, config *ClientConfig) (*Client, error) {
  163. conn, err := net.Dial(network, addr)
  164. if err != nil {
  165. return nil, err
  166. }
  167. c, chans, reqs, err := NewClientConn(conn, addr, config)
  168. if err != nil {
  169. return nil, err
  170. }
  171. return NewClient(c, chans, reqs), nil
  172. }
  173. // A ClientConfig structure is used to configure a Client. It must not be
  174. // modified after having been passed to an SSH function.
  175. type ClientConfig struct {
  176. // Config contains configuration that is shared between clients and
  177. // servers.
  178. Config
  179. // User contains the username to authenticate as.
  180. User string
  181. // Auth contains possible authentication methods to use with the
  182. // server. Only the first instance of a particular RFC 4252 method will
  183. // be used during authentication.
  184. Auth []AuthMethod
  185. // HostKeyCallback, if not nil, is called during the cryptographic
  186. // handshake to validate the server's host key. A nil HostKeyCallback
  187. // implies that all host keys are accepted.
  188. HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  189. // ClientVersion contains the version identification string that will
  190. // be used for the connection. If empty, a reasonable default is used.
  191. ClientVersion string
  192. }