client.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. handleForwardsOnce sync.Once // guards calling (*Client).handleForwards
  19. forwards forwardList // forwarded tcpip connections from the remote side
  20. mu sync.Mutex
  21. channelHandlers map[string]chan NewChannel
  22. }
  23. // HandleChannelOpen returns a channel on which NewChannel requests
  24. // for the given type are sent. If the type already is being handled,
  25. // nil is returned. The channel is closed when the connection is closed.
  26. func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
  27. c.mu.Lock()
  28. defer c.mu.Unlock()
  29. if c.channelHandlers == nil {
  30. // The SSH channel has been closed.
  31. c := make(chan NewChannel)
  32. close(c)
  33. return c
  34. }
  35. ch := c.channelHandlers[channelType]
  36. if ch != nil {
  37. return nil
  38. }
  39. ch = make(chan NewChannel, chanSize)
  40. c.channelHandlers[channelType] = ch
  41. return ch
  42. }
  43. // NewClient creates a Client on top of the given connection.
  44. func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
  45. conn := &Client{
  46. Conn: c,
  47. channelHandlers: make(map[string]chan NewChannel, 1),
  48. }
  49. go conn.handleGlobalRequests(reqs)
  50. go conn.handleChannelOpens(chans)
  51. go func() {
  52. conn.Wait()
  53. conn.forwards.closeAll()
  54. }()
  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, user: fullConf.User},
  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, algo string, 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. // For keys, underlyingAlgo is exactly algo. For certificates,
  107. // we have to look up the underlying key algorithm that SSH
  108. // uses to evaluate signatures.
  109. underlyingAlgo := algo
  110. for sigAlgo, certAlgo := range certAlgoNames {
  111. if certAlgo == algo {
  112. underlyingAlgo = sigAlgo
  113. }
  114. }
  115. if sig.Format != underlyingAlgo {
  116. return fmt.Errorf("ssh: invalid signature algorithm %q, expected %q", sig.Format, underlyingAlgo)
  117. }
  118. return hostKey.Verify(result.H, sig)
  119. }
  120. // NewSession opens a new Session for this client. (A session is a remote
  121. // execution of a program.)
  122. func (c *Client) NewSession() (*Session, error) {
  123. ch, in, err := c.OpenChannel("session", nil)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return newSession(ch, in)
  128. }
  129. func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
  130. for r := range incoming {
  131. // This handles keepalive messages and matches
  132. // the behaviour of OpenSSH.
  133. r.Reply(false, nil)
  134. }
  135. }
  136. // handleChannelOpens channel open messages from the remote side.
  137. func (c *Client) handleChannelOpens(in <-chan NewChannel) {
  138. for ch := range in {
  139. c.mu.Lock()
  140. handler := c.channelHandlers[ch.ChannelType()]
  141. c.mu.Unlock()
  142. if handler != nil {
  143. handler <- ch
  144. } else {
  145. ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
  146. }
  147. }
  148. c.mu.Lock()
  149. for _, ch := range c.channelHandlers {
  150. close(ch)
  151. }
  152. c.channelHandlers = nil
  153. c.mu.Unlock()
  154. }
  155. // Dial starts a client connection to the given SSH server. It is a
  156. // convenience function that connects to the given network address,
  157. // initiates the SSH handshake, and then sets up a Client. For access
  158. // to incoming channels and requests, use net.Dial with NewClientConn
  159. // instead.
  160. func Dial(network, addr string, config *ClientConfig) (*Client, error) {
  161. conn, err := net.DialTimeout(network, addr, config.Timeout)
  162. if err != nil {
  163. return nil, err
  164. }
  165. c, chans, reqs, err := NewClientConn(conn, addr, config)
  166. if err != nil {
  167. return nil, err
  168. }
  169. return NewClient(c, chans, reqs), nil
  170. }
  171. // HostKeyCallback is the function type used for verifying server
  172. // keys. A HostKeyCallback must return nil if the host key is OK, or
  173. // an error to reject it. It receives the hostname as passed to Dial
  174. // or NewClientConn. The remote address is the RemoteAddr of the
  175. // net.Conn underlying the SSH connection.
  176. type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  177. // BannerCallback is the function type used for treat the banner sent by
  178. // the server. A BannerCallback receives the message sent by the remote server.
  179. type BannerCallback func(message string) error
  180. // A ClientConfig structure is used to configure a Client. It must not be
  181. // modified after having been passed to an SSH function.
  182. type ClientConfig struct {
  183. // Config contains configuration that is shared between clients and
  184. // servers.
  185. Config
  186. // User contains the username to authenticate as.
  187. User string
  188. // Auth contains possible authentication methods to use with the
  189. // server. Only the first instance of a particular RFC 4252 method will
  190. // be used during authentication.
  191. Auth []AuthMethod
  192. // HostKeyCallback is called during the cryptographic
  193. // handshake to validate the server's host key. The client
  194. // configuration must supply this callback for the connection
  195. // to succeed. The functions InsecureIgnoreHostKey or
  196. // FixedHostKey can be used for simplistic host key checks.
  197. HostKeyCallback HostKeyCallback
  198. // BannerCallback is called during the SSH dance to display a custom
  199. // server's message. The client configuration can supply this callback to
  200. // handle it as wished. The function BannerDisplayStderr can be used for
  201. // simplistic display on Stderr.
  202. BannerCallback BannerCallback
  203. // ClientVersion contains the version identification string that will
  204. // be used for the connection. If empty, a reasonable default is used.
  205. ClientVersion string
  206. // HostKeyAlgorithms lists the key types that the client will
  207. // accept from the server as host key, in order of
  208. // preference. If empty, a reasonable default is used. Any
  209. // string returned from PublicKey.Type method may be used, or
  210. // any of the CertAlgoXxxx and KeyAlgoXxxx constants.
  211. HostKeyAlgorithms []string
  212. // Timeout is the maximum amount of time for the TCP connection to establish.
  213. //
  214. // A Timeout of zero means no timeout.
  215. Timeout time.Duration
  216. }
  217. // InsecureIgnoreHostKey returns a function that can be used for
  218. // ClientConfig.HostKeyCallback to accept any host key. It should
  219. // not be used for production code.
  220. func InsecureIgnoreHostKey() HostKeyCallback {
  221. return func(hostname string, remote net.Addr, key PublicKey) error {
  222. return nil
  223. }
  224. }
  225. type fixedHostKey struct {
  226. key PublicKey
  227. }
  228. func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error {
  229. if f.key == nil {
  230. return fmt.Errorf("ssh: required host key was nil")
  231. }
  232. if !bytes.Equal(key.Marshal(), f.key.Marshal()) {
  233. return fmt.Errorf("ssh: host key mismatch")
  234. }
  235. return nil
  236. }
  237. // FixedHostKey returns a function for use in
  238. // ClientConfig.HostKeyCallback to accept only a specific host key.
  239. func FixedHostKey(key PublicKey) HostKeyCallback {
  240. hk := &fixedHostKey{key}
  241. return hk.check
  242. }
  243. // BannerDisplayStderr returns a function that can be used for
  244. // ClientConfig.BannerCallback to display banners on os.Stderr.
  245. func BannerDisplayStderr() BannerCallback {
  246. return func(banner string) error {
  247. _, err := os.Stderr.WriteString(banner)
  248. return err
  249. }
  250. }