cipher.go 15 KB

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