github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/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  )
    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  	if config.ClientVersion != "" {
    86  		c.clientVersion = []byte(config.ClientVersion)
    87  	} else {
    88  		c.clientVersion = []byte(packageVersion)
    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  
   109  	// We just did the key change, so the session ID is established.
   110  	c.sessionID = c.transport.getSessionID()
   111  
   112  	return c.clientAuthenticate(config)
   113  }
   114  
   115  // verifyHostKeySignature verifies the host key obtained in the key
   116  // exchange.
   117  func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
   118  	sig, rest, ok := parseSignatureBody(result.Signature)
   119  	if len(rest) > 0 || !ok {
   120  		return errors.New("ssh: signature parse error")
   121  	}
   122  
   123  	return hostKey.Verify(result.H, sig)
   124  }
   125  
   126  // NewSession opens a new Session for this client. (A session is a remote
   127  // execution of a program.)
   128  func (c *Client) NewSession() (*Session, error) {
   129  	ch, in, err := c.OpenChannel("session", nil)
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  	return newSession(ch, in)
   134  }
   135  
   136  func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
   137  	for r := range incoming {
   138  		// This handles keepalive messages and matches
   139  		// the behaviour of OpenSSH.
   140  		r.Reply(false, nil)
   141  	}
   142  }
   143  
   144  // handleChannelOpens channel open messages from the remote side.
   145  func (c *Client) handleChannelOpens(in <-chan NewChannel) {
   146  	for ch := range in {
   147  		c.mu.Lock()
   148  		handler := c.channelHandlers[ch.ChannelType()]
   149  		c.mu.Unlock()
   150  
   151  		if handler != nil {
   152  			handler <- ch
   153  		} else {
   154  			ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
   155  		}
   156  	}
   157  
   158  	c.mu.Lock()
   159  	for _, ch := range c.channelHandlers {
   160  		close(ch)
   161  	}
   162  	c.channelHandlers = nil
   163  	c.mu.Unlock()
   164  }
   165  
   166  // Dial starts a client connection to the given SSH server. It is a
   167  // convenience function that connects to the given network address,
   168  // initiates the SSH handshake, and then sets up a Client.  For access
   169  // to incoming channels and requests, use net.Dial with NewClientConn
   170  // instead.
   171  func Dial(network, addr string, config *ClientConfig) (*Client, error) {
   172  	conn, err := net.Dial(network, addr)
   173  	if err != nil {
   174  		return nil, err
   175  	}
   176  	c, chans, reqs, err := NewClientConn(conn, addr, config)
   177  	if err != nil {
   178  		return nil, err
   179  	}
   180  	return NewClient(c, chans, reqs), nil
   181  }
   182  
   183  // A ClientConfig structure is used to configure a Client. It must not be
   184  // modified after having been passed to an SSH function.
   185  type ClientConfig struct {
   186  	// Config contains configuration that is shared between clients and
   187  	// servers.
   188  	Config
   189  
   190  	// User contains the username to authenticate as.
   191  	User string
   192  
   193  	// Auth contains possible authentication methods to use with the
   194  	// server. Only the first instance of a particular RFC 4252 method will
   195  	// be used during authentication.
   196  	Auth []AuthMethod
   197  
   198  	// HostKeyCallback, if not nil, is called during the cryptographic
   199  	// handshake to validate the server's host key. A nil HostKeyCallback
   200  	// implies that all host keys are accepted.
   201  	HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
   202  
   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  }