client.go 14 KB

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