cipher.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/aes"
  7. "crypto/cipher"
  8. "crypto/rc4"
  9. "crypto/subtle"
  10. "encoding/binary"
  11. "errors"
  12. "fmt"
  13. "hash"
  14. "io"
  15. )
  16. const (
  17. packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher.
  18. // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations
  19. // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC
  20. // indicates implementations SHOULD be able to handle larger packet sizes, but then
  21. // waffles on about reasonable limits.
  22. //
  23. // OpenSSH caps their maxPacket at 256kB so we choose to do
  24. // the same. maxPacket is also used to ensure that uint32
  25. // length fields do not overflow, so it should remain well
  26. // below 4G.
  27. maxPacket = 256 * 1024
  28. )
  29. // noneCipher implements cipher.Stream and provides no encryption. It is used
  30. // by the transport before the first key-exchange.
  31. type noneCipher struct{}
  32. func (c noneCipher) XORKeyStream(dst, src []byte) {
  33. copy(dst, src)
  34. }
  35. func newAESCTR(key, iv []byte) (cipher.Stream, error) {
  36. c, err := aes.NewCipher(key)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return cipher.NewCTR(c, iv), nil
  41. }
  42. func newRC4(key, iv []byte) (cipher.Stream, error) {
  43. return rc4.NewCipher(key)
  44. }
  45. type streamCipherMode struct {
  46. keySize int
  47. ivSize int
  48. skip int
  49. createFunc func(key, iv []byte) (cipher.Stream, error)
  50. }
  51. func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) {
  52. if len(key) < c.keySize {
  53. panic("ssh: key length too small for cipher")
  54. }
  55. if len(iv) < c.ivSize {
  56. panic("ssh: iv too small for cipher")
  57. }
  58. stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize])
  59. if err != nil {
  60. return nil, err
  61. }
  62. var streamDump []byte
  63. if c.skip > 0 {
  64. streamDump = make([]byte, 512)
  65. }
  66. for remainingToDump := c.skip; remainingToDump > 0; {
  67. dumpThisTime := remainingToDump
  68. if dumpThisTime > len(streamDump) {
  69. dumpThisTime = len(streamDump)
  70. }
  71. stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime])
  72. remainingToDump -= dumpThisTime
  73. }
  74. return stream, nil
  75. }
  76. // cipherModes documents properties of supported ciphers. Ciphers not included
  77. // are not supported and will not be negotiated, even if explicitly requested in
  78. // ClientConfig.Crypto.Ciphers.
  79. var cipherModes = map[string]*streamCipherMode{
  80. // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms
  81. // are defined in the order specified in the RFC.
  82. "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR},
  83. "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR},
  84. "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR},
  85. // Ciphers from RFC4345, which introduces security-improved arcfour ciphers.
  86. // They are defined in the order specified in the RFC.
  87. "arcfour128": {16, 0, 1536, newRC4},
  88. "arcfour256": {32, 0, 1536, newRC4},
  89. // AES-GCM is not a stream cipher, so it is constructed with a
  90. // special case. If we add any more non-stream ciphers, we
  91. // should invest a cleaner way to do this.
  92. gcmCipherID: {16, 12, 0, nil},
  93. }
  94. // prefixLen is the length of the packet prefix that contains the packet length
  95. // and number of padding bytes.
  96. const prefixLen = 5
  97. // streamPacketCipher is a packetCipher using a stream cipher.
  98. type streamPacketCipher struct {
  99. mac hash.Hash
  100. cipher cipher.Stream
  101. // The following members are to avoid per-packet allocations.
  102. prefix [prefixLen]byte
  103. seqNumBytes [4]byte
  104. padding [2 * packetSizeMultiple]byte
  105. packetData []byte
  106. macResult []byte
  107. }
  108. // readPacket reads and decrypt a single packet from the reader argument.
  109. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  110. if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
  111. return nil, err
  112. }
  113. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  114. length := binary.BigEndian.Uint32(s.prefix[0:4])
  115. paddingLength := uint32(s.prefix[4])
  116. var macSize uint32
  117. if s.mac != nil {
  118. s.mac.Reset()
  119. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  120. s.mac.Write(s.seqNumBytes[:])
  121. s.mac.Write(s.prefix[:])
  122. macSize = uint32(s.mac.Size())
  123. }
  124. if length <= paddingLength+1 {
  125. return nil, errors.New("ssh: invalid packet length, packet too small")
  126. }
  127. if length > maxPacket {
  128. return nil, errors.New("ssh: invalid packet length, packet too large")
  129. }
  130. // the maxPacket check above ensures that length-1+macSize
  131. // does not overflow.
  132. if uint32(cap(s.packetData)) < length-1+macSize {
  133. s.packetData = make([]byte, length-1+macSize)
  134. } else {
  135. s.packetData = s.packetData[:length-1+macSize]
  136. }
  137. if _, err := io.ReadFull(r, s.packetData); err != nil {
  138. return nil, err
  139. }
  140. mac := s.packetData[length-1:]
  141. data := s.packetData[:length-1]
  142. s.cipher.XORKeyStream(data, data)
  143. if s.mac != nil {
  144. s.mac.Write(data)
  145. s.macResult = s.mac.Sum(s.macResult[:0])
  146. if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
  147. return nil, errors.New("ssh: MAC failure")
  148. }
  149. }
  150. return s.packetData[:length-paddingLength-1], nil
  151. }
  152. // writePacket encrypts and sends a packet of data to the writer argument
  153. func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  154. if len(packet) > maxPacket {
  155. return errors.New("ssh: packet too large")
  156. }
  157. paddingLength := packetSizeMultiple - (prefixLen+len(packet))%packetSizeMultiple
  158. if paddingLength < 4 {
  159. paddingLength += packetSizeMultiple
  160. }
  161. length := len(packet) + 1 + paddingLength
  162. binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
  163. s.prefix[4] = byte(paddingLength)
  164. padding := s.padding[:paddingLength]
  165. if _, err := io.ReadFull(rand, padding); err != nil {
  166. return err
  167. }
  168. if s.mac != nil {
  169. s.mac.Reset()
  170. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  171. s.mac.Write(s.seqNumBytes[:])
  172. s.mac.Write(s.prefix[:])
  173. s.mac.Write(packet)
  174. s.mac.Write(padding)
  175. }
  176. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  177. s.cipher.XORKeyStream(packet, packet)
  178. s.cipher.XORKeyStream(padding, padding)
  179. if _, err := w.Write(s.prefix[:]); err != nil {
  180. return err
  181. }
  182. if _, err := w.Write(packet); err != nil {
  183. return err
  184. }
  185. if _, err := w.Write(padding); err != nil {
  186. return err
  187. }
  188. if s.mac != nil {
  189. s.macResult = s.mac.Sum(s.macResult[:0])
  190. if _, err := w.Write(s.macResult); err != nil {
  191. return err
  192. }
  193. }
  194. return nil
  195. }
  196. type gcmCipher struct {
  197. aead cipher.AEAD
  198. prefix [4]byte
  199. iv []byte
  200. buf []byte
  201. }
  202. func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) {
  203. c, err := aes.NewCipher(key)
  204. if err != nil {
  205. return nil, err
  206. }
  207. aead, err := cipher.NewGCM(c)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return &gcmCipher{
  212. aead: aead,
  213. iv: iv,
  214. }, nil
  215. }
  216. const gcmTagSize = 16
  217. func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  218. // Pad out to multiple of 16 bytes. This is different from the
  219. // stream cipher because that encrypts the length too.
  220. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple)
  221. if padding < 4 {
  222. padding += packetSizeMultiple
  223. }
  224. length := uint32(len(packet) + int(padding) + 1)
  225. binary.BigEndian.PutUint32(c.prefix[:], length)
  226. if _, err := w.Write(c.prefix[:]); err != nil {
  227. return err
  228. }
  229. if cap(c.buf) < int(length) {
  230. c.buf = make([]byte, length)
  231. } else {
  232. c.buf = c.buf[:length]
  233. }
  234. c.buf[0] = padding
  235. copy(c.buf[1:], packet)
  236. if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil {
  237. return err
  238. }
  239. c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:])
  240. if _, err := w.Write(c.buf); err != nil {
  241. return err
  242. }
  243. c.incIV()
  244. return nil
  245. }
  246. func (c *gcmCipher) incIV() {
  247. for i := 4 + 7; i >= 4; i-- {
  248. c.iv[i]++
  249. if c.iv[i] != 0 {
  250. break
  251. }
  252. }
  253. }
  254. func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  255. if _, err := io.ReadFull(r, c.prefix[:]); err != nil {
  256. return nil, err
  257. }
  258. length := binary.BigEndian.Uint32(c.prefix[:])
  259. if length > maxPacket {
  260. return nil, errors.New("ssh: max packet length exceeded.")
  261. }
  262. if cap(c.buf) < int(length+gcmTagSize) {
  263. c.buf = make([]byte, length+gcmTagSize)
  264. } else {
  265. c.buf = c.buf[:length+gcmTagSize]
  266. }
  267. if _, err := io.ReadFull(r, c.buf); err != nil {
  268. return nil, err
  269. }
  270. plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:])
  271. if err != nil {
  272. return nil, err
  273. }
  274. c.incIV()
  275. padding := plain[0]
  276. if padding < 4 || padding >= 20 {
  277. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  278. }
  279. if int(padding+1) >= len(plain) {
  280. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  281. }
  282. plain = plain[1 : length-uint32(padding)]
  283. return plain, nil
  284. }