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