github.com/maenmax/kairep@v0.0.0-20210218001208-55bf3df36788/src/golang.org/x/crypto/ssh/client.go (about)

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