You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

412 lines
10 KiB

  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. // getSessionID returns the session ID. prepareKeyChange must
  28. // have been called once.
  29. getSessionID() []byte
  30. }
  31. // rekeyingTransport is the interface of handshakeTransport that we
  32. // (internally) expose to ClientConn and ServerConn.
  33. type rekeyingTransport interface {
  34. packetConn
  35. // requestKeyChange asks the remote side to change keys. All
  36. // writes are blocked until the key change succeeds, which is
  37. // signaled by reading a msgNewKeys.
  38. requestKeyChange() error
  39. // getSessionID returns the session ID. This is only valid
  40. // after the first key change has completed.
  41. getSessionID() []byte
  42. }
  43. // handshakeTransport implements rekeying on top of a keyingTransport
  44. // and offers a thread-safe writePacket() interface.
  45. type handshakeTransport struct {
  46. conn keyingTransport
  47. config *Config
  48. serverVersion []byte
  49. clientVersion []byte
  50. // hostKeys is non-empty if we are the server. In that case,
  51. // it contains all host keys that can be used to sign the
  52. // connection.
  53. hostKeys []Signer
  54. // hostKeyAlgorithms is non-empty if we are the client. In that case,
  55. // we accept these key types from the server as host key.
  56. hostKeyAlgorithms []string
  57. // On read error, incoming is closed, and readError is set.
  58. incoming chan []byte
  59. readError error
  60. // data for host key checking
  61. hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  62. dialAddress string
  63. remoteAddr net.Addr
  64. readSinceKex uint64
  65. // Protects the writing side of the connection
  66. mu sync.Mutex
  67. cond *sync.Cond
  68. sentInitPacket []byte
  69. sentInitMsg *kexInitMsg
  70. writtenSinceKex uint64
  71. writeError error
  72. }
  73. func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
  74. t := &handshakeTransport{
  75. conn: conn,
  76. serverVersion: serverVersion,
  77. clientVersion: clientVersion,
  78. incoming: make(chan []byte, 16),
  79. config: config,
  80. }
  81. t.cond = sync.NewCond(&t.mu)
  82. return t
  83. }
  84. func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
  85. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  86. t.dialAddress = dialAddr
  87. t.remoteAddr = addr
  88. t.hostKeyCallback = config.HostKeyCallback
  89. if config.HostKeyAlgorithms != nil {
  90. t.hostKeyAlgorithms = config.HostKeyAlgorithms
  91. } else {
  92. t.hostKeyAlgorithms = supportedHostKeyAlgos
  93. }
  94. go t.readLoop()
  95. return t
  96. }
  97. func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
  98. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  99. t.hostKeys = config.hostKeys
  100. go t.readLoop()
  101. return t
  102. }
  103. func (t *handshakeTransport) getSessionID() []byte {
  104. return t.conn.getSessionID()
  105. }
  106. func (t *handshakeTransport) id() string {
  107. if len(t.hostKeys) > 0 {
  108. return "server"
  109. }
  110. return "client"
  111. }
  112. func (t *handshakeTransport) readPacket() ([]byte, error) {
  113. p, ok := <-t.incoming
  114. if !ok {
  115. return nil, t.readError
  116. }
  117. return p, nil
  118. }
  119. func (t *handshakeTransport) readLoop() {
  120. for {
  121. p, err := t.readOnePacket()
  122. if err != nil {
  123. t.readError = err
  124. close(t.incoming)
  125. break
  126. }
  127. if p[0] == msgIgnore || p[0] == msgDebug {
  128. continue
  129. }
  130. t.incoming <- p
  131. }
  132. // If we can't read, declare the writing part dead too.
  133. t.mu.Lock()
  134. defer t.mu.Unlock()
  135. if t.writeError == nil {
  136. t.writeError = t.readError
  137. }
  138. t.cond.Broadcast()
  139. }
  140. func (t *handshakeTransport) readOnePacket() ([]byte, error) {
  141. if t.readSinceKex > t.config.RekeyThreshold {
  142. if err := t.requestKeyChange(); err != nil {
  143. return nil, err
  144. }
  145. }
  146. p, err := t.conn.readPacket()
  147. if err != nil {
  148. return nil, err
  149. }
  150. t.readSinceKex += uint64(len(p))
  151. if debugHandshake {
  152. msg, err := decode(p)
  153. log.Printf("%s got %T %v (%v)", t.id(), msg, msg, err)
  154. }
  155. if p[0] != msgKexInit {
  156. return p, nil
  157. }
  158. err = t.enterKeyExchange(p)
  159. t.mu.Lock()
  160. if err != nil {
  161. // drop connection
  162. t.conn.Close()
  163. t.writeError = err
  164. }
  165. if debugHandshake {
  166. log.Printf("%s exited key exchange, err %v", t.id(), err)
  167. }
  168. // Unblock writers.
  169. t.sentInitMsg = nil
  170. t.sentInitPacket = nil
  171. t.cond.Broadcast()
  172. t.writtenSinceKex = 0
  173. t.mu.Unlock()
  174. if err != nil {
  175. return nil, err
  176. }
  177. t.readSinceKex = 0
  178. return []byte{msgNewKeys}, nil
  179. }
  180. // sendKexInit sends a key change message, and returns the message
  181. // that was sent. After initiating the key change, all writes will be
  182. // blocked until the change is done, and a failed key change will
  183. // close the underlying transport. This function is safe for
  184. // concurrent use by multiple goroutines.
  185. func (t *handshakeTransport) sendKexInit() (*kexInitMsg, []byte, error) {
  186. t.mu.Lock()
  187. defer t.mu.Unlock()
  188. return t.sendKexInitLocked()
  189. }
  190. func (t *handshakeTransport) requestKeyChange() error {
  191. _, _, err := t.sendKexInit()
  192. return err
  193. }
  194. // sendKexInitLocked sends a key change message. t.mu must be locked
  195. // while this happens.
  196. func (t *handshakeTransport) sendKexInitLocked() (*kexInitMsg, []byte, error) {
  197. // kexInits may be sent either in response to the other side,
  198. // or because our side wants to initiate a key change, so we
  199. // may have already sent a kexInit. In that case, don't send a
  200. // second kexInit.
  201. if t.sentInitMsg != nil {
  202. return t.sentInitMsg, t.sentInitPacket, nil
  203. }
  204. msg := &kexInitMsg{
  205. KexAlgos: t.config.KeyExchanges,
  206. CiphersClientServer: t.config.Ciphers,
  207. CiphersServerClient: t.config.Ciphers,
  208. MACsClientServer: t.config.MACs,
  209. MACsServerClient: t.config.MACs,
  210. CompressionClientServer: supportedCompressions,
  211. CompressionServerClient: supportedCompressions,
  212. }
  213. io.ReadFull(rand.Reader, msg.Cookie[:])
  214. if len(t.hostKeys) > 0 {
  215. for _, k := range t.hostKeys {
  216. msg.ServerHostKeyAlgos = append(
  217. msg.ServerHostKeyAlgos, k.PublicKey().Type())
  218. }
  219. } else {
  220. msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
  221. }
  222. packet := Marshal(msg)
  223. // writePacket destroys the contents, so save a copy.
  224. packetCopy := make([]byte, len(packet))
  225. copy(packetCopy, packet)
  226. if err := t.conn.writePacket(packetCopy); err != nil {
  227. return nil, nil, err
  228. }
  229. t.sentInitMsg = msg
  230. t.sentInitPacket = packet
  231. return msg, packet, nil
  232. }
  233. func (t *handshakeTransport) writePacket(p []byte) error {
  234. t.mu.Lock()
  235. defer t.mu.Unlock()
  236. if t.writtenSinceKex > t.config.RekeyThreshold {
  237. t.sendKexInitLocked()
  238. }
  239. for t.sentInitMsg != nil && t.writeError == nil {
  240. t.cond.Wait()
  241. }
  242. if t.writeError != nil {
  243. return t.writeError
  244. }
  245. t.writtenSinceKex += uint64(len(p))
  246. switch p[0] {
  247. case msgKexInit:
  248. return errors.New("ssh: only handshakeTransport can send kexInit")
  249. case msgNewKeys:
  250. return errors.New("ssh: only handshakeTransport can send newKeys")
  251. default:
  252. return t.conn.writePacket(p)
  253. }
  254. }
  255. func (t *handshakeTransport) Close() error {
  256. return t.conn.Close()
  257. }
  258. // enterKeyExchange runs the key exchange.
  259. func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
  260. if debugHandshake {
  261. log.Printf("%s entered key exchange", t.id())
  262. }
  263. myInit, myInitPacket, err := t.sendKexInit()
  264. if err != nil {
  265. return err
  266. }
  267. otherInit := &kexInitMsg{}
  268. if err := Unmarshal(otherInitPacket, otherInit); err != nil {
  269. return err
  270. }
  271. magics := handshakeMagics{
  272. clientVersion: t.clientVersion,
  273. serverVersion: t.serverVersion,
  274. clientKexInit: otherInitPacket,
  275. serverKexInit: myInitPacket,
  276. }
  277. clientInit := otherInit
  278. serverInit := myInit
  279. if len(t.hostKeys) == 0 {
  280. clientInit = myInit
  281. serverInit = otherInit
  282. magics.clientKexInit = myInitPacket
  283. magics.serverKexInit = otherInitPacket
  284. }
  285. algs, err := findAgreedAlgorithms(clientInit, serverInit)
  286. if err != nil {
  287. return err
  288. }
  289. // We don't send FirstKexFollows, but we handle receiving it.
  290. if otherInit.FirstKexFollows && algs.kex != otherInit.KexAlgos[0] {
  291. // other side sent a kex message for the wrong algorithm,
  292. // which we have to ignore.
  293. if _, err := t.conn.readPacket(); err != nil {
  294. return err
  295. }
  296. }
  297. kex, ok := kexAlgoMap[algs.kex]
  298. if !ok {
  299. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
  300. }
  301. var result *kexResult
  302. if len(t.hostKeys) > 0 {
  303. result, err = t.server(kex, algs, &magics)
  304. } else {
  305. result, err = t.client(kex, algs, &magics)
  306. }
  307. if err != nil {
  308. return err
  309. }
  310. t.conn.prepareKeyChange(algs, result)
  311. if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
  312. return err
  313. }
  314. if packet, err := t.conn.readPacket(); err != nil {
  315. return err
  316. } else if packet[0] != msgNewKeys {
  317. return unexpectedMessageError(msgNewKeys, packet[0])
  318. }
  319. return nil
  320. }
  321. func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  322. var hostKey Signer
  323. for _, k := range t.hostKeys {
  324. if algs.hostKey == k.PublicKey().Type() {
  325. hostKey = k
  326. }
  327. }
  328. r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
  329. return r, err
  330. }
  331. func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  332. result, err := kex.Client(t.conn, t.config.Rand, magics)
  333. if err != nil {
  334. return nil, err
  335. }
  336. hostKey, err := ParsePublicKey(result.HostKey)
  337. if err != nil {
  338. return nil, err
  339. }
  340. if err := verifyHostKeySignature(hostKey, result); err != nil {
  341. return nil, err
  342. }
  343. if t.hostKeyCallback != nil {
  344. err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
  345. if err != nil {
  346. return nil, err
  347. }
  348. }
  349. return result, nil
  350. }