You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

278 lines
8.4 KiB

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