cipher.go 16 KB

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