transport.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "bufio"
  7. "crypto"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "encoding/binary"
  11. "errors"
  12. "hash"
  13. "io"
  14. "net"
  15. "sync"
  16. )
  17. const (
  18. packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher.
  19. )
  20. // conn represents an ssh transport that implements packet based
  21. // operations.
  22. type conn interface {
  23. // Encrypt and send a packet of data to the remote peer.
  24. writePacket(packet []byte) error
  25. // Close closes the connection.
  26. Close() error
  27. }
  28. // transport represents the SSH connection to the remote peer.
  29. type transport struct {
  30. reader
  31. writer
  32. net.Conn
  33. }
  34. // reader represents the incoming connection state.
  35. type reader struct {
  36. io.Reader
  37. common
  38. }
  39. // writer represents the outgoing connection state.
  40. type writer struct {
  41. sync.Mutex // protects writer.Writer from concurrent writes
  42. *bufio.Writer
  43. rand io.Reader
  44. common
  45. }
  46. // common represents the cipher state needed to process messages in a single
  47. // direction.
  48. type common struct {
  49. seqNum uint32
  50. mac hash.Hash
  51. cipher cipher.Stream
  52. cipherAlgo string
  53. macAlgo string
  54. compressionAlgo string
  55. }
  56. // Read and decrypt a single packet from the remote peer.
  57. func (r *reader) readOnePacket() ([]byte, error) {
  58. var lengthBytes = make([]byte, 5)
  59. var macSize uint32
  60. if _, err := io.ReadFull(r, lengthBytes); err != nil {
  61. return nil, err
  62. }
  63. r.cipher.XORKeyStream(lengthBytes, lengthBytes)
  64. if r.mac != nil {
  65. r.mac.Reset()
  66. seqNumBytes := []byte{
  67. byte(r.seqNum >> 24),
  68. byte(r.seqNum >> 16),
  69. byte(r.seqNum >> 8),
  70. byte(r.seqNum),
  71. }
  72. r.mac.Write(seqNumBytes)
  73. r.mac.Write(lengthBytes)
  74. macSize = uint32(r.mac.Size())
  75. }
  76. length := binary.BigEndian.Uint32(lengthBytes[0:4])
  77. paddingLength := uint32(lengthBytes[4])
  78. if length <= paddingLength+1 {
  79. return nil, errors.New("ssh: invalid packet length")
  80. }
  81. packet := make([]byte, length-1+macSize)
  82. if _, err := io.ReadFull(r, packet); err != nil {
  83. return nil, err
  84. }
  85. mac := packet[length-1:]
  86. r.cipher.XORKeyStream(packet, packet[:length-1])
  87. if r.mac != nil {
  88. r.mac.Write(packet[:length-1])
  89. if subtle.ConstantTimeCompare(r.mac.Sum(nil), mac) != 1 {
  90. return nil, errors.New("ssh: MAC failure")
  91. }
  92. }
  93. r.seqNum++
  94. return packet[:length-paddingLength-1], nil
  95. }
  96. // Read and decrypt next packet discarding debug and noop messages.
  97. func (t *transport) readPacket() ([]byte, error) {
  98. for {
  99. packet, err := t.readOnePacket()
  100. if err != nil {
  101. return nil, err
  102. }
  103. if len(packet) == 0 {
  104. return nil, errors.New("ssh: zero length packet")
  105. }
  106. if packet[0] != msgIgnore && packet[0] != msgDebug {
  107. return packet, nil
  108. }
  109. }
  110. panic("unreachable")
  111. }
  112. // Encrypt and send a packet of data to the remote peer.
  113. func (w *writer) writePacket(packet []byte) error {
  114. w.Mutex.Lock()
  115. defer w.Mutex.Unlock()
  116. paddingLength := packetSizeMultiple - (5+len(packet))%packetSizeMultiple
  117. if paddingLength < 4 {
  118. paddingLength += packetSizeMultiple
  119. }
  120. length := len(packet) + 1 + paddingLength
  121. lengthBytes := []byte{
  122. byte(length >> 24),
  123. byte(length >> 16),
  124. byte(length >> 8),
  125. byte(length),
  126. byte(paddingLength),
  127. }
  128. padding := make([]byte, paddingLength)
  129. _, err := io.ReadFull(w.rand, padding)
  130. if err != nil {
  131. return err
  132. }
  133. if w.mac != nil {
  134. w.mac.Reset()
  135. seqNumBytes := []byte{
  136. byte(w.seqNum >> 24),
  137. byte(w.seqNum >> 16),
  138. byte(w.seqNum >> 8),
  139. byte(w.seqNum),
  140. }
  141. w.mac.Write(seqNumBytes)
  142. w.mac.Write(lengthBytes)
  143. w.mac.Write(packet)
  144. w.mac.Write(padding)
  145. }
  146. // TODO(dfc) lengthBytes, packet and padding should be
  147. // subslices of a single buffer
  148. w.cipher.XORKeyStream(lengthBytes, lengthBytes)
  149. w.cipher.XORKeyStream(packet, packet)
  150. w.cipher.XORKeyStream(padding, padding)
  151. if _, err := w.Write(lengthBytes); err != nil {
  152. return err
  153. }
  154. if _, err := w.Write(packet); err != nil {
  155. return err
  156. }
  157. if _, err := w.Write(padding); err != nil {
  158. return err
  159. }
  160. if w.mac != nil {
  161. if _, err := w.Write(w.mac.Sum(nil)); err != nil {
  162. return err
  163. }
  164. }
  165. w.seqNum++
  166. return w.Flush()
  167. }
  168. // Send a message to the remote peer
  169. func (t *transport) sendMessage(typ uint8, msg interface{}) error {
  170. packet := marshal(typ, msg)
  171. return t.writePacket(packet)
  172. }
  173. func newTransport(conn net.Conn, rand io.Reader) *transport {
  174. return &transport{
  175. reader: reader{
  176. Reader: bufio.NewReader(conn),
  177. common: common{
  178. cipher: noneCipher{},
  179. },
  180. },
  181. writer: writer{
  182. Writer: bufio.NewWriter(conn),
  183. rand: rand,
  184. common: common{
  185. cipher: noneCipher{},
  186. },
  187. },
  188. Conn: conn,
  189. }
  190. }
  191. type direction struct {
  192. ivTag []byte
  193. keyTag []byte
  194. macKeyTag []byte
  195. }
  196. // TODO(dfc) can this be made a constant ?
  197. var (
  198. serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}}
  199. clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}}
  200. )
  201. // setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
  202. // described in RFC 4253, section 6.4. direction should either be serverKeys
  203. // (to setup server->client keys) or clientKeys (for client->server keys).
  204. func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error {
  205. cipherMode := cipherModes[c.cipherAlgo]
  206. macMode := macModes[c.macAlgo]
  207. iv := make([]byte, cipherMode.ivSize)
  208. key := make([]byte, cipherMode.keySize)
  209. macKey := make([]byte, macMode.keySize)
  210. h := hashFunc.New()
  211. generateKeyMaterial(iv, d.ivTag, K, H, sessionId, h)
  212. generateKeyMaterial(key, d.keyTag, K, H, sessionId, h)
  213. generateKeyMaterial(macKey, d.macKeyTag, K, H, sessionId, h)
  214. c.mac = macMode.new(macKey)
  215. var err error
  216. c.cipher, err = cipherMode.createCipher(key, iv)
  217. return err
  218. }
  219. // generateKeyMaterial fills out with key material generated from tag, K, H
  220. // and sessionId, as specified in RFC 4253, section 7.2.
  221. func generateKeyMaterial(out, tag []byte, K, H, sessionId []byte, h hash.Hash) {
  222. var digestsSoFar []byte
  223. for len(out) > 0 {
  224. h.Reset()
  225. h.Write(K)
  226. h.Write(H)
  227. if len(digestsSoFar) == 0 {
  228. h.Write(tag)
  229. h.Write(sessionId)
  230. } else {
  231. h.Write(digestsSoFar)
  232. }
  233. digest := h.Sum(nil)
  234. n := copy(out, digest)
  235. out = out[n:]
  236. if len(out) > 0 {
  237. digestsSoFar = append(digestsSoFar, digest...)
  238. }
  239. }
  240. }
  241. // maxVersionStringBytes is the maximum number of bytes that we'll accept as a
  242. // version string. In the event that the client is talking a different protocol
  243. // we need to set a limit otherwise we will keep using more and more memory
  244. // while searching for the end of the version handshake.
  245. const maxVersionStringBytes = 1024
  246. // Read version string as specified by RFC 4253, section 4.2.
  247. func readVersion(r io.Reader) ([]byte, error) {
  248. versionString := make([]byte, 0, 64)
  249. var ok bool
  250. var buf [1]byte
  251. forEachByte:
  252. for len(versionString) < maxVersionStringBytes {
  253. _, err := io.ReadFull(r, buf[:])
  254. if err != nil {
  255. return nil, err
  256. }
  257. // The RFC says that the version should be terminated with \r\n
  258. // but several SSH servers actually only send a \n.
  259. if buf[0] == '\n' {
  260. ok = true
  261. break forEachByte
  262. }
  263. versionString = append(versionString, buf[0])
  264. }
  265. if !ok {
  266. return nil, errors.New("ssh: failed to read version string")
  267. }
  268. // There might be a '\r' on the end which we should remove.
  269. if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' {
  270. versionString = versionString[:len(versionString)-1]
  271. }
  272. return versionString, nil
  273. }