handshake.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // Copyright 2013 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/rand"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "sync"
  13. )
  14. // debugHandshake, if set, prints messages sent and received. Key
  15. // exchange messages are printed as if DH were used, so the debug
  16. // messages are wrong when using ECDH.
  17. const debugHandshake = false
  18. // keyingTransport is a packet based transport that supports key
  19. // changes. It need not be thread-safe. It should pass through
  20. // msgNewKeys in both directions.
  21. type keyingTransport interface {
  22. packetConn
  23. // prepareKeyChange sets up a key change. The key change for a
  24. // direction will be effected if a msgNewKeys message is sent
  25. // or received.
  26. prepareKeyChange(*algorithms, *kexResult) error
  27. }
  28. // handshakeTransport implements rekeying on top of a keyingTransport
  29. // and offers a thread-safe writePacket() interface.
  30. type handshakeTransport struct {
  31. conn keyingTransport
  32. config *Config
  33. serverVersion []byte
  34. clientVersion []byte
  35. // hostKeys is non-empty if we are the server. In that case,
  36. // it contains all host keys that can be used to sign the
  37. // connection.
  38. hostKeys []Signer
  39. // hostKeyAlgorithms is non-empty if we are the client. In that case,
  40. // we accept these key types from the server as host key.
  41. hostKeyAlgorithms []string
  42. // On read error, incoming is closed, and readError is set.
  43. incoming chan []byte
  44. readError error
  45. // data for host key checking
  46. hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  47. dialAddress string
  48. remoteAddr net.Addr
  49. readSinceKex uint64
  50. // Protects the writing side of the connection
  51. mu sync.Mutex
  52. cond *sync.Cond
  53. sentInitPacket []byte
  54. sentInitMsg *kexInitMsg
  55. writtenSinceKex uint64
  56. writeError error
  57. // The session ID or nil if first kex did not complete yet.
  58. sessionID []byte
  59. }
  60. func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
  61. t := &handshakeTransport{
  62. conn: conn,
  63. serverVersion: serverVersion,
  64. clientVersion: clientVersion,
  65. incoming: make(chan []byte, 16),
  66. config: config,
  67. }
  68. t.cond = sync.NewCond(&t.mu)
  69. return t
  70. }
  71. func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
  72. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  73. t.dialAddress = dialAddr
  74. t.remoteAddr = addr
  75. t.hostKeyCallback = config.HostKeyCallback
  76. if config.HostKeyAlgorithms != nil {
  77. t.hostKeyAlgorithms = config.HostKeyAlgorithms
  78. } else {
  79. t.hostKeyAlgorithms = supportedHostKeyAlgos
  80. }
  81. go t.readLoop()
  82. return t
  83. }
  84. func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
  85. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  86. t.hostKeys = config.hostKeys
  87. go t.readLoop()
  88. return t
  89. }
  90. func (t *handshakeTransport) getSessionID() []byte {
  91. return t.sessionID
  92. }
  93. func (t *handshakeTransport) id() string {
  94. if len(t.hostKeys) > 0 {
  95. return "server"
  96. }
  97. return "client"
  98. }
  99. func (t *handshakeTransport) readPacket() ([]byte, error) {
  100. p, ok := <-t.incoming
  101. if !ok {
  102. return nil, t.readError
  103. }
  104. return p, nil
  105. }
  106. func (t *handshakeTransport) readLoop() {
  107. for {
  108. p, err := t.readOnePacket()
  109. if err != nil {
  110. t.readError = err
  111. close(t.incoming)
  112. break
  113. }
  114. if p[0] == msgIgnore || p[0] == msgDebug {
  115. continue
  116. }
  117. t.incoming <- p
  118. }
  119. // If we can't read, declare the writing part dead too.
  120. t.mu.Lock()
  121. defer t.mu.Unlock()
  122. if t.writeError == nil {
  123. t.writeError = t.readError
  124. }
  125. t.cond.Broadcast()
  126. }
  127. func (t *handshakeTransport) readOnePacket() ([]byte, error) {
  128. if t.readSinceKex > t.config.RekeyThreshold {
  129. if err := t.requestKeyChange(); err != nil {
  130. return nil, err
  131. }
  132. }
  133. p, err := t.conn.readPacket()
  134. if err != nil {
  135. return nil, err
  136. }
  137. t.readSinceKex += uint64(len(p))
  138. if debugHandshake {
  139. if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
  140. log.Printf("%s got data (packet %d bytes)", t.id(), len(p))
  141. } else {
  142. msg, err := decode(p)
  143. log.Printf("%s got %T %v (%v)", t.id(), msg, msg, err)
  144. }
  145. }
  146. if p[0] != msgKexInit {
  147. return p, nil
  148. }
  149. t.mu.Lock()
  150. firstKex := t.sessionID == nil
  151. err = t.enterKeyExchangeLocked(p)
  152. if err != nil {
  153. // drop connection
  154. t.conn.Close()
  155. t.writeError = err
  156. }
  157. if debugHandshake {
  158. log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
  159. }
  160. // Unblock writers.
  161. t.sentInitMsg = nil
  162. t.sentInitPacket = nil
  163. t.cond.Broadcast()
  164. t.writtenSinceKex = 0
  165. t.mu.Unlock()
  166. if err != nil {
  167. return nil, err
  168. }
  169. t.readSinceKex = 0
  170. // By default, a key exchange is hidden from higher layers by
  171. // translating it into msgIgnore.
  172. successPacket := []byte{msgIgnore}
  173. if firstKex {
  174. // sendKexInit() for the first kex waits for
  175. // msgNewKeys so the authentication process is
  176. // guaranteed to happen over an encrypted transport.
  177. successPacket = []byte{msgNewKeys}
  178. }
  179. return successPacket, nil
  180. }
  181. // keyChangeCategory describes whether a key exchange is the first on a
  182. // connection, or a subsequent one.
  183. type keyChangeCategory bool
  184. const (
  185. firstKeyExchange keyChangeCategory = true
  186. subsequentKeyExchange keyChangeCategory = false
  187. )
  188. // sendKexInit sends a key change message, and returns the message
  189. // that was sent. After initiating the key change, all writes will be
  190. // blocked until the change is done, and a failed key change will
  191. // close the underlying transport. This function is safe for
  192. // concurrent use by multiple goroutines.
  193. func (t *handshakeTransport) sendKexInit(isFirst keyChangeCategory) error {
  194. var err error
  195. t.mu.Lock()
  196. // If this is the initial key change, but we already have a sessionID,
  197. // then do nothing because the key exchange has already completed
  198. // asynchronously.
  199. if !isFirst || t.sessionID == nil {
  200. _, _, err = t.sendKexInitLocked(isFirst)
  201. }
  202. t.mu.Unlock()
  203. if err != nil {
  204. return err
  205. }
  206. if isFirst {
  207. if packet, err := t.readPacket(); err != nil {
  208. return err
  209. } else if packet[0] != msgNewKeys {
  210. return unexpectedMessageError(msgNewKeys, packet[0])
  211. }
  212. }
  213. return nil
  214. }
  215. func (t *handshakeTransport) requestInitialKeyChange() error {
  216. return t.sendKexInit(firstKeyExchange)
  217. }
  218. func (t *handshakeTransport) requestKeyChange() error {
  219. return t.sendKexInit(subsequentKeyExchange)
  220. }
  221. // sendKexInitLocked sends a key change message. t.mu must be locked
  222. // while this happens.
  223. func (t *handshakeTransport) sendKexInitLocked(isFirst keyChangeCategory) (*kexInitMsg, []byte, error) {
  224. // kexInits may be sent either in response to the other side,
  225. // or because our side wants to initiate a key change, so we
  226. // may have already sent a kexInit. In that case, don't send a
  227. // second kexInit.
  228. if t.sentInitMsg != nil {
  229. return t.sentInitMsg, t.sentInitPacket, nil
  230. }
  231. msg := &kexInitMsg{
  232. KexAlgos: t.config.KeyExchanges,
  233. CiphersClientServer: t.config.Ciphers,
  234. CiphersServerClient: t.config.Ciphers,
  235. MACsClientServer: t.config.MACs,
  236. MACsServerClient: t.config.MACs,
  237. CompressionClientServer: supportedCompressions,
  238. CompressionServerClient: supportedCompressions,
  239. }
  240. io.ReadFull(rand.Reader, msg.Cookie[:])
  241. if len(t.hostKeys) > 0 {
  242. for _, k := range t.hostKeys {
  243. msg.ServerHostKeyAlgos = append(
  244. msg.ServerHostKeyAlgos, k.PublicKey().Type())
  245. }
  246. } else {
  247. msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
  248. }
  249. packet := Marshal(msg)
  250. // writePacket destroys the contents, so save a copy.
  251. packetCopy := make([]byte, len(packet))
  252. copy(packetCopy, packet)
  253. if err := t.conn.writePacket(packetCopy); err != nil {
  254. return nil, nil, err
  255. }
  256. t.sentInitMsg = msg
  257. t.sentInitPacket = packet
  258. return msg, packet, nil
  259. }
  260. func (t *handshakeTransport) writePacket(p []byte) error {
  261. t.mu.Lock()
  262. defer t.mu.Unlock()
  263. if t.writtenSinceKex > t.config.RekeyThreshold {
  264. t.sendKexInitLocked(subsequentKeyExchange)
  265. }
  266. for t.sentInitMsg != nil && t.writeError == nil {
  267. t.cond.Wait()
  268. }
  269. if t.writeError != nil {
  270. return t.writeError
  271. }
  272. t.writtenSinceKex += uint64(len(p))
  273. switch p[0] {
  274. case msgKexInit:
  275. return errors.New("ssh: only handshakeTransport can send kexInit")
  276. case msgNewKeys:
  277. return errors.New("ssh: only handshakeTransport can send newKeys")
  278. default:
  279. return t.conn.writePacket(p)
  280. }
  281. }
  282. func (t *handshakeTransport) Close() error {
  283. return t.conn.Close()
  284. }
  285. // enterKeyExchange runs the key exchange. t.mu must be held while running this.
  286. func (t *handshakeTransport) enterKeyExchangeLocked(otherInitPacket []byte) error {
  287. if debugHandshake {
  288. log.Printf("%s entered key exchange", t.id())
  289. }
  290. myInit, myInitPacket, err := t.sendKexInitLocked(subsequentKeyExchange)
  291. if err != nil {
  292. return err
  293. }
  294. otherInit := &kexInitMsg{}
  295. if err := Unmarshal(otherInitPacket, otherInit); err != nil {
  296. return err
  297. }
  298. magics := handshakeMagics{
  299. clientVersion: t.clientVersion,
  300. serverVersion: t.serverVersion,
  301. clientKexInit: otherInitPacket,
  302. serverKexInit: myInitPacket,
  303. }
  304. clientInit := otherInit
  305. serverInit := myInit
  306. if len(t.hostKeys) == 0 {
  307. clientInit = myInit
  308. serverInit = otherInit
  309. magics.clientKexInit = myInitPacket
  310. magics.serverKexInit = otherInitPacket
  311. }
  312. algs, err := findAgreedAlgorithms(clientInit, serverInit)
  313. if err != nil {
  314. return err
  315. }
  316. // We don't send FirstKexFollows, but we handle receiving it.
  317. //
  318. // RFC 4253 section 7 defines the kex and the agreement method for
  319. // first_kex_packet_follows. It states that the guessed packet
  320. // should be ignored if the "kex algorithm and/or the host
  321. // key algorithm is guessed wrong (server and client have
  322. // different preferred algorithm), or if any of the other
  323. // algorithms cannot be agreed upon". The other algorithms have
  324. // already been checked above so the kex algorithm and host key
  325. // algorithm are checked here.
  326. if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
  327. // other side sent a kex message for the wrong algorithm,
  328. // which we have to ignore.
  329. if _, err := t.conn.readPacket(); err != nil {
  330. return err
  331. }
  332. }
  333. kex, ok := kexAlgoMap[algs.kex]
  334. if !ok {
  335. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
  336. }
  337. var result *kexResult
  338. if len(t.hostKeys) > 0 {
  339. result, err = t.server(kex, algs, &magics)
  340. } else {
  341. result, err = t.client(kex, algs, &magics)
  342. }
  343. if err != nil {
  344. return err
  345. }
  346. if t.sessionID == nil {
  347. t.sessionID = result.H
  348. }
  349. result.SessionID = t.sessionID
  350. t.conn.prepareKeyChange(algs, result)
  351. if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
  352. return err
  353. }
  354. if packet, err := t.conn.readPacket(); err != nil {
  355. return err
  356. } else if packet[0] != msgNewKeys {
  357. return unexpectedMessageError(msgNewKeys, packet[0])
  358. }
  359. return nil
  360. }
  361. func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  362. var hostKey Signer
  363. for _, k := range t.hostKeys {
  364. if algs.hostKey == k.PublicKey().Type() {
  365. hostKey = k
  366. }
  367. }
  368. r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
  369. return r, err
  370. }
  371. func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  372. result, err := kex.Client(t.conn, t.config.Rand, magics)
  373. if err != nil {
  374. return nil, err
  375. }
  376. hostKey, err := ParsePublicKey(result.HostKey)
  377. if err != nil {
  378. return nil, err
  379. }
  380. if err := verifyHostKeySignature(hostKey, result); err != nil {
  381. return nil, err
  382. }
  383. if t.hostKeyCallback != nil {
  384. err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
  385. if err != nil {
  386. return nil, err
  387. }
  388. }
  389. return result, nil
  390. }