github.com/inflatablewoman/deis@v1.0.1-0.20141111034523-a4511c46a6ce/deisctl/Godeps/_workspace/src/code.google.com/p/go.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  )
    13  
    14  // Client implements a traditional SSH client that supports shells,
    15  // subprocesses, port forwarding and tunneled dialing.
    16  type Client struct {
    17  	Conn
    18  
    19  	forwards        forwardList // forwarded tcpip connections from the remote side
    20  	mu              sync.Mutex
    21  	channelHandlers map[string]chan NewChannel
    22  }
    23  
    24  // HandleChannelOpen returns a channel on which NewChannel requests
    25  // for the given type are sent. If the type already is being handled,
    26  // nil is returned. The channel is closed when the connection is closed.
    27  func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
    28  	c.mu.Lock()
    29  	defer c.mu.Unlock()
    30  	if c.channelHandlers == nil {
    31  		// The SSH channel has been closed.
    32  		c := make(chan NewChannel)
    33  		close(c)
    34  		return c
    35  	}
    36  
    37  	ch := c.channelHandlers[channelType]
    38  	if ch != nil {
    39  		return nil
    40  	}
    41  
    42  	ch = make(chan NewChannel, 16)
    43  	c.channelHandlers[channelType] = ch
    44  	return ch
    45  }
    46  
    47  // NewClient creates a Client on top of the given connection.
    48  func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
    49  	conn := &Client{
    50  		Conn:            c,
    51  		channelHandlers: make(map[string]chan NewChannel, 1),
    52  	}
    53  
    54  	go conn.handleGlobalRequests(reqs)
    55  	go conn.handleChannelOpens(chans)
    56  	go func() {
    57  		conn.Wait()
    58  		conn.forwards.closeAll()
    59  	}()
    60  	go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip"))
    61  	return conn
    62  }
    63  
    64  // NewClientConn establishes an authenticated SSH connection using c
    65  // as the underlying transport.  The Request and NewChannel channels
    66  // must be serviced or the connection will hang.
    67  func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) {
    68  	fullConf := *config
    69  	fullConf.SetDefaults()
    70  	conn := &connection{
    71  		sshConn: sshConn{conn: c},
    72  	}
    73  
    74  	if err := conn.clientHandshake(addr, &fullConf); err != nil {
    75  		c.Close()
    76  		return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err)
    77  	}
    78  	conn.mux = newMux(conn.transport)
    79  	return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
    80  }
    81  
    82  // clientHandshake performs the client side key exchange. See RFC 4253 Section
    83  // 7.
    84  func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
    85  	c.clientVersion = []byte(packageVersion)
    86  	if config.ClientVersion != "" {
    87  		c.clientVersion = []byte(config.ClientVersion)
    88  	}
    89  
    90  	var err error
    91  	c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
    92  	if err != nil {
    93  		return err
    94  	}
    95  
    96  	c.transport = newClientTransport(
    97  		newTransport(c.sshConn.conn, config.Rand, true /* is client */),
    98  		c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
    99  	if err := c.transport.requestKeyChange(); err != nil {
   100  		return err
   101  	}
   102  
   103  	if packet, err := c.transport.readPacket(); err != nil {
   104  		return err
   105  	} else if packet[0] != msgNewKeys {
   106  		return unexpectedMessageError(msgNewKeys, packet[0])
   107  	}
   108  	return c.clientAuthenticate(config)
   109  }
   110  
   111  // verifyHostKeySignature verifies the host key obtained in the key
   112  // exchange.
   113  func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
   114  	sig, rest, ok := parseSignatureBody(result.Signature)
   115  	if len(rest) > 0 || !ok {
   116  		return errors.New("ssh: signature parse error")
   117  	}
   118  
   119  	return hostKey.Verify(result.H, sig)
   120  }
   121  
   122  // NewSession opens a new Session for this client. (A session is a remote
   123  // execution of a program.)
   124  func (c *Client) NewSession() (*Session, error) {
   125  	ch, in, err := c.OpenChannel("session", nil)
   126  	if err != nil {
   127  		return nil, err
   128  	}
   129  	return newSession(ch, in)
   130  }
   131  
   132  func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
   133  	for r := range incoming {
   134  		// This handles keepalive messages and matches
   135  		// the behaviour of OpenSSH.
   136  		r.Reply(false, nil)
   137  	}
   138  }
   139  
   140  // handleChannelOpens channel open messages from the remote side.
   141  func (c *Client) handleChannelOpens(in <-chan NewChannel) {
   142  	for ch := range in {
   143  		c.mu.Lock()
   144  		handler := c.channelHandlers[ch.ChannelType()]
   145  		c.mu.Unlock()
   146  
   147  		if handler != nil {
   148  			handler <- ch
   149  		} else {
   150  			ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
   151  		}
   152  	}
   153  
   154  	c.mu.Lock()
   155  	for _, ch := range c.channelHandlers {
   156  		close(ch)
   157  	}
   158  	c.channelHandlers = nil
   159  	c.mu.Unlock()
   160  }
   161  
   162  // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
   163  // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
   164  // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
   165  func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
   166  	addr, b, ok := parseString(b)
   167  	if !ok {
   168  		return nil, b, false
   169  	}
   170  	port, b, ok := parseUint32(b)
   171  	if !ok || port == 0 || port > 65535 {
   172  		return nil, b, false
   173  	}
   174  	ip := net.ParseIP(string(addr))
   175  	if ip == nil {
   176  		return nil, b, false
   177  	}
   178  	return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
   179  }
   180  
   181  // Dial starts a client connection to the given SSH server. It is a
   182  // convenience function that connects to the given network address,
   183  // initiates the SSH handshake, and then sets up a Client.  For access
   184  // to incoming channels and requests, use net.Dial with NewClientConn
   185  // instead.
   186  func Dial(network, addr string, config *ClientConfig) (*Client, error) {
   187  	conn, err := net.Dial(network, addr)
   188  	if err != nil {
   189  		return nil, err
   190  	}
   191  	c, chans, reqs, err := NewClientConn(conn, addr, config)
   192  	if err != nil {
   193  		return nil, err
   194  	}
   195  	return NewClient(c, chans, reqs), nil
   196  }
   197  
   198  // A ClientConfig structure is used to configure a Client. It must not be
   199  // modified after having been passed to an SSH function.
   200  type ClientConfig struct {
   201  	// Config contains configuration that is shared between clients and
   202  	// servers.
   203  	Config
   204  
   205  	// User contains the username to authenticate as.
   206  	User string
   207  
   208  	// Auth contains possible authentication methods to use with the
   209  	// server. Only the first instance of a particular RFC 4252 method will
   210  	// be used during authentication.
   211  	Auth []AuthMethod
   212  
   213  	// HostKeyCallback, if not nil, is called during the cryptographic
   214  	// handshake to validate the server's host key. A nil HostKeyCallback
   215  	// implies that all host keys are accepted.
   216  	HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
   217  
   218  	// ClientVersion contains the version identification string that will
   219  	// be used for the connection. If empty, a reasonable default is used.
   220  	ClientVersion string
   221  }