client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. package ssh
  5. import (
  6. "crypto/rand"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "sync"
  13. )
  14. // ClientConn represents the client side of an SSH connection.
  15. type ClientConn struct {
  16. transport *transport
  17. config *ClientConfig
  18. chanList // channels associated with this connection
  19. forwardList // forwarded tcpip connections from the remote side
  20. globalRequest
  21. // Address as passed to the Dial function.
  22. dialAddress string
  23. serverVersion string
  24. }
  25. type globalRequest struct {
  26. sync.Mutex
  27. response chan interface{}
  28. }
  29. // Client returns a new SSH client connection using c as the underlying transport.
  30. func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) {
  31. return clientWithAddress(c, "", config)
  32. }
  33. func clientWithAddress(c net.Conn, addr string, config *ClientConfig) (*ClientConn, error) {
  34. conn := &ClientConn{
  35. transport: newTransport(c, config.rand(), true /* is client */),
  36. config: config,
  37. globalRequest: globalRequest{response: make(chan interface{}, 1)},
  38. dialAddress: addr,
  39. }
  40. if err := conn.handshake(); err != nil {
  41. conn.transport.Close()
  42. return nil, fmt.Errorf("handshake failed: %v", err)
  43. }
  44. go conn.mainLoop()
  45. return conn, nil
  46. }
  47. // Close closes the connection.
  48. func (c *ClientConn) Close() error { return c.transport.Close() }
  49. // LocalAddr returns the local network address.
  50. func (c *ClientConn) LocalAddr() net.Addr { return c.transport.LocalAddr() }
  51. // RemoteAddr returns the remote network address.
  52. func (c *ClientConn) RemoteAddr() net.Addr { return c.transport.RemoteAddr() }
  53. // handshake performs the client side key exchange. See RFC 4253 Section 7.
  54. func (c *ClientConn) handshake() error {
  55. clientVersion := []byte(packageVersion)
  56. if c.config.ClientVersion != "" {
  57. clientVersion = []byte(c.config.ClientVersion)
  58. }
  59. serverVersion, err := exchangeVersions(c.transport.Conn, clientVersion)
  60. if err != nil {
  61. return err
  62. }
  63. c.serverVersion = string(serverVersion)
  64. clientKexInit := kexInitMsg{
  65. KexAlgos: c.config.Crypto.kexes(),
  66. ServerHostKeyAlgos: supportedHostKeyAlgos,
  67. CiphersClientServer: c.config.Crypto.ciphers(),
  68. CiphersServerClient: c.config.Crypto.ciphers(),
  69. MACsClientServer: c.config.Crypto.macs(),
  70. MACsServerClient: c.config.Crypto.macs(),
  71. CompressionClientServer: supportedCompressions,
  72. CompressionServerClient: supportedCompressions,
  73. }
  74. kexInitPacket := marshal(msgKexInit, clientKexInit)
  75. if err := c.transport.writePacket(kexInitPacket); err != nil {
  76. return err
  77. }
  78. packet, err := c.transport.readPacket()
  79. if err != nil {
  80. return err
  81. }
  82. var serverKexInit kexInitMsg
  83. if err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {
  84. return err
  85. }
  86. algs := findAgreedAlgorithms(&clientKexInit, &serverKexInit)
  87. if algs == nil {
  88. return errors.New("ssh: no common algorithms")
  89. }
  90. if serverKexInit.FirstKexFollows && algs.kex != serverKexInit.KexAlgos[0] {
  91. // The server sent a Kex message for the wrong algorithm,
  92. // which we have to ignore.
  93. if _, err := c.transport.readPacket(); err != nil {
  94. return err
  95. }
  96. }
  97. kex, ok := kexAlgoMap[algs.kex]
  98. if !ok {
  99. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
  100. }
  101. magics := handshakeMagics{
  102. clientVersion: clientVersion,
  103. serverVersion: serverVersion,
  104. clientKexInit: kexInitPacket,
  105. serverKexInit: packet,
  106. }
  107. result, err := kex.Client(c.transport, c.config.rand(), &magics)
  108. if err != nil {
  109. return err
  110. }
  111. err = verifyHostKeySignature(algs.hostKey, result.HostKey, result.H, result.Signature)
  112. if err != nil {
  113. return err
  114. }
  115. if checker := c.config.HostKeyChecker; checker != nil {
  116. err = checker.Check(c.dialAddress, c.transport.RemoteAddr(), algs.hostKey, result.HostKey)
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. c.transport.prepareKeyChange(algs, result)
  122. if err = c.transport.writePacket([]byte{msgNewKeys}); err != nil {
  123. return err
  124. }
  125. if packet, err = c.transport.readPacket(); err != nil {
  126. return err
  127. }
  128. if packet[0] != msgNewKeys {
  129. return UnexpectedMessageError{msgNewKeys, packet[0]}
  130. }
  131. return c.authenticate()
  132. }
  133. // Verify the host key obtained in the key exchange.
  134. func verifyHostKeySignature(hostKeyAlgo string, hostKeyBytes []byte, data []byte, signature []byte) error {
  135. hostKey, rest, ok := ParsePublicKey(hostKeyBytes)
  136. if len(rest) > 0 || !ok {
  137. return errors.New("ssh: could not parse hostkey")
  138. }
  139. sig, rest, ok := parseSignatureBody(signature)
  140. if len(rest) > 0 || !ok {
  141. return errors.New("ssh: signature parse error")
  142. }
  143. if sig.Format != hostKeyAlgo {
  144. return fmt.Errorf("ssh: unexpected signature type %q", sig.Format)
  145. }
  146. if !hostKey.Verify(data, sig.Blob) {
  147. return errors.New("ssh: host key signature error")
  148. }
  149. return nil
  150. }
  151. // mainLoop reads incoming messages and routes channel messages
  152. // to their respective ClientChans.
  153. func (c *ClientConn) mainLoop() {
  154. defer func() {
  155. c.transport.Close()
  156. c.chanList.closeAll()
  157. c.forwardList.closeAll()
  158. }()
  159. for {
  160. packet, err := c.transport.readPacket()
  161. if err != nil {
  162. break
  163. }
  164. // TODO(dfc) A note on blocking channel use.
  165. // The msg, data and dataExt channels of a clientChan can
  166. // cause this loop to block indefinitely if the consumer does
  167. // not service them.
  168. switch packet[0] {
  169. case msgChannelData:
  170. if len(packet) < 9 {
  171. // malformed data packet
  172. return
  173. }
  174. remoteId := binary.BigEndian.Uint32(packet[1:5])
  175. length := binary.BigEndian.Uint32(packet[5:9])
  176. packet = packet[9:]
  177. if length != uint32(len(packet)) {
  178. return
  179. }
  180. ch, ok := c.getChan(remoteId)
  181. if !ok {
  182. return
  183. }
  184. ch.stdout.write(packet)
  185. case msgChannelExtendedData:
  186. if len(packet) < 13 {
  187. // malformed data packet
  188. return
  189. }
  190. remoteId := binary.BigEndian.Uint32(packet[1:5])
  191. datatype := binary.BigEndian.Uint32(packet[5:9])
  192. length := binary.BigEndian.Uint32(packet[9:13])
  193. packet = packet[13:]
  194. if length != uint32(len(packet)) {
  195. return
  196. }
  197. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  198. // for stderr on interactive sessions. Other data types are
  199. // silently discarded.
  200. if datatype == 1 {
  201. ch, ok := c.getChan(remoteId)
  202. if !ok {
  203. return
  204. }
  205. ch.stderr.write(packet)
  206. }
  207. default:
  208. decoded, err := decode(packet)
  209. if err != nil {
  210. if _, ok := err.(UnexpectedMessageError); ok {
  211. fmt.Printf("mainLoop: unexpected message: %v\n", err)
  212. continue
  213. }
  214. return
  215. }
  216. switch msg := decoded.(type) {
  217. case *channelOpenMsg:
  218. c.handleChanOpen(msg)
  219. case *channelOpenConfirmMsg:
  220. ch, ok := c.getChan(msg.PeersId)
  221. if !ok {
  222. return
  223. }
  224. ch.msg <- msg
  225. case *channelOpenFailureMsg:
  226. ch, ok := c.getChan(msg.PeersId)
  227. if !ok {
  228. return
  229. }
  230. ch.msg <- msg
  231. case *channelCloseMsg:
  232. ch, ok := c.getChan(msg.PeersId)
  233. if !ok {
  234. return
  235. }
  236. ch.Close()
  237. close(ch.msg)
  238. c.chanList.remove(msg.PeersId)
  239. case *channelEOFMsg:
  240. ch, ok := c.getChan(msg.PeersId)
  241. if !ok {
  242. return
  243. }
  244. ch.stdout.eof()
  245. // RFC 4254 is mute on how EOF affects dataExt messages but
  246. // it is logical to signal EOF at the same time.
  247. ch.stderr.eof()
  248. case *channelRequestSuccessMsg:
  249. ch, ok := c.getChan(msg.PeersId)
  250. if !ok {
  251. return
  252. }
  253. ch.msg <- msg
  254. case *channelRequestFailureMsg:
  255. ch, ok := c.getChan(msg.PeersId)
  256. if !ok {
  257. return
  258. }
  259. ch.msg <- msg
  260. case *channelRequestMsg:
  261. ch, ok := c.getChan(msg.PeersId)
  262. if !ok {
  263. return
  264. }
  265. ch.msg <- msg
  266. case *windowAdjustMsg:
  267. ch, ok := c.getChan(msg.PeersId)
  268. if !ok {
  269. return
  270. }
  271. if !ch.remoteWin.add(msg.AdditionalBytes) {
  272. // invalid window update
  273. return
  274. }
  275. case *globalRequestMsg:
  276. // This handles keepalive messages and matches
  277. // the behaviour of OpenSSH.
  278. if msg.WantReply {
  279. c.transport.writePacket(marshal(msgRequestFailure, globalRequestFailureMsg{}))
  280. }
  281. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  282. c.globalRequest.response <- msg
  283. case *disconnectMsg:
  284. return
  285. default:
  286. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  287. }
  288. }
  289. }
  290. }
  291. // Handle channel open messages from the remote side.
  292. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  293. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  294. c.sendConnectionFailed(msg.PeersId)
  295. }
  296. switch msg.ChanType {
  297. case "forwarded-tcpip":
  298. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  299. if !ok {
  300. // invalid request
  301. c.sendConnectionFailed(msg.PeersId)
  302. return
  303. }
  304. l, ok := c.forwardList.lookup(*laddr)
  305. if !ok {
  306. // TODO: print on a more structured log.
  307. fmt.Println("could not find forward list entry for", laddr)
  308. // Section 7.2, implementations MUST reject spurious incoming
  309. // connections.
  310. c.sendConnectionFailed(msg.PeersId)
  311. return
  312. }
  313. raddr, rest, ok := parseTCPAddr(rest)
  314. if !ok {
  315. // invalid request
  316. c.sendConnectionFailed(msg.PeersId)
  317. return
  318. }
  319. ch := c.newChan(c.transport)
  320. ch.remoteId = msg.PeersId
  321. ch.remoteWin.add(msg.PeersWindow)
  322. ch.maxPacket = msg.MaxPacketSize
  323. m := channelOpenConfirmMsg{
  324. PeersId: ch.remoteId,
  325. MyId: ch.localId,
  326. MyWindow: channelWindowSize,
  327. MaxPacketSize: channelMaxPacketSize,
  328. }
  329. c.transport.writePacket(marshal(msgChannelOpenConfirm, m))
  330. l <- forward{ch, raddr}
  331. default:
  332. // unknown channel type
  333. m := channelOpenFailureMsg{
  334. PeersId: msg.PeersId,
  335. Reason: UnknownChannelType,
  336. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  337. Language: "en_US.UTF-8",
  338. }
  339. c.transport.writePacket(marshal(msgChannelOpenFailure, m))
  340. }
  341. }
  342. // sendGlobalRequest sends a global request message as specified
  343. // in RFC4254 section 4. To correctly synchronise messages, a lock
  344. // is held internally until a response is returned.
  345. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  346. c.globalRequest.Lock()
  347. defer c.globalRequest.Unlock()
  348. if err := c.transport.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  349. return nil, err
  350. }
  351. r := <-c.globalRequest.response
  352. if r, ok := r.(*globalRequestSuccessMsg); ok {
  353. return r, nil
  354. }
  355. return nil, errors.New("request failed")
  356. }
  357. // sendConnectionFailed rejects an incoming channel identified
  358. // by remoteId.
  359. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  360. m := channelOpenFailureMsg{
  361. PeersId: remoteId,
  362. Reason: ConnectionFailed,
  363. Message: "invalid request",
  364. Language: "en_US.UTF-8",
  365. }
  366. return c.transport.writePacket(marshal(msgChannelOpenFailure, m))
  367. }
  368. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  369. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  370. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  371. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  372. addr, b, ok := parseString(b)
  373. if !ok {
  374. return nil, b, false
  375. }
  376. port, b, ok := parseUint32(b)
  377. if !ok {
  378. return nil, b, false
  379. }
  380. ip := net.ParseIP(string(addr))
  381. if ip == nil {
  382. return nil, b, false
  383. }
  384. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  385. }
  386. // Dial connects to the given network address using net.Dial and
  387. // then initiates a SSH handshake, returning the resulting client connection.
  388. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  389. conn, err := net.Dial(network, addr)
  390. if err != nil {
  391. return nil, err
  392. }
  393. return clientWithAddress(conn, addr, config)
  394. }
  395. // A ClientConfig structure is used to configure a ClientConn. After one has
  396. // been passed to an SSH function it must not be modified.
  397. type ClientConfig struct {
  398. // Rand provides the source of entropy for key exchange. If Rand is
  399. // nil, the cryptographic random reader in package crypto/rand will
  400. // be used.
  401. Rand io.Reader
  402. // The username to authenticate.
  403. User string
  404. // A slice of ClientAuth methods. Only the first instance
  405. // of a particular RFC 4252 method will be used during authentication.
  406. Auth []ClientAuth
  407. // HostKeyChecker, if not nil, is called during the cryptographic
  408. // handshake to validate the server's host key. A nil HostKeyChecker
  409. // implies that all host keys are accepted.
  410. HostKeyChecker HostKeyChecker
  411. // Cryptographic-related configuration.
  412. Crypto CryptoConfig
  413. // The identification string that will be used for the connection.
  414. // If empty, a reasonable default is used.
  415. ClientVersion string
  416. }
  417. func (c *ClientConfig) rand() io.Reader {
  418. if c.Rand == nil {
  419. return rand.Reader
  420. }
  421. return c.Rand
  422. }
  423. // Thread safe channel list.
  424. type chanList struct {
  425. // protects concurrent access to chans
  426. sync.Mutex
  427. // chans are indexed by the local id of the channel, clientChan.localId.
  428. // The PeersId value of messages received by ClientConn.mainLoop is
  429. // used to locate the right local clientChan in this slice.
  430. chans []*clientChan
  431. }
  432. // Allocate a new ClientChan with the next avail local id.
  433. func (c *chanList) newChan(p packetConn) *clientChan {
  434. c.Lock()
  435. defer c.Unlock()
  436. for i := range c.chans {
  437. if c.chans[i] == nil {
  438. ch := newClientChan(p, uint32(i))
  439. c.chans[i] = ch
  440. return ch
  441. }
  442. }
  443. i := len(c.chans)
  444. ch := newClientChan(p, uint32(i))
  445. c.chans = append(c.chans, ch)
  446. return ch
  447. }
  448. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  449. c.Lock()
  450. defer c.Unlock()
  451. if id >= uint32(len(c.chans)) {
  452. return nil, false
  453. }
  454. return c.chans[id], true
  455. }
  456. func (c *chanList) remove(id uint32) {
  457. c.Lock()
  458. defer c.Unlock()
  459. c.chans[id] = nil
  460. }
  461. func (c *chanList) closeAll() {
  462. c.Lock()
  463. defer c.Unlock()
  464. for _, ch := range c.chans {
  465. if ch == nil {
  466. continue
  467. }
  468. ch.Close()
  469. close(ch.msg)
  470. }
  471. }