cipher.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. "io/ioutil"
  16. )
  17. const (
  18. packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher.
  19. // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations
  20. // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC
  21. // indicates implementations SHOULD be able to handle larger packet sizes, but then
  22. // waffles on about reasonable limits.
  23. //
  24. // OpenSSH caps their maxPacket at 256kB so we choose to do
  25. // the same. maxPacket is also used to ensure that uint32
  26. // length fields do not overflow, so it should remain well
  27. // below 4G.
  28. maxPacket = 256 * 1024
  29. )
  30. // noneCipher implements cipher.Stream and provides no encryption. It is used
  31. // by the transport before the first key-exchange.
  32. type noneCipher struct{}
  33. func (c noneCipher) XORKeyStream(dst, src []byte) {
  34. copy(dst, src)
  35. }
  36. func newAESCTR(key, iv []byte) (cipher.Stream, error) {
  37. c, err := aes.NewCipher(key)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return cipher.NewCTR(c, iv), nil
  42. }
  43. func newRC4(key, iv []byte) (cipher.Stream, error) {
  44. return rc4.NewCipher(key)
  45. }
  46. type streamCipherMode struct {
  47. keySize int
  48. ivSize int
  49. skip int
  50. createFunc func(key, iv []byte) (cipher.Stream, error)
  51. }
  52. func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) {
  53. if len(key) < c.keySize {
  54. panic("ssh: key length too small for cipher")
  55. }
  56. if len(iv) < c.ivSize {
  57. panic("ssh: iv too small for cipher")
  58. }
  59. stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize])
  60. if err != nil {
  61. return nil, err
  62. }
  63. var streamDump []byte
  64. if c.skip > 0 {
  65. streamDump = make([]byte, 512)
  66. }
  67. for remainingToDump := c.skip; remainingToDump > 0; {
  68. dumpThisTime := remainingToDump
  69. if dumpThisTime > len(streamDump) {
  70. dumpThisTime = len(streamDump)
  71. }
  72. stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime])
  73. remainingToDump -= dumpThisTime
  74. }
  75. return stream, nil
  76. }
  77. // cipherModes documents properties of supported ciphers. Ciphers not included
  78. // are not supported and will not be negotiated, even if explicitly requested in
  79. // ClientConfig.Crypto.Ciphers.
  80. var cipherModes = map[string]*streamCipherMode{
  81. // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms
  82. // are defined in the order specified in the RFC.
  83. "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR},
  84. "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR},
  85. "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR},
  86. // Ciphers from RFC4345, which introduces security-improved arcfour ciphers.
  87. // They are defined in the order specified in the RFC.
  88. "arcfour128": {16, 0, 1536, newRC4},
  89. "arcfour256": {32, 0, 1536, newRC4},
  90. // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol.
  91. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and
  92. // RC4) has problems with weak keys, and should be used with caution."
  93. // RFC4345 introduces improved versions of Arcfour.
  94. "arcfour": {16, 0, 0, newRC4},
  95. // AES-GCM is not a stream cipher, so it is constructed with a
  96. // special case. If we add any more non-stream ciphers, we
  97. // should invest a cleaner way to do this.
  98. gcmCipherID: {16, 12, 0, nil},
  99. // insecure cipher, see http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf
  100. // uncomment below to enable it.
  101. // aes128cbcID: {16, aes.BlockSize, 0, nil},
  102. }
  103. // prefixLen is the length of the packet prefix that contains the packet length
  104. // and number of padding bytes.
  105. const prefixLen = 5
  106. // streamPacketCipher is a packetCipher using a stream cipher.
  107. type streamPacketCipher struct {
  108. mac hash.Hash
  109. cipher cipher.Stream
  110. // The following members are to avoid per-packet allocations.
  111. prefix [prefixLen]byte
  112. seqNumBytes [4]byte
  113. padding [2 * packetSizeMultiple]byte
  114. packetData []byte
  115. macResult []byte
  116. }
  117. // readPacket reads and decrypt a single packet from the reader argument.
  118. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  119. if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
  120. return nil, err
  121. }
  122. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  123. length := binary.BigEndian.Uint32(s.prefix[0:4])
  124. paddingLength := uint32(s.prefix[4])
  125. var macSize uint32
  126. if s.mac != nil {
  127. s.mac.Reset()
  128. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  129. s.mac.Write(s.seqNumBytes[:])
  130. s.mac.Write(s.prefix[:])
  131. macSize = uint32(s.mac.Size())
  132. }
  133. if length <= paddingLength+1 {
  134. return nil, errors.New("ssh: invalid packet length, packet too small")
  135. }
  136. if length > maxPacket {
  137. return nil, errors.New("ssh: invalid packet length, packet too large")
  138. }
  139. // the maxPacket check above ensures that length-1+macSize
  140. // does not overflow.
  141. if uint32(cap(s.packetData)) < length-1+macSize {
  142. s.packetData = make([]byte, length-1+macSize)
  143. } else {
  144. s.packetData = s.packetData[:length-1+macSize]
  145. }
  146. if _, err := io.ReadFull(r, s.packetData); err != nil {
  147. return nil, err
  148. }
  149. mac := s.packetData[length-1:]
  150. data := s.packetData[:length-1]
  151. s.cipher.XORKeyStream(data, data)
  152. if s.mac != nil {
  153. s.mac.Write(data)
  154. s.macResult = s.mac.Sum(s.macResult[:0])
  155. if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
  156. return nil, errors.New("ssh: MAC failure")
  157. }
  158. }
  159. return s.packetData[:length-paddingLength-1], nil
  160. }
  161. // writePacket encrypts and sends a packet of data to the writer argument
  162. func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  163. if len(packet) > maxPacket {
  164. return errors.New("ssh: packet too large")
  165. }
  166. paddingLength := packetSizeMultiple - (prefixLen+len(packet))%packetSizeMultiple
  167. if paddingLength < 4 {
  168. paddingLength += packetSizeMultiple
  169. }
  170. length := len(packet) + 1 + paddingLength
  171. binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
  172. s.prefix[4] = byte(paddingLength)
  173. padding := s.padding[:paddingLength]
  174. if _, err := io.ReadFull(rand, padding); err != nil {
  175. return err
  176. }
  177. if s.mac != nil {
  178. s.mac.Reset()
  179. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  180. s.mac.Write(s.seqNumBytes[:])
  181. s.mac.Write(s.prefix[:])
  182. s.mac.Write(packet)
  183. s.mac.Write(padding)
  184. }
  185. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  186. s.cipher.XORKeyStream(packet, packet)
  187. s.cipher.XORKeyStream(padding, padding)
  188. if _, err := w.Write(s.prefix[:]); err != nil {
  189. return err
  190. }
  191. if _, err := w.Write(packet); err != nil {
  192. return err
  193. }
  194. if _, err := w.Write(padding); err != nil {
  195. return err
  196. }
  197. if s.mac != nil {
  198. s.macResult = s.mac.Sum(s.macResult[:0])
  199. if _, err := w.Write(s.macResult); err != nil {
  200. return err
  201. }
  202. }
  203. return nil
  204. }
  205. type gcmCipher struct {
  206. aead cipher.AEAD
  207. prefix [4]byte
  208. iv []byte
  209. buf []byte
  210. }
  211. func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) {
  212. c, err := aes.NewCipher(key)
  213. if err != nil {
  214. return nil, err
  215. }
  216. aead, err := cipher.NewGCM(c)
  217. if err != nil {
  218. return nil, err
  219. }
  220. return &gcmCipher{
  221. aead: aead,
  222. iv: iv,
  223. }, nil
  224. }
  225. const gcmTagSize = 16
  226. func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  227. // Pad out to multiple of 16 bytes. This is different from the
  228. // stream cipher because that encrypts the length too.
  229. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple)
  230. if padding < 4 {
  231. padding += packetSizeMultiple
  232. }
  233. length := uint32(len(packet) + int(padding) + 1)
  234. binary.BigEndian.PutUint32(c.prefix[:], length)
  235. if _, err := w.Write(c.prefix[:]); err != nil {
  236. return err
  237. }
  238. if cap(c.buf) < int(length) {
  239. c.buf = make([]byte, length)
  240. } else {
  241. c.buf = c.buf[:length]
  242. }
  243. c.buf[0] = padding
  244. copy(c.buf[1:], packet)
  245. if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil {
  246. return err
  247. }
  248. c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:])
  249. if _, err := w.Write(c.buf); err != nil {
  250. return err
  251. }
  252. c.incIV()
  253. return nil
  254. }
  255. func (c *gcmCipher) incIV() {
  256. for i := 4 + 7; i >= 4; i-- {
  257. c.iv[i]++
  258. if c.iv[i] != 0 {
  259. break
  260. }
  261. }
  262. }
  263. func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  264. if _, err := io.ReadFull(r, c.prefix[:]); err != nil {
  265. return nil, err
  266. }
  267. length := binary.BigEndian.Uint32(c.prefix[:])
  268. if length > maxPacket {
  269. return nil, errors.New("ssh: max packet length exceeded.")
  270. }
  271. if cap(c.buf) < int(length+gcmTagSize) {
  272. c.buf = make([]byte, length+gcmTagSize)
  273. } else {
  274. c.buf = c.buf[:length+gcmTagSize]
  275. }
  276. if _, err := io.ReadFull(r, c.buf); err != nil {
  277. return nil, err
  278. }
  279. plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:])
  280. if err != nil {
  281. return nil, err
  282. }
  283. c.incIV()
  284. padding := plain[0]
  285. if padding < 4 || padding >= 20 {
  286. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  287. }
  288. if int(padding+1) >= len(plain) {
  289. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  290. }
  291. plain = plain[1 : length-uint32(padding)]
  292. return plain, nil
  293. }
  294. // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1
  295. type cbcCipher struct {
  296. mac hash.Hash
  297. macSize uint32
  298. decrypter cipher.BlockMode
  299. encrypter cipher.BlockMode
  300. // The following members are to avoid per-packet allocations.
  301. seqNumBytes [4]byte
  302. packetData []byte
  303. macResult []byte
  304. // Amount of data we should still read to hide which
  305. // verification error triggered.
  306. oracleCamouflage uint32
  307. }
  308. func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  309. c, err := aes.NewCipher(key)
  310. if err != nil {
  311. return nil, err
  312. }
  313. cbc := &cbcCipher{
  314. mac: macModes[algs.MAC].new(macKey),
  315. decrypter: cipher.NewCBCDecrypter(c, iv),
  316. encrypter: cipher.NewCBCEncrypter(c, iv),
  317. packetData: make([]byte, 1024),
  318. }
  319. if cbc.mac != nil {
  320. cbc.macSize = uint32(cbc.mac.Size())
  321. }
  322. return cbc, nil
  323. }
  324. func maxUInt32(a, b int) uint32 {
  325. if a > b {
  326. return uint32(a)
  327. }
  328. return uint32(b)
  329. }
  330. const (
  331. cbcMinPacketSizeMultiple = 8
  332. cbcMinPacketSize = 16
  333. cbcMinPaddingSize = 4
  334. )
  335. // cbcError represents a verification error that may leak information.
  336. type cbcError string
  337. func (e cbcError) Error() string { return string(e) }
  338. func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  339. p, err := c.readPacketLeaky(seqNum, r)
  340. if err != nil {
  341. if _, ok := err.(cbcError); ok {
  342. // Verification error: read a fixed amount of
  343. // data, to make distinguishing between
  344. // failing MAC and failing length check more
  345. // difficult.
  346. io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage))
  347. }
  348. }
  349. return p, err
  350. }
  351. func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) {
  352. blockSize := c.decrypter.BlockSize()
  353. // Read the header, which will include some of the subsequent data in the
  354. // case of block ciphers - this is copied back to the payload later.
  355. // How many bytes of payload/padding will be read with this first read.
  356. firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize)
  357. firstBlock := c.packetData[:firstBlockLength]
  358. if _, err := io.ReadFull(r, firstBlock); err != nil {
  359. return nil, err
  360. }
  361. c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength
  362. c.decrypter.CryptBlocks(firstBlock, firstBlock)
  363. length := binary.BigEndian.Uint32(firstBlock[:4])
  364. if length > maxPacket {
  365. return nil, cbcError("ssh: packet too large")
  366. }
  367. if length+4 < maxUInt32(cbcMinPacketSize, blockSize) {
  368. // The minimum size of a packet is 16 (or the cipher block size, whichever
  369. // is larger) bytes.
  370. return nil, cbcError("ssh: packet too small")
  371. }
  372. // The length of the packet (including the length field but not the MAC) must
  373. // be a multiple of the block size or 8, whichever is larger.
  374. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 {
  375. return nil, cbcError("ssh: invalid packet length multiple")
  376. }
  377. paddingLength := uint32(firstBlock[4])
  378. if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 {
  379. return nil, cbcError("ssh: invalid packet length")
  380. }
  381. // Positions within the c.packetData buffer:
  382. macStart := 4 + length
  383. paddingStart := macStart - paddingLength
  384. // Entire packet size, starting before length, ending at end of mac.
  385. entirePacketSize := macStart + c.macSize
  386. // Ensure c.packetData is large enough for the entire packet data.
  387. if uint32(cap(c.packetData)) < entirePacketSize {
  388. // Still need to upsize and copy, but this should be rare at runtime, only
  389. // on upsizing the packetData buffer.
  390. c.packetData = make([]byte, entirePacketSize)
  391. copy(c.packetData, firstBlock)
  392. } else {
  393. c.packetData = c.packetData[:entirePacketSize]
  394. }
  395. if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil {
  396. return nil, err
  397. } else {
  398. c.oracleCamouflage -= uint32(n)
  399. }
  400. remainingCrypted := c.packetData[firstBlockLength:macStart]
  401. c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted)
  402. mac := c.packetData[macStart:]
  403. if c.mac != nil {
  404. c.mac.Reset()
  405. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  406. c.mac.Write(c.seqNumBytes[:])
  407. c.mac.Write(c.packetData[:macStart])
  408. c.macResult = c.mac.Sum(c.macResult[:0])
  409. if subtle.ConstantTimeCompare(c.macResult, mac) != 1 {
  410. return nil, cbcError("ssh: MAC failure")
  411. }
  412. }
  413. return c.packetData[prefixLen:paddingStart], nil
  414. }
  415. func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  416. effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize())
  417. // Length of encrypted portion of the packet (header, payload, padding).
  418. // Enforce minimum padding and packet size.
  419. encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
  420. // Enforce block size.
  421. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
  422. length := encLength - 4
  423. paddingLength := int(length) - (1 + len(packet))
  424. // Overall buffer contains: header, payload, padding, mac.
  425. // Space for the MAC is reserved in the capacity but not the slice length.
  426. bufferSize := encLength + c.macSize
  427. if uint32(cap(c.packetData)) < bufferSize {
  428. c.packetData = make([]byte, encLength, bufferSize)
  429. } else {
  430. c.packetData = c.packetData[:encLength]
  431. }
  432. p := c.packetData
  433. // Packet header.
  434. binary.BigEndian.PutUint32(p, length)
  435. p = p[4:]
  436. p[0] = byte(paddingLength)
  437. // Payload.
  438. p = p[1:]
  439. copy(p, packet)
  440. // Padding.
  441. p = p[len(packet):]
  442. if _, err := io.ReadFull(rand, p); err != nil {
  443. return err
  444. }
  445. if c.mac != nil {
  446. c.mac.Reset()
  447. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  448. c.mac.Write(c.seqNumBytes[:])
  449. c.mac.Write(c.packetData)
  450. // The MAC is now appended into the capacity reserved for it earlier.
  451. c.packetData = c.mac.Sum(c.packetData)
  452. }
  453. c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength])
  454. if _, err := w.Write(c.packetData); err != nil {
  455. return err
  456. }
  457. return nil
  458. }