1
0

client.go 7.7 KB

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