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 5package ssh 6 7import ( 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. 19type 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. 32func (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. 53func 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. 71func 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}, 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. 93func (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. 118func verifyHostKeySignature(hostKey PublicKey, 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 return hostKey.Verify(result.H, sig) 125} 126 127// NewSession opens a new Session for this client. (A session is a remote 128// execution of a program.) 129func (c *Client) NewSession() (*Session, error) { 130 ch, in, err := c.OpenChannel("session", nil) 131 if err != nil { 132 return nil, err 133 } 134 return newSession(ch, in) 135} 136 137func (c *Client) handleGlobalRequests(incoming <-chan *Request) { 138 for r := range incoming { 139 // This handles keepalive messages and matches 140 // the behaviour of OpenSSH. 141 r.Reply(false, nil) 142 } 143} 144 145// handleChannelOpens channel open messages from the remote side. 146func (c *Client) handleChannelOpens(in <-chan NewChannel) { 147 for ch := range in { 148 c.mu.Lock() 149 handler := c.channelHandlers[ch.ChannelType()] 150 c.mu.Unlock() 151 152 if handler != nil { 153 handler <- ch 154 } else { 155 ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType())) 156 } 157 } 158 159 c.mu.Lock() 160 for _, ch := range c.channelHandlers { 161 close(ch) 162 } 163 c.channelHandlers = nil 164 c.mu.Unlock() 165} 166 167// Dial starts a client connection to the given SSH server. It is a 168// convenience function that connects to the given network address, 169// initiates the SSH handshake, and then sets up a Client. For access 170// to incoming channels and requests, use net.Dial with NewClientConn 171// instead. 172func Dial(network, addr string, config *ClientConfig) (*Client, error) { 173 conn, err := net.DialTimeout(network, addr, config.Timeout) 174 if err != nil { 175 return nil, err 176 } 177 c, chans, reqs, err := NewClientConn(conn, addr, config) 178 if err != nil { 179 return nil, err 180 } 181 return NewClient(c, chans, reqs), nil 182} 183 184// HostKeyCallback is the function type used for verifying server 185// keys. A HostKeyCallback must return nil if the host key is OK, or 186// an error to reject it. It receives the hostname as passed to Dial 187// or NewClientConn. The remote address is the RemoteAddr of the 188// net.Conn underlying the SSH connection. 189type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error 190 191// BannerCallback is the function type used for treat the banner sent by 192// the server. A BannerCallback receives the message sent by the remote server. 193type BannerCallback func(message string) error 194 195// A ClientConfig structure is used to configure a Client. It must not be 196// modified after having been passed to an SSH function. 197type ClientConfig struct { 198 // Config contains configuration that is shared between clients and 199 // servers. 200 Config 201 202 // User contains the username to authenticate as. 203 User string 204 205 // Auth contains possible authentication methods to use with the 206 // server. Only the first instance of a particular RFC 4252 method will 207 // be used during authentication. 208 Auth []AuthMethod 209 210 // HostKeyCallback is called during the cryptographic 211 // handshake to validate the server's host key. The client 212 // configuration must supply this callback for the connection 213 // to succeed. The functions InsecureIgnoreHostKey or 214 // FixedHostKey can be used for simplistic host key checks. 215 HostKeyCallback HostKeyCallback 216 217 // BannerCallback is called during the SSH dance to display a custom 218 // server's message. The client configuration can supply this callback to 219 // handle it as wished. The function BannerDisplayStderr can be used for 220 // simplistic display on Stderr. 221 BannerCallback BannerCallback 222 223 // ClientVersion contains the version identification string that will 224 // be used for the connection. If empty, a reasonable default is used. 225 ClientVersion string 226 227 // HostKeyAlgorithms lists the key types that the client will 228 // accept from the server as host key, in order of 229 // preference. If empty, a reasonable default is used. Any 230 // string returned from PublicKey.Type method may be used, or 231 // any of the CertAlgoXxxx and KeyAlgoXxxx constants. 232 HostKeyAlgorithms []string 233 234 // Timeout is the maximum amount of time for the TCP connection to establish. 235 // 236 // A Timeout of zero means no timeout. 237 Timeout time.Duration 238} 239 240// InsecureIgnoreHostKey returns a function that can be used for 241// ClientConfig.HostKeyCallback to accept any host key. It should 242// not be used for production code. 243func InsecureIgnoreHostKey() HostKeyCallback { 244 return func(hostname string, remote net.Addr, key PublicKey) error { 245 return nil 246 } 247} 248 249type fixedHostKey struct { 250 key PublicKey 251} 252 253func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error { 254 if f.key == nil { 255 return fmt.Errorf("ssh: required host key was nil") 256 } 257 if !bytes.Equal(key.Marshal(), f.key.Marshal()) { 258 return fmt.Errorf("ssh: host key mismatch") 259 } 260 return nil 261} 262 263// FixedHostKey returns a function for use in 264// ClientConfig.HostKeyCallback to accept only a specific host key. 265func FixedHostKey(key PublicKey) HostKeyCallback { 266 hk := &fixedHostKey{key} 267 return hk.check 268} 269 270// BannerDisplayStderr returns a function that can be used for 271// ClientConfig.BannerCallback to display banners on os.Stderr. 272func BannerDisplayStderr() BannerCallback { 273 return func(banner string) error { 274 _, err := os.Stderr.WriteString(banner) 275 276 return err 277 } 278} 279