transport.go 7.6 KB

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