cipher.go 17 KB

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