cipher.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol.
  90. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and
  91. // RC4) has problems with weak keys, and should be used with caution."
  92. // RFC4345 introduces improved versions of Arcfour.
  93. "arcfour": {16, 0, 0, newRC4},
  94. // AES-GCM is not a stream cipher, so it is constructed with a
  95. // special case. If we add any more non-stream ciphers, we
  96. // should invest a cleaner way to do this.
  97. gcmCipherID: {16, 12, 0, nil},
  98. }
  99. // prefixLen is the length of the packet prefix that contains the packet length
  100. // and number of padding bytes.
  101. const prefixLen = 5
  102. // streamPacketCipher is a packetCipher using a stream cipher.
  103. type streamPacketCipher struct {
  104. mac hash.Hash
  105. cipher cipher.Stream
  106. // The following members are to avoid per-packet allocations.
  107. prefix [prefixLen]byte
  108. seqNumBytes [4]byte
  109. padding [2 * packetSizeMultiple]byte
  110. packetData []byte
  111. macResult []byte
  112. }
  113. // readPacket reads and decrypt a single packet from the reader argument.
  114. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  115. if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
  116. return nil, err
  117. }
  118. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  119. length := binary.BigEndian.Uint32(s.prefix[0:4])
  120. paddingLength := uint32(s.prefix[4])
  121. var macSize uint32
  122. if s.mac != nil {
  123. s.mac.Reset()
  124. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  125. s.mac.Write(s.seqNumBytes[:])
  126. s.mac.Write(s.prefix[:])
  127. macSize = uint32(s.mac.Size())
  128. }
  129. if length <= paddingLength+1 {
  130. return nil, errors.New("ssh: invalid packet length, packet too small")
  131. }
  132. if length > maxPacket {
  133. return nil, errors.New("ssh: invalid packet length, packet too large")
  134. }
  135. // the maxPacket check above ensures that length-1+macSize
  136. // does not overflow.
  137. if uint32(cap(s.packetData)) < length-1+macSize {
  138. s.packetData = make([]byte, length-1+macSize)
  139. } else {
  140. s.packetData = s.packetData[:length-1+macSize]
  141. }
  142. if _, err := io.ReadFull(r, s.packetData); err != nil {
  143. return nil, err
  144. }
  145. mac := s.packetData[length-1:]
  146. data := s.packetData[:length-1]
  147. s.cipher.XORKeyStream(data, data)
  148. if s.mac != nil {
  149. s.mac.Write(data)
  150. s.macResult = s.mac.Sum(s.macResult[:0])
  151. if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
  152. return nil, errors.New("ssh: MAC failure")
  153. }
  154. }
  155. return s.packetData[:length-paddingLength-1], nil
  156. }
  157. // writePacket encrypts and sends a packet of data to the writer argument
  158. func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  159. if len(packet) > maxPacket {
  160. return errors.New("ssh: packet too large")
  161. }
  162. paddingLength := packetSizeMultiple - (prefixLen+len(packet))%packetSizeMultiple
  163. if paddingLength < 4 {
  164. paddingLength += packetSizeMultiple
  165. }
  166. length := len(packet) + 1 + paddingLength
  167. binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
  168. s.prefix[4] = byte(paddingLength)
  169. padding := s.padding[:paddingLength]
  170. if _, err := io.ReadFull(rand, padding); err != nil {
  171. return err
  172. }
  173. if s.mac != nil {
  174. s.mac.Reset()
  175. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  176. s.mac.Write(s.seqNumBytes[:])
  177. s.mac.Write(s.prefix[:])
  178. s.mac.Write(packet)
  179. s.mac.Write(padding)
  180. }
  181. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  182. s.cipher.XORKeyStream(packet, packet)
  183. s.cipher.XORKeyStream(padding, padding)
  184. if _, err := w.Write(s.prefix[:]); err != nil {
  185. return err
  186. }
  187. if _, err := w.Write(packet); err != nil {
  188. return err
  189. }
  190. if _, err := w.Write(padding); err != nil {
  191. return err
  192. }
  193. if s.mac != nil {
  194. s.macResult = s.mac.Sum(s.macResult[:0])
  195. if _, err := w.Write(s.macResult); err != nil {
  196. return err
  197. }
  198. }
  199. return nil
  200. }
  201. type gcmCipher struct {
  202. aead cipher.AEAD
  203. prefix [4]byte
  204. iv []byte
  205. buf []byte
  206. }
  207. func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) {
  208. c, err := aes.NewCipher(key)
  209. if err != nil {
  210. return nil, err
  211. }
  212. aead, err := cipher.NewGCM(c)
  213. if err != nil {
  214. return nil, err
  215. }
  216. return &gcmCipher{
  217. aead: aead,
  218. iv: iv,
  219. }, nil
  220. }
  221. const gcmTagSize = 16
  222. func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  223. // Pad out to multiple of 16 bytes. This is different from the
  224. // stream cipher because that encrypts the length too.
  225. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple)
  226. if padding < 4 {
  227. padding += packetSizeMultiple
  228. }
  229. length := uint32(len(packet) + int(padding) + 1)
  230. binary.BigEndian.PutUint32(c.prefix[:], length)
  231. if _, err := w.Write(c.prefix[:]); err != nil {
  232. return err
  233. }
  234. if cap(c.buf) < int(length) {
  235. c.buf = make([]byte, length)
  236. } else {
  237. c.buf = c.buf[:length]
  238. }
  239. c.buf[0] = padding
  240. copy(c.buf[1:], packet)
  241. if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil {
  242. return err
  243. }
  244. c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:])
  245. if _, err := w.Write(c.buf); err != nil {
  246. return err
  247. }
  248. c.incIV()
  249. return nil
  250. }
  251. func (c *gcmCipher) incIV() {
  252. for i := 4 + 7; i >= 4; i-- {
  253. c.iv[i]++
  254. if c.iv[i] != 0 {
  255. break
  256. }
  257. }
  258. }
  259. func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  260. if _, err := io.ReadFull(r, c.prefix[:]); err != nil {
  261. return nil, err
  262. }
  263. length := binary.BigEndian.Uint32(c.prefix[:])
  264. if length > maxPacket {
  265. return nil, errors.New("ssh: max packet length exceeded.")
  266. }
  267. if cap(c.buf) < int(length+gcmTagSize) {
  268. c.buf = make([]byte, length+gcmTagSize)
  269. } else {
  270. c.buf = c.buf[:length+gcmTagSize]
  271. }
  272. if _, err := io.ReadFull(r, c.buf); err != nil {
  273. return nil, err
  274. }
  275. plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:])
  276. if err != nil {
  277. return nil, err
  278. }
  279. c.incIV()
  280. padding := plain[0]
  281. if padding < 4 || padding >= 20 {
  282. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  283. }
  284. if int(padding+1) >= len(plain) {
  285. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  286. }
  287. plain = plain[1 : length-uint32(padding)]
  288. return plain, nil
  289. }