client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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: 1 << 14,
  327. // As per RFC 4253 6.1, 32k is also the minimum.
  328. MaxPacketSize: 1 << 15,
  329. }
  330. c.transport.writePacket(marshal(msgChannelOpenConfirm, m))
  331. l <- forward{ch, raddr}
  332. default:
  333. // unknown channel type
  334. m := channelOpenFailureMsg{
  335. PeersId: msg.PeersId,
  336. Reason: UnknownChannelType,
  337. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  338. Language: "en_US.UTF-8",
  339. }
  340. c.transport.writePacket(marshal(msgChannelOpenFailure, m))
  341. }
  342. }
  343. // sendGlobalRequest sends a global request message as specified
  344. // in RFC4254 section 4. To correctly synchronise messages, a lock
  345. // is held internally until a response is returned.
  346. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  347. c.globalRequest.Lock()
  348. defer c.globalRequest.Unlock()
  349. if err := c.transport.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  350. return nil, err
  351. }
  352. r := <-c.globalRequest.response
  353. if r, ok := r.(*globalRequestSuccessMsg); ok {
  354. return r, nil
  355. }
  356. return nil, errors.New("request failed")
  357. }
  358. // sendConnectionFailed rejects an incoming channel identified
  359. // by remoteId.
  360. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  361. m := channelOpenFailureMsg{
  362. PeersId: remoteId,
  363. Reason: ConnectionFailed,
  364. Message: "invalid request",
  365. Language: "en_US.UTF-8",
  366. }
  367. return c.transport.writePacket(marshal(msgChannelOpenFailure, m))
  368. }
  369. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  370. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  371. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  372. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  373. addr, b, ok := parseString(b)
  374. if !ok {
  375. return nil, b, false
  376. }
  377. port, b, ok := parseUint32(b)
  378. if !ok {
  379. return nil, b, false
  380. }
  381. ip := net.ParseIP(string(addr))
  382. if ip == nil {
  383. return nil, b, false
  384. }
  385. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  386. }
  387. // Dial connects to the given network address using net.Dial and
  388. // then initiates a SSH handshake, returning the resulting client connection.
  389. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  390. conn, err := net.Dial(network, addr)
  391. if err != nil {
  392. return nil, err
  393. }
  394. return clientWithAddress(conn, addr, config)
  395. }
  396. // A ClientConfig structure is used to configure a ClientConn. After one has
  397. // been passed to an SSH function it must not be modified.
  398. type ClientConfig struct {
  399. // Rand provides the source of entropy for key exchange. If Rand is
  400. // nil, the cryptographic random reader in package crypto/rand will
  401. // be used.
  402. Rand io.Reader
  403. // The username to authenticate.
  404. User string
  405. // A slice of ClientAuth methods. Only the first instance
  406. // of a particular RFC 4252 method will be used during authentication.
  407. Auth []ClientAuth
  408. // HostKeyChecker, if not nil, is called during the cryptographic
  409. // handshake to validate the server's host key. A nil HostKeyChecker
  410. // implies that all host keys are accepted.
  411. HostKeyChecker HostKeyChecker
  412. // Cryptographic-related configuration.
  413. Crypto CryptoConfig
  414. // The identification string that will be used for the connection.
  415. // If empty, a reasonable default is used.
  416. ClientVersion string
  417. }
  418. func (c *ClientConfig) rand() io.Reader {
  419. if c.Rand == nil {
  420. return rand.Reader
  421. }
  422. return c.Rand
  423. }
  424. // Thread safe channel list.
  425. type chanList struct {
  426. // protects concurrent access to chans
  427. sync.Mutex
  428. // chans are indexed by the local id of the channel, clientChan.localId.
  429. // The PeersId value of messages received by ClientConn.mainLoop is
  430. // used to locate the right local clientChan in this slice.
  431. chans []*clientChan
  432. }
  433. // Allocate a new ClientChan with the next avail local id.
  434. func (c *chanList) newChan(p packetConn) *clientChan {
  435. c.Lock()
  436. defer c.Unlock()
  437. for i := range c.chans {
  438. if c.chans[i] == nil {
  439. ch := newClientChan(p, uint32(i))
  440. c.chans[i] = ch
  441. return ch
  442. }
  443. }
  444. i := len(c.chans)
  445. ch := newClientChan(p, uint32(i))
  446. c.chans = append(c.chans, ch)
  447. return ch
  448. }
  449. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  450. c.Lock()
  451. defer c.Unlock()
  452. if id >= uint32(len(c.chans)) {
  453. return nil, false
  454. }
  455. return c.chans[id], true
  456. }
  457. func (c *chanList) remove(id uint32) {
  458. c.Lock()
  459. defer c.Unlock()
  460. c.chans[id] = nil
  461. }
  462. func (c *chanList) closeAll() {
  463. c.Lock()
  464. defer c.Unlock()
  465. for _, ch := range c.chans {
  466. if ch == nil {
  467. continue
  468. }
  469. ch.Close()
  470. close(ch.msg)
  471. }
  472. }