client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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.chanList.closeAll()
  186. c.forwardList.closeAll()
  187. }()
  188. for {
  189. packet, err := c.readPacket()
  190. if err != nil {
  191. break
  192. }
  193. // TODO(dfc) A note on blocking channel use.
  194. // The msg, data and dataExt channels of a clientChan can
  195. // cause this loop to block indefinately if the consumer does
  196. // not service them.
  197. switch packet[0] {
  198. case msgChannelData:
  199. if len(packet) < 9 {
  200. // malformed data packet
  201. return
  202. }
  203. remoteId := binary.BigEndian.Uint32(packet[1:5])
  204. length := binary.BigEndian.Uint32(packet[5:9])
  205. packet = packet[9:]
  206. if length != uint32(len(packet)) {
  207. return
  208. }
  209. ch, ok := c.getChan(remoteId)
  210. if !ok {
  211. return
  212. }
  213. ch.stdout.write(packet)
  214. case msgChannelExtendedData:
  215. if len(packet) < 13 {
  216. // malformed data packet
  217. return
  218. }
  219. remoteId := binary.BigEndian.Uint32(packet[1:5])
  220. datatype := binary.BigEndian.Uint32(packet[5:9])
  221. length := binary.BigEndian.Uint32(packet[9:13])
  222. packet = packet[13:]
  223. if length != uint32(len(packet)) {
  224. return
  225. }
  226. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  227. // for stderr on interactive sessions. Other data types are
  228. // silently discarded.
  229. if datatype == 1 {
  230. ch, ok := c.getChan(remoteId)
  231. if !ok {
  232. return
  233. }
  234. ch.stderr.write(packet)
  235. }
  236. default:
  237. decoded, err := decode(packet)
  238. if err != nil {
  239. if _, ok := err.(UnexpectedMessageError); ok {
  240. fmt.Printf("mainLoop: unexpected message: %v\n", err)
  241. continue
  242. }
  243. return
  244. }
  245. switch msg := decoded.(type) {
  246. case *channelOpenMsg:
  247. c.handleChanOpen(msg)
  248. case *channelOpenConfirmMsg:
  249. ch, ok := c.getChan(msg.PeersId)
  250. if !ok {
  251. return
  252. }
  253. ch.msg <- msg
  254. case *channelOpenFailureMsg:
  255. ch, ok := c.getChan(msg.PeersId)
  256. if !ok {
  257. return
  258. }
  259. ch.msg <- msg
  260. case *channelCloseMsg:
  261. ch, ok := c.getChan(msg.PeersId)
  262. if !ok {
  263. return
  264. }
  265. ch.Close()
  266. close(ch.msg)
  267. c.chanList.remove(msg.PeersId)
  268. case *channelEOFMsg:
  269. ch, ok := c.getChan(msg.PeersId)
  270. if !ok {
  271. return
  272. }
  273. ch.stdout.eof()
  274. // RFC 4254 is mute on how EOF affects dataExt messages but
  275. // it is logical to signal EOF at the same time.
  276. ch.stderr.eof()
  277. case *channelRequestSuccessMsg:
  278. ch, ok := c.getChan(msg.PeersId)
  279. if !ok {
  280. return
  281. }
  282. ch.msg <- msg
  283. case *channelRequestFailureMsg:
  284. ch, ok := c.getChan(msg.PeersId)
  285. if !ok {
  286. return
  287. }
  288. ch.msg <- msg
  289. case *channelRequestMsg:
  290. ch, ok := c.getChan(msg.PeersId)
  291. if !ok {
  292. return
  293. }
  294. ch.msg <- msg
  295. case *windowAdjustMsg:
  296. ch, ok := c.getChan(msg.PeersId)
  297. if !ok {
  298. return
  299. }
  300. if !ch.remoteWin.add(msg.AdditionalBytes) {
  301. // invalid window update
  302. return
  303. }
  304. case *globalRequestMsg:
  305. // This handles keepalive messages and matches
  306. // the behaviour of OpenSSH.
  307. if msg.WantReply {
  308. c.writePacket(marshal(msgRequestFailure, globalRequestFailureMsg{}))
  309. }
  310. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  311. c.globalRequest.response <- msg
  312. case *disconnectMsg:
  313. return
  314. default:
  315. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  316. }
  317. }
  318. }
  319. }
  320. // Handle channel open messages from the remote side.
  321. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  322. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  323. c.sendConnectionFailed(msg.PeersId)
  324. }
  325. switch msg.ChanType {
  326. case "forwarded-tcpip":
  327. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  328. if !ok {
  329. // invalid request
  330. c.sendConnectionFailed(msg.PeersId)
  331. return
  332. }
  333. l, ok := c.forwardList.lookup(*laddr)
  334. if !ok {
  335. // TODO: print on a more structured log.
  336. fmt.Println("could not find forward list entry for", laddr)
  337. // Section 7.2, implementations MUST reject suprious incoming
  338. // connections.
  339. c.sendConnectionFailed(msg.PeersId)
  340. return
  341. }
  342. raddr, rest, ok := parseTCPAddr(rest)
  343. if !ok {
  344. // invalid request
  345. c.sendConnectionFailed(msg.PeersId)
  346. return
  347. }
  348. ch := c.newChan(c.transport)
  349. ch.remoteId = msg.PeersId
  350. ch.remoteWin.add(msg.PeersWindow)
  351. ch.maxPacket = msg.MaxPacketSize
  352. m := channelOpenConfirmMsg{
  353. PeersId: ch.remoteId,
  354. MyId: ch.localId,
  355. MyWindow: 1 << 14,
  356. // As per RFC 4253 6.1, 32k is also the minimum.
  357. MaxPacketSize: 1 << 15,
  358. }
  359. c.writePacket(marshal(msgChannelOpenConfirm, m))
  360. l <- forward{ch, raddr}
  361. default:
  362. // unknown channel type
  363. m := channelOpenFailureMsg{
  364. PeersId: msg.PeersId,
  365. Reason: UnknownChannelType,
  366. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  367. Language: "en_US.UTF-8",
  368. }
  369. c.writePacket(marshal(msgChannelOpenFailure, m))
  370. }
  371. }
  372. // sendGlobalRequest sends a global request message as specified
  373. // in RFC4254 section 4. To correctly synchronise messages, a lock
  374. // is held internally until a response is returned.
  375. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  376. c.globalRequest.Lock()
  377. defer c.globalRequest.Unlock()
  378. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  379. return nil, err
  380. }
  381. r := <-c.globalRequest.response
  382. if r, ok := r.(*globalRequestSuccessMsg); ok {
  383. return r, nil
  384. }
  385. return nil, errors.New("request failed")
  386. }
  387. // sendConnectionFailed rejects an incoming channel identified
  388. // by remoteId.
  389. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  390. m := channelOpenFailureMsg{
  391. PeersId: remoteId,
  392. Reason: ConnectionFailed,
  393. Message: "invalid request",
  394. Language: "en_US.UTF-8",
  395. }
  396. return c.writePacket(marshal(msgChannelOpenFailure, m))
  397. }
  398. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  399. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  400. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  401. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  402. addr, b, ok := parseString(b)
  403. if !ok {
  404. return nil, b, false
  405. }
  406. port, b, ok := parseUint32(b)
  407. if !ok {
  408. return nil, b, false
  409. }
  410. ip := net.ParseIP(string(addr))
  411. if ip == nil {
  412. return nil, b, false
  413. }
  414. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  415. }
  416. // Dial connects to the given network address using net.Dial and
  417. // then initiates a SSH handshake, returning the resulting client connection.
  418. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  419. conn, err := net.Dial(network, addr)
  420. if err != nil {
  421. return nil, err
  422. }
  423. return clientWithAddress(conn, addr, config)
  424. }
  425. // A ClientConfig structure is used to configure a ClientConn. After one has
  426. // been passed to an SSH function it must not be modified.
  427. type ClientConfig struct {
  428. // Rand provides the source of entropy for key exchange. If Rand is
  429. // nil, the cryptographic random reader in package crypto/rand will
  430. // be used.
  431. Rand io.Reader
  432. // The username to authenticate.
  433. User string
  434. // A slice of ClientAuth methods. Only the first instance
  435. // of a particular RFC 4252 method will be used during authentication.
  436. Auth []ClientAuth
  437. // HostKeyChecker, if not nil, is called during the cryptographic
  438. // handshake to validate the server's host key. A nil HostKeyChecker
  439. // implies that all host keys are accepted.
  440. HostKeyChecker HostKeyChecker
  441. // Cryptographic-related configuration.
  442. Crypto CryptoConfig
  443. }
  444. func (c *ClientConfig) rand() io.Reader {
  445. if c.Rand == nil {
  446. return rand.Reader
  447. }
  448. return c.Rand
  449. }
  450. // Thread safe channel list.
  451. type chanList struct {
  452. // protects concurrent access to chans
  453. sync.Mutex
  454. // chans are indexed by the local id of the channel, clientChan.localId.
  455. // The PeersId value of messages received by ClientConn.mainLoop is
  456. // used to locate the right local clientChan in this slice.
  457. chans []*clientChan
  458. }
  459. // Allocate a new ClientChan with the next avail local id.
  460. func (c *chanList) newChan(t *transport) *clientChan {
  461. c.Lock()
  462. defer c.Unlock()
  463. for i := range c.chans {
  464. if c.chans[i] == nil {
  465. ch := newClientChan(t, uint32(i))
  466. c.chans[i] = ch
  467. return ch
  468. }
  469. }
  470. i := len(c.chans)
  471. ch := newClientChan(t, uint32(i))
  472. c.chans = append(c.chans, ch)
  473. return ch
  474. }
  475. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  476. c.Lock()
  477. defer c.Unlock()
  478. if id >= uint32(len(c.chans)) {
  479. return nil, false
  480. }
  481. return c.chans[id], true
  482. }
  483. func (c *chanList) remove(id uint32) {
  484. c.Lock()
  485. defer c.Unlock()
  486. c.chans[id] = nil
  487. }
  488. func (c *chanList) closeAll() {
  489. c.Lock()
  490. defer c.Unlock()
  491. for _, ch := range c.chans {
  492. if ch == nil {
  493. continue
  494. }
  495. ch.Close()
  496. close(ch.msg)
  497. }
  498. }