client.go 14 KB

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