client.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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"
  7. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "math/big"
  12. "net"
  13. "sync"
  14. )
  15. // clientVersion is the fixed identification string that the client will use.
  16. var clientVersion = []byte("SSH-2.0-Go\r\n")
  17. // ClientConn represents the client side of an SSH connection.
  18. type ClientConn struct {
  19. *transport
  20. config *ClientConfig
  21. chanList // channels associated with this connection
  22. forwardList // forwarded tcpip connections from the remote side
  23. globalRequest
  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. conn := &ClientConn{
  32. transport: newTransport(c, config.rand()),
  33. config: config,
  34. globalRequest: globalRequest{response: make(chan interface{}, 1)},
  35. }
  36. if err := conn.handshake(); err != nil {
  37. conn.Close()
  38. return nil, err
  39. }
  40. go conn.mainLoop()
  41. return conn, nil
  42. }
  43. // handshake performs the client side key exchange. See RFC 4253 Section 7.
  44. func (c *ClientConn) handshake() error {
  45. var magics handshakeMagics
  46. if _, err := c.Write(clientVersion); err != nil {
  47. return err
  48. }
  49. if err := c.Flush(); err != nil {
  50. return err
  51. }
  52. magics.clientVersion = clientVersion[:len(clientVersion)-2]
  53. // read remote server version
  54. version, err := readVersion(c)
  55. if err != nil {
  56. return err
  57. }
  58. magics.serverVersion = version
  59. clientKexInit := kexInitMsg{
  60. KexAlgos: supportedKexAlgos,
  61. ServerHostKeyAlgos: supportedHostKeyAlgos,
  62. CiphersClientServer: c.config.Crypto.ciphers(),
  63. CiphersServerClient: c.config.Crypto.ciphers(),
  64. MACsClientServer: c.config.Crypto.macs(),
  65. MACsServerClient: c.config.Crypto.macs(),
  66. CompressionClientServer: supportedCompressions,
  67. CompressionServerClient: supportedCompressions,
  68. }
  69. kexInitPacket := marshal(msgKexInit, clientKexInit)
  70. magics.clientKexInit = kexInitPacket
  71. if err := c.writePacket(kexInitPacket); err != nil {
  72. return err
  73. }
  74. packet, err := c.readPacket()
  75. if err != nil {
  76. return err
  77. }
  78. magics.serverKexInit = packet
  79. var serverKexInit kexInitMsg
  80. if err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {
  81. return err
  82. }
  83. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)
  84. if !ok {
  85. return errors.New("ssh: no common algorithms")
  86. }
  87. if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {
  88. // The server sent a Kex message for the wrong algorithm,
  89. // which we have to ignore.
  90. if _, err := c.readPacket(); err != nil {
  91. return err
  92. }
  93. }
  94. var H, K []byte
  95. var hashFunc crypto.Hash
  96. switch kexAlgo {
  97. case kexAlgoDH14SHA1:
  98. hashFunc = crypto.SHA1
  99. dhGroup14Once.Do(initDHGroup14)
  100. H, K, err = c.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)
  101. case keyAlgoDH1SHA1:
  102. hashFunc = crypto.SHA1
  103. dhGroup1Once.Do(initDHGroup1)
  104. H, K, err = c.kexDH(dhGroup1, hashFunc, &magics, hostKeyAlgo)
  105. default:
  106. err = fmt.Errorf("ssh: unexpected key exchange algorithm %v", kexAlgo)
  107. }
  108. if err != nil {
  109. return err
  110. }
  111. if err = c.writePacket([]byte{msgNewKeys}); err != nil {
  112. return err
  113. }
  114. if err = c.transport.writer.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  115. return err
  116. }
  117. if packet, err = c.readPacket(); err != nil {
  118. return err
  119. }
  120. if packet[0] != msgNewKeys {
  121. return UnexpectedMessageError{msgNewKeys, packet[0]}
  122. }
  123. if err := c.transport.reader.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  124. return err
  125. }
  126. return c.authenticate(H)
  127. }
  128. // kexDH performs Diffie-Hellman key agreement on a ClientConn. The
  129. // returned values are given the same names as in RFC 4253, section 8.
  130. func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, error) {
  131. x, err := rand.Int(c.config.rand(), group.p)
  132. if err != nil {
  133. return nil, nil, err
  134. }
  135. X := new(big.Int).Exp(group.g, x, group.p)
  136. kexDHInit := kexDHInitMsg{
  137. X: X,
  138. }
  139. if err := c.writePacket(marshal(msgKexDHInit, kexDHInit)); err != nil {
  140. return nil, nil, err
  141. }
  142. packet, err := c.readPacket()
  143. if err != nil {
  144. return nil, nil, err
  145. }
  146. var kexDHReply kexDHReplyMsg
  147. if err = unmarshal(&kexDHReply, packet, msgKexDHReply); err != nil {
  148. return nil, nil, err
  149. }
  150. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  151. if err != nil {
  152. return nil, nil, err
  153. }
  154. h := hashFunc.New()
  155. writeString(h, magics.clientVersion)
  156. writeString(h, magics.serverVersion)
  157. writeString(h, magics.clientKexInit)
  158. writeString(h, magics.serverKexInit)
  159. writeString(h, kexDHReply.HostKey)
  160. writeInt(h, X)
  161. writeInt(h, kexDHReply.Y)
  162. K := make([]byte, intLength(kInt))
  163. marshalInt(K, kInt)
  164. h.Write(K)
  165. H := h.Sum(nil)
  166. return H, K, nil
  167. }
  168. // mainLoop reads incoming messages and routes channel messages
  169. // to their respective ClientChans.
  170. func (c *ClientConn) mainLoop() {
  171. defer func() {
  172. c.Close()
  173. c.closeAll()
  174. }()
  175. for {
  176. packet, err := c.readPacket()
  177. if err != nil {
  178. break
  179. }
  180. // TODO(dfc) A note on blocking channel use.
  181. // The msg, data and dataExt channels of a clientChan can
  182. // cause this loop to block indefinately if the consumer does
  183. // not service them.
  184. switch packet[0] {
  185. case msgChannelData:
  186. if len(packet) < 9 {
  187. // malformed data packet
  188. return
  189. }
  190. remoteId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  191. length := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  192. packet = packet[9:]
  193. if length != uint32(len(packet)) {
  194. return
  195. }
  196. ch, ok := c.getChan(remoteId)
  197. if !ok {
  198. return
  199. }
  200. ch.stdout.write(packet)
  201. case msgChannelExtendedData:
  202. if len(packet) < 13 {
  203. // malformed data packet
  204. return
  205. }
  206. remoteId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  207. datatype := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  208. length := uint32(packet[9])<<24 | uint32(packet[10])<<16 | uint32(packet[11])<<8 | uint32(packet[12])
  209. packet = packet[13:]
  210. if length != uint32(len(packet)) {
  211. return
  212. }
  213. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  214. // for stderr on interactive sessions. Other data types are
  215. // silently discarded.
  216. if datatype == 1 {
  217. ch, ok := c.getChan(remoteId)
  218. if !ok {
  219. return
  220. }
  221. ch.stderr.write(packet)
  222. }
  223. default:
  224. switch msg := decode(packet).(type) {
  225. case *channelOpenMsg:
  226. c.handleChanOpen(msg)
  227. case *channelOpenConfirmMsg:
  228. ch, ok := c.getChan(msg.PeersId)
  229. if !ok {
  230. return
  231. }
  232. ch.msg <- msg
  233. case *channelOpenFailureMsg:
  234. ch, ok := c.getChan(msg.PeersId)
  235. if !ok {
  236. return
  237. }
  238. ch.msg <- msg
  239. case *channelCloseMsg:
  240. ch, ok := c.getChan(msg.PeersId)
  241. if !ok {
  242. return
  243. }
  244. ch.theyClosed = true
  245. ch.stdout.eof()
  246. ch.stderr.eof()
  247. close(ch.msg)
  248. if !ch.weClosed {
  249. ch.weClosed = true
  250. ch.sendClose()
  251. }
  252. c.chanList.remove(msg.PeersId)
  253. case *channelEOFMsg:
  254. ch, ok := c.getChan(msg.PeersId)
  255. if !ok {
  256. return
  257. }
  258. ch.stdout.eof()
  259. // RFC 4254 is mute on how EOF affects dataExt messages but
  260. // it is logical to signal EOF at the same time.
  261. ch.stderr.eof()
  262. case *channelRequestSuccessMsg:
  263. ch, ok := c.getChan(msg.PeersId)
  264. if !ok {
  265. return
  266. }
  267. ch.msg <- msg
  268. case *channelRequestFailureMsg:
  269. ch, ok := c.getChan(msg.PeersId)
  270. if !ok {
  271. return
  272. }
  273. ch.msg <- msg
  274. case *channelRequestMsg:
  275. ch, ok := c.getChan(msg.PeersId)
  276. if !ok {
  277. return
  278. }
  279. ch.msg <- msg
  280. case *windowAdjustMsg:
  281. ch, ok := c.getChan(msg.PeersId)
  282. if !ok {
  283. return
  284. }
  285. if !ch.remoteWin.add(msg.AdditionalBytes) {
  286. // invalid window update
  287. return
  288. }
  289. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  290. c.globalRequest.response <- msg
  291. case *disconnectMsg:
  292. return
  293. default:
  294. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  295. }
  296. }
  297. }
  298. }
  299. // Handle channel open messages from the remote side.
  300. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  301. switch msg.ChanType {
  302. case "forwarded-tcpip":
  303. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  304. if !ok {
  305. // invalid request
  306. c.sendConnectionFailed(msg.PeersId)
  307. return
  308. }
  309. l, ok := c.forwardList.lookup(laddr)
  310. if !ok {
  311. fmt.Println("could not find forward list entry for", laddr)
  312. // Section 7.2, implementations MUST reject suprious incoming
  313. // connections.
  314. c.sendConnectionFailed(msg.PeersId)
  315. return
  316. }
  317. raddr, rest, ok := parseTCPAddr(rest)
  318. if !ok {
  319. // invalid request
  320. c.sendConnectionFailed(msg.PeersId)
  321. return
  322. }
  323. ch := c.newChan(c.transport)
  324. ch.remoteId = msg.PeersId
  325. ch.remoteWin.add(msg.PeersWindow)
  326. m := channelOpenConfirmMsg{
  327. PeersId: ch.remoteId,
  328. MyId: ch.localId,
  329. MyWindow: 1 << 14,
  330. MaxPacketSize: 1 << 15, // RFC 4253 6.1
  331. }
  332. c.writePacket(marshal(msgChannelOpenConfirm, m))
  333. l <- forward{ch, raddr}
  334. default:
  335. // unknown channel type
  336. m := channelOpenFailureMsg{
  337. PeersId: msg.PeersId,
  338. Reason: UnknownChannelType,
  339. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  340. Language: "en_US.UTF-8",
  341. }
  342. c.writePacket(marshal(msgChannelOpenFailure, m))
  343. }
  344. }
  345. // sendGlobalRequest sends a global request message as specified
  346. // in RFC4254 section 4. To correctly synchronise messages, a lock
  347. // is held internally until a response is returned.
  348. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  349. c.globalRequest.Lock()
  350. defer c.globalRequest.Unlock()
  351. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  352. return nil, err
  353. }
  354. r := <-c.globalRequest.response
  355. if r, ok := r.(*globalRequestSuccessMsg); ok {
  356. return r, nil
  357. }
  358. return nil, errors.New("request failed")
  359. }
  360. // sendConnectionFailed rejects an incoming channel identified
  361. // by remoteId.
  362. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  363. m := channelOpenFailureMsg{
  364. PeersId: remoteId,
  365. Reason: ConnectionFailed,
  366. Message: "invalid request",
  367. Language: "en_US.UTF-8",
  368. }
  369. return c.writePacket(marshal(msgChannelOpenFailure, m))
  370. }
  371. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  372. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  373. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  374. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  375. addr, b, ok := parseString(b)
  376. if !ok {
  377. return nil, b, false
  378. }
  379. port, b, ok := parseUint32(b)
  380. if !ok {
  381. return nil, b, false
  382. }
  383. ip := net.ParseIP(string(addr))
  384. if ip == nil {
  385. return nil, b, false
  386. }
  387. return &net.TCPAddr{ip, int(port)}, b, true
  388. }
  389. // Dial connects to the given network address using net.Dial and
  390. // then initiates a SSH handshake, returning the resulting client connection.
  391. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  392. conn, err := net.Dial(network, addr)
  393. if err != nil {
  394. return nil, err
  395. }
  396. return Client(conn, config)
  397. }
  398. // A ClientConfig structure is used to configure a ClientConn. After one has
  399. // been passed to an SSH function it must not be modified.
  400. type ClientConfig struct {
  401. // Rand provides the source of entropy for key exchange. If Rand is
  402. // nil, the cryptographic random reader in package crypto/rand will
  403. // be used.
  404. Rand io.Reader
  405. // The username to authenticate.
  406. User string
  407. // A slice of ClientAuth methods. Only the first instance
  408. // of a particular RFC 4252 method will be used during authentication.
  409. Auth []ClientAuth
  410. // Cryptographic-related configuration.
  411. Crypto CryptoConfig
  412. }
  413. func (c *ClientConfig) rand() io.Reader {
  414. if c.Rand == nil {
  415. return rand.Reader
  416. }
  417. return c.Rand
  418. }
  419. // A clientChan represents a single RFC 4254 channel that is multiplexed
  420. // over a single SSH connection.
  421. type clientChan struct {
  422. channel
  423. stdin *chanWriter
  424. stdout *chanReader
  425. stderr *chanReader
  426. msg chan interface{}
  427. }
  428. // newClientChan returns a partially constructed *clientChan
  429. // using the local id provided. To be usable clientChan.remoteId
  430. // needs to be assigned once known.
  431. func newClientChan(cc conn, id uint32) *clientChan {
  432. c := &clientChan{
  433. channel: channel{
  434. conn: cc,
  435. localId: id,
  436. remoteWin: window{Cond: newCond()},
  437. },
  438. msg: make(chan interface{}, 16),
  439. }
  440. c.stdin = &chanWriter{
  441. channel: &c.channel,
  442. }
  443. c.stdout = &chanReader{
  444. channel: &c.channel,
  445. buffer: newBuffer(),
  446. }
  447. c.stderr = &chanReader{
  448. channel: &c.channel,
  449. buffer: newBuffer(),
  450. }
  451. return c
  452. }
  453. // waitForChannelOpenResponse, if successful, fills out
  454. // the remoteId and records any initial window advertisement.
  455. func (c *clientChan) waitForChannelOpenResponse() error {
  456. switch msg := (<-c.msg).(type) {
  457. case *channelOpenConfirmMsg:
  458. // fixup remoteId field
  459. c.remoteId = msg.MyId
  460. c.remoteWin.add(msg.MyWindow)
  461. return nil
  462. case *channelOpenFailureMsg:
  463. return errors.New(safeString(msg.Message))
  464. }
  465. return errors.New("ssh: unexpected packet")
  466. }
  467. // Close closes the channel. This does not close the underlying connection.
  468. func (c *clientChan) Close() error {
  469. if !c.weClosed {
  470. c.weClosed = true
  471. return c.sendClose()
  472. }
  473. return nil
  474. }
  475. // Thread safe channel list.
  476. type chanList struct {
  477. // protects concurrent access to chans
  478. sync.Mutex
  479. // chans are indexed by the local id of the channel, clientChan.localId.
  480. // The PeersId value of messages received by ClientConn.mainLoop is
  481. // used to locate the right local clientChan in this slice.
  482. chans []*clientChan
  483. }
  484. // Allocate a new ClientChan with the next avail local id.
  485. func (c *chanList) newChan(t *transport) *clientChan {
  486. c.Lock()
  487. defer c.Unlock()
  488. for i := range c.chans {
  489. if c.chans[i] == nil {
  490. ch := newClientChan(t, uint32(i))
  491. c.chans[i] = ch
  492. return ch
  493. }
  494. }
  495. i := len(c.chans)
  496. ch := newClientChan(t, uint32(i))
  497. c.chans = append(c.chans, ch)
  498. return ch
  499. }
  500. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  501. c.Lock()
  502. defer c.Unlock()
  503. if id >= uint32(len(c.chans)) {
  504. return nil, false
  505. }
  506. return c.chans[id], true
  507. }
  508. func (c *chanList) remove(id uint32) {
  509. c.Lock()
  510. defer c.Unlock()
  511. c.chans[id] = nil
  512. }
  513. func (c *chanList) closeAll() {
  514. c.Lock()
  515. defer c.Unlock()
  516. for _, ch := range c.chans {
  517. if ch == nil {
  518. continue
  519. }
  520. ch.theyClosed = true
  521. ch.stdout.eof()
  522. ch.stderr.eof()
  523. close(ch.msg)
  524. }
  525. }
  526. // A chanWriter represents the stdin of a remote process.
  527. type chanWriter struct {
  528. *channel
  529. }
  530. // Write writes data to the remote process's standard input.
  531. func (w *chanWriter) Write(data []byte) (written int, err error) {
  532. for len(data) > 0 {
  533. // n cannot be larger than 2^31 as len(data) cannot
  534. // be larger than 2^31
  535. n := int(w.remoteWin.reserve(uint32(len(data))))
  536. remoteId := w.remoteId
  537. packet := []byte{
  538. msgChannelData,
  539. byte(remoteId >> 24), byte(remoteId >> 16), byte(remoteId >> 8), byte(remoteId),
  540. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  541. }
  542. if err = w.writePacket(append(packet, data[:n]...)); err != nil {
  543. break
  544. }
  545. data = data[n:]
  546. written += n
  547. }
  548. return
  549. }
  550. func min(a, b int) int {
  551. if a < b {
  552. return a
  553. }
  554. return b
  555. }
  556. func (w *chanWriter) Close() error {
  557. return w.sendEOF()
  558. }
  559. // A chanReader represents stdout or stderr of a remote process.
  560. type chanReader struct {
  561. *channel // the channel backing this reader
  562. *buffer
  563. }
  564. // Read reads data from the remote process's stdout or stderr.
  565. func (r *chanReader) Read(buf []byte) (int, error) {
  566. n, err := r.buffer.Read(buf)
  567. if err != nil {
  568. if err == io.EOF {
  569. return n, err
  570. }
  571. return 0, err
  572. }
  573. return n, r.sendWindowAdj(n)
  574. }