cipher.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. // insecure cipher, see http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf
  99. // uncomment below to enable it.
  100. // aes128cbcID: {16, aes.BlockSize, 0, nil},
  101. }
  102. // prefixLen is the length of the packet prefix that contains the packet length
  103. // and number of padding bytes.
  104. const prefixLen = 5
  105. // streamPacketCipher is a packetCipher using a stream cipher.
  106. type streamPacketCipher struct {
  107. mac hash.Hash
  108. cipher cipher.Stream
  109. // The following members are to avoid per-packet allocations.
  110. prefix [prefixLen]byte
  111. seqNumBytes [4]byte
  112. padding [2 * packetSizeMultiple]byte
  113. packetData []byte
  114. macResult []byte
  115. }
  116. // readPacket reads and decrypt a single packet from the reader argument.
  117. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  118. if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
  119. return nil, err
  120. }
  121. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  122. length := binary.BigEndian.Uint32(s.prefix[0:4])
  123. paddingLength := uint32(s.prefix[4])
  124. var macSize uint32
  125. if s.mac != nil {
  126. s.mac.Reset()
  127. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  128. s.mac.Write(s.seqNumBytes[:])
  129. s.mac.Write(s.prefix[:])
  130. macSize = uint32(s.mac.Size())
  131. }
  132. if length <= paddingLength+1 {
  133. return nil, errors.New("ssh: invalid packet length, packet too small")
  134. }
  135. if length > maxPacket {
  136. return nil, errors.New("ssh: invalid packet length, packet too large")
  137. }
  138. // the maxPacket check above ensures that length-1+macSize
  139. // does not overflow.
  140. if uint32(cap(s.packetData)) < length-1+macSize {
  141. s.packetData = make([]byte, length-1+macSize)
  142. } else {
  143. s.packetData = s.packetData[:length-1+macSize]
  144. }
  145. if _, err := io.ReadFull(r, s.packetData); err != nil {
  146. return nil, err
  147. }
  148. mac := s.packetData[length-1:]
  149. data := s.packetData[:length-1]
  150. s.cipher.XORKeyStream(data, data)
  151. if s.mac != nil {
  152. s.mac.Write(data)
  153. s.macResult = s.mac.Sum(s.macResult[:0])
  154. if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
  155. return nil, errors.New("ssh: MAC failure")
  156. }
  157. }
  158. return s.packetData[:length-paddingLength-1], nil
  159. }
  160. // writePacket encrypts and sends a packet of data to the writer argument
  161. func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  162. if len(packet) > maxPacket {
  163. return errors.New("ssh: packet too large")
  164. }
  165. paddingLength := packetSizeMultiple - (prefixLen+len(packet))%packetSizeMultiple
  166. if paddingLength < 4 {
  167. paddingLength += packetSizeMultiple
  168. }
  169. length := len(packet) + 1 + paddingLength
  170. binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
  171. s.prefix[4] = byte(paddingLength)
  172. padding := s.padding[:paddingLength]
  173. if _, err := io.ReadFull(rand, padding); err != nil {
  174. return err
  175. }
  176. if s.mac != nil {
  177. s.mac.Reset()
  178. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  179. s.mac.Write(s.seqNumBytes[:])
  180. s.mac.Write(s.prefix[:])
  181. s.mac.Write(packet)
  182. s.mac.Write(padding)
  183. }
  184. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  185. s.cipher.XORKeyStream(packet, packet)
  186. s.cipher.XORKeyStream(padding, padding)
  187. if _, err := w.Write(s.prefix[:]); err != nil {
  188. return err
  189. }
  190. if _, err := w.Write(packet); err != nil {
  191. return err
  192. }
  193. if _, err := w.Write(padding); err != nil {
  194. return err
  195. }
  196. if s.mac != nil {
  197. s.macResult = s.mac.Sum(s.macResult[:0])
  198. if _, err := w.Write(s.macResult); err != nil {
  199. return err
  200. }
  201. }
  202. return nil
  203. }
  204. type gcmCipher struct {
  205. aead cipher.AEAD
  206. prefix [4]byte
  207. iv []byte
  208. buf []byte
  209. }
  210. func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) {
  211. c, err := aes.NewCipher(key)
  212. if err != nil {
  213. return nil, err
  214. }
  215. aead, err := cipher.NewGCM(c)
  216. if err != nil {
  217. return nil, err
  218. }
  219. return &gcmCipher{
  220. aead: aead,
  221. iv: iv,
  222. }, nil
  223. }
  224. const gcmTagSize = 16
  225. func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  226. // Pad out to multiple of 16 bytes. This is different from the
  227. // stream cipher because that encrypts the length too.
  228. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple)
  229. if padding < 4 {
  230. padding += packetSizeMultiple
  231. }
  232. length := uint32(len(packet) + int(padding) + 1)
  233. binary.BigEndian.PutUint32(c.prefix[:], length)
  234. if _, err := w.Write(c.prefix[:]); err != nil {
  235. return err
  236. }
  237. if cap(c.buf) < int(length) {
  238. c.buf = make([]byte, length)
  239. } else {
  240. c.buf = c.buf[:length]
  241. }
  242. c.buf[0] = padding
  243. copy(c.buf[1:], packet)
  244. if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil {
  245. return err
  246. }
  247. c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:])
  248. if _, err := w.Write(c.buf); err != nil {
  249. return err
  250. }
  251. c.incIV()
  252. return nil
  253. }
  254. func (c *gcmCipher) incIV() {
  255. for i := 4 + 7; i >= 4; i-- {
  256. c.iv[i]++
  257. if c.iv[i] != 0 {
  258. break
  259. }
  260. }
  261. }
  262. func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  263. if _, err := io.ReadFull(r, c.prefix[:]); err != nil {
  264. return nil, err
  265. }
  266. length := binary.BigEndian.Uint32(c.prefix[:])
  267. if length > maxPacket {
  268. return nil, errors.New("ssh: max packet length exceeded.")
  269. }
  270. if cap(c.buf) < int(length+gcmTagSize) {
  271. c.buf = make([]byte, length+gcmTagSize)
  272. } else {
  273. c.buf = c.buf[:length+gcmTagSize]
  274. }
  275. if _, err := io.ReadFull(r, c.buf); err != nil {
  276. return nil, err
  277. }
  278. plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:])
  279. if err != nil {
  280. return nil, err
  281. }
  282. c.incIV()
  283. padding := plain[0]
  284. if padding < 4 || padding >= 20 {
  285. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  286. }
  287. if int(padding+1) >= len(plain) {
  288. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  289. }
  290. plain = plain[1 : length-uint32(padding)]
  291. return plain, nil
  292. }
  293. // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1
  294. type cbcCipher struct {
  295. mac hash.Hash
  296. decrypter cipher.BlockMode
  297. encrypter cipher.BlockMode
  298. // The following members are to avoid per-packet allocations.
  299. seqNumBytes [4]byte
  300. packetData []byte
  301. macResult []byte
  302. }
  303. func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  304. c, err := aes.NewCipher(key)
  305. if err != nil {
  306. return nil, err
  307. }
  308. return &cbcCipher{
  309. mac: macModes[algs.MAC].new(macKey),
  310. decrypter: cipher.NewCBCDecrypter(c, iv),
  311. encrypter: cipher.NewCBCEncrypter(c, iv),
  312. packetData: make([]byte, 1024),
  313. }, nil
  314. }
  315. func maxUInt32(a, b int) uint32 {
  316. if a > b {
  317. return uint32(a)
  318. }
  319. return uint32(b)
  320. }
  321. const (
  322. cbcMinPacketSizeMultiple = 8
  323. cbcMinPacketSize = 16
  324. cbcMinPaddingSize = 4
  325. )
  326. func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  327. blockSize := c.decrypter.BlockSize()
  328. // Read the header, which will include some of the subsequent data in the
  329. // case of block ciphers - this is copied back to the payload later.
  330. // How many bytes of payload/padding will be read with this first read.
  331. firstBlockLength := (prefixLen + blockSize - 1) / blockSize * blockSize
  332. firstBlock := c.packetData[:firstBlockLength]
  333. if _, err := io.ReadFull(r, firstBlock); err != nil {
  334. return nil, err
  335. }
  336. c.decrypter.CryptBlocks(firstBlock, firstBlock)
  337. length := binary.BigEndian.Uint32(firstBlock[:4])
  338. if length > maxPacket {
  339. return nil, errors.New("ssh: packet too large")
  340. }
  341. if length+4 < maxUInt32(cbcMinPacketSize, blockSize) {
  342. // The minimum size of a packet is 16 (or the cipher block size, whichever
  343. // is larger) bytes.
  344. return nil, errors.New("ssh: packet too small")
  345. }
  346. // The length of the packet (including the length field but not the MAC) must
  347. // be a multiple of the block size or 8, whichever is larger.
  348. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 {
  349. return nil, errors.New("ssh: invalid packet length multiple")
  350. }
  351. paddingLength := uint32(firstBlock[4])
  352. if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 {
  353. return nil, errors.New("ssh: invalid packet length")
  354. }
  355. var macSize uint32
  356. if c.mac != nil {
  357. macSize = uint32(c.mac.Size())
  358. }
  359. // Positions within the c.packetData buffer:
  360. macStart := 4 + length
  361. paddingStart := macStart - paddingLength
  362. // Entire packet size, starting before length, ending at end of mac.
  363. entirePacketSize := macStart + macSize
  364. // Ensure c.packetData is large enough for the entire packet data.
  365. if uint32(cap(c.packetData)) < entirePacketSize {
  366. // Still need to upsize and copy, but this should be rare at runtime, only
  367. // on upsizing the packetData buffer.
  368. c.packetData = make([]byte, entirePacketSize)
  369. copy(c.packetData, firstBlock)
  370. } else {
  371. c.packetData = c.packetData[:entirePacketSize]
  372. }
  373. if _, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil {
  374. return nil, err
  375. }
  376. remainingCrypted := c.packetData[firstBlockLength:macStart]
  377. c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted)
  378. mac := c.packetData[macStart:]
  379. if c.mac != nil {
  380. c.mac.Reset()
  381. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  382. c.mac.Write(c.seqNumBytes[:])
  383. c.mac.Write(c.packetData[:macStart])
  384. c.macResult = c.mac.Sum(c.macResult[:0])
  385. if subtle.ConstantTimeCompare(c.macResult, mac) != 1 {
  386. return nil, errors.New("ssh: MAC failure")
  387. }
  388. }
  389. return c.packetData[prefixLen:paddingStart], nil
  390. }
  391. func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  392. effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize())
  393. // Length of encrypted portion of the packet (header, payload, padding).
  394. // Enforce minimum padding and packet size.
  395. encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
  396. // Enforce block size.
  397. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
  398. length := encLength - 4
  399. paddingLength := int(length) - (1 + len(packet))
  400. var macSize uint32
  401. if c.mac != nil {
  402. macSize = uint32(c.mac.Size())
  403. }
  404. // Overall buffer contains: header, payload, padding, mac.
  405. // Space for the MAC is reserved in the capacity but not the slice length.
  406. bufferSize := encLength + macSize
  407. if uint32(cap(c.packetData)) < bufferSize {
  408. c.packetData = make([]byte, encLength, bufferSize)
  409. } else {
  410. c.packetData = c.packetData[:encLength]
  411. }
  412. p := c.packetData
  413. // Packet header.
  414. binary.BigEndian.PutUint32(p, length)
  415. p = p[4:]
  416. p[0] = byte(paddingLength)
  417. // Payload.
  418. p = p[1:]
  419. copy(p, packet)
  420. // Padding.
  421. p = p[len(packet):]
  422. if _, err := io.ReadFull(rand, p); err != nil {
  423. return err
  424. }
  425. if c.mac != nil {
  426. c.mac.Reset()
  427. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  428. c.mac.Write(c.seqNumBytes[:])
  429. c.mac.Write(c.packetData)
  430. // The MAC is now appended into the capacity reserved for it earlier.
  431. c.packetData = c.mac.Sum(c.packetData)
  432. }
  433. c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength])
  434. if _, err := w.Write(c.packetData); err != nil {
  435. return err
  436. }
  437. return nil
  438. }