client.go 14 KB

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