PageRenderTime 43ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/golang.org/x/crypto/ssh/client.go

https://gitlab.com/veterinabb/webedit
Go | 219 lines | 139 code | 31 blank | 49 comment | 37 complexity | 5337b5189a4933be9757ae69366c8814 MD5 | raw file
  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. "time"
  11. )
  12. // Client implements a traditional SSH client that supports shells,
  13. // subprocesses, port forwarding and tunneled dialing.
  14. type Client struct {
  15. Conn
  16. forwards forwardList // forwarded tcpip connections from the remote side
  17. mu sync.Mutex
  18. channelHandlers map[string]chan NewChannel
  19. }
  20. // HandleChannelOpen returns a channel on which NewChannel requests
  21. // for the given type are sent. If the type already is being handled,
  22. // nil is returned. The channel is closed when the connection is closed.
  23. func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
  24. c.mu.Lock()
  25. defer c.mu.Unlock()
  26. if c.channelHandlers == nil {
  27. // The SSH channel has been closed.
  28. c := make(chan NewChannel)
  29. close(c)
  30. return c
  31. }
  32. ch := c.channelHandlers[channelType]
  33. if ch != nil {
  34. return nil
  35. }
  36. ch = make(chan NewChannel, 16)
  37. c.channelHandlers[channelType] = ch
  38. return ch
  39. }
  40. // NewClient creates a Client on top of the given connection.
  41. func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
  42. conn := &Client{
  43. Conn: c,
  44. channelHandlers: make(map[string]chan NewChannel, 1),
  45. }
  46. go conn.handleGlobalRequests(reqs)
  47. go conn.handleChannelOpens(chans)
  48. go func() {
  49. conn.Wait()
  50. conn.forwards.closeAll()
  51. }()
  52. go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip"))
  53. return conn
  54. }
  55. // NewClientConn establishes an authenticated SSH connection using c
  56. // as the underlying transport. The Request and NewChannel channels
  57. // must be serviced or the connection will hang.
  58. func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) {
  59. fullConf := *config
  60. fullConf.SetDefaults()
  61. conn := &connection{
  62. sshConn: sshConn{conn: c},
  63. }
  64. if err := conn.clientHandshake(addr, &fullConf); err != nil {
  65. c.Close()
  66. return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err)
  67. }
  68. conn.mux = newMux(conn.transport)
  69. return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
  70. }
  71. // clientHandshake performs the client side key exchange. See RFC 4253 Section
  72. // 7.
  73. func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
  74. if config.ClientVersion != "" {
  75. c.clientVersion = []byte(config.ClientVersion)
  76. } else {
  77. c.clientVersion = []byte(packageVersion)
  78. }
  79. var err error
  80. c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
  81. if err != nil {
  82. return err
  83. }
  84. c.transport = newClientTransport(
  85. newTransport(c.sshConn.conn, config.Rand, true /* is client */),
  86. c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
  87. if err := c.transport.requestInitialKeyChange(); err != nil {
  88. return err
  89. }
  90. if packet, err := c.transport.readPacket(); err != nil {
  91. return err
  92. } else if packet[0] != msgNewKeys {
  93. return unexpectedMessageError(msgNewKeys, packet[0])
  94. }
  95. // We just did the key change, so the session ID is established.
  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. // A ClientConfig structure is used to configure a Client. It must not be
  160. // modified after having been passed to an SSH function.
  161. type ClientConfig struct {
  162. // Config contains configuration that is shared between clients and
  163. // servers.
  164. Config
  165. // User contains the username to authenticate as.
  166. User string
  167. // Auth contains possible authentication methods to use with the
  168. // server. Only the first instance of a particular RFC 4252 method will
  169. // be used during authentication.
  170. Auth []AuthMethod
  171. // HostKeyCallback, if not nil, is called during the cryptographic
  172. // handshake to validate the server's host key. A nil HostKeyCallback
  173. // implies that all host keys are accepted.
  174. HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  175. // ClientVersion contains the version identification string that will
  176. // be used for the connection. If empty, a reasonable default is used.
  177. ClientVersion string
  178. // HostKeyAlgorithms lists the key types that the client will
  179. // accept from the server as host key, in order of
  180. // preference. If empty, a reasonable default is used. Any
  181. // string returned from PublicKey.Type method may be used, or
  182. // any of the CertAlgoXxxx and KeyAlgoXxxx constants.
  183. HostKeyAlgorithms []string
  184. // Timeout is the maximum amount of time for the TCP connection to establish.
  185. //
  186. // A Timeout of zero means no timeout.
  187. Timeout time.Duration
  188. }