You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1346 lines
37 KiB

  1. // Copyright 2010 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. // TLS low level connection and record layer
  5. package main
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/ecdsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "sync"
  17. "time"
  18. )
  19. // A Conn represents a secured connection.
  20. // It implements the net.Conn interface.
  21. type Conn struct {
  22. // constant
  23. conn net.Conn
  24. isDTLS bool
  25. isClient bool
  26. // constant after handshake; protected by handshakeMutex
  27. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  28. handshakeErr error // error resulting from handshake
  29. vers uint16 // TLS version
  30. haveVers bool // version has been negotiated
  31. config *Config // configuration passed to constructor
  32. handshakeComplete bool
  33. didResume bool // whether this connection was a session resumption
  34. extendedMasterSecret bool // whether this session used an extended master secret
  35. cipherSuite *cipherSuite
  36. ocspResponse []byte // stapled OCSP response
  37. peerCertificates []*x509.Certificate
  38. // verifiedChains contains the certificate chains that we built, as
  39. // opposed to the ones presented by the server.
  40. verifiedChains [][]*x509.Certificate
  41. // serverName contains the server name indicated by the client, if any.
  42. serverName string
  43. clientRandom, serverRandom [32]byte
  44. masterSecret [48]byte
  45. clientProtocol string
  46. clientProtocolFallback bool
  47. usedALPN bool
  48. // verify_data values for the renegotiation extension.
  49. clientVerify []byte
  50. serverVerify []byte
  51. channelID *ecdsa.PublicKey
  52. srtpProtectionProfile uint16
  53. clientVersion uint16
  54. // input/output
  55. in, out halfConn // in.Mutex < out.Mutex
  56. rawInput *block // raw input, right off the wire
  57. input *block // application record waiting to be read
  58. hand bytes.Buffer // handshake record waiting to be read
  59. // DTLS state
  60. sendHandshakeSeq uint16
  61. recvHandshakeSeq uint16
  62. handMsg []byte // pending assembled handshake message
  63. handMsgLen int // handshake message length, not including the header
  64. pendingFragments [][]byte // pending outgoing handshake fragments.
  65. tmp [16]byte
  66. }
  67. func (c *Conn) init() {
  68. c.in.isDTLS = c.isDTLS
  69. c.out.isDTLS = c.isDTLS
  70. c.in.config = c.config
  71. c.out.config = c.config
  72. }
  73. // Access to net.Conn methods.
  74. // Cannot just embed net.Conn because that would
  75. // export the struct field too.
  76. // LocalAddr returns the local network address.
  77. func (c *Conn) LocalAddr() net.Addr {
  78. return c.conn.LocalAddr()
  79. }
  80. // RemoteAddr returns the remote network address.
  81. func (c *Conn) RemoteAddr() net.Addr {
  82. return c.conn.RemoteAddr()
  83. }
  84. // SetDeadline sets the read and write deadlines associated with the connection.
  85. // A zero value for t means Read and Write will not time out.
  86. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  87. func (c *Conn) SetDeadline(t time.Time) error {
  88. return c.conn.SetDeadline(t)
  89. }
  90. // SetReadDeadline sets the read deadline on the underlying connection.
  91. // A zero value for t means Read will not time out.
  92. func (c *Conn) SetReadDeadline(t time.Time) error {
  93. return c.conn.SetReadDeadline(t)
  94. }
  95. // SetWriteDeadline sets the write deadline on the underlying conneciton.
  96. // A zero value for t means Write will not time out.
  97. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  98. func (c *Conn) SetWriteDeadline(t time.Time) error {
  99. return c.conn.SetWriteDeadline(t)
  100. }
  101. // A halfConn represents one direction of the record layer
  102. // connection, either sending or receiving.
  103. type halfConn struct {
  104. sync.Mutex
  105. err error // first permanent error
  106. version uint16 // protocol version
  107. isDTLS bool
  108. cipher interface{} // cipher algorithm
  109. mac macFunction
  110. seq [8]byte // 64-bit sequence number
  111. bfree *block // list of free blocks
  112. nextCipher interface{} // next encryption state
  113. nextMac macFunction // next MAC algorithm
  114. nextSeq [6]byte // next epoch's starting sequence number in DTLS
  115. // used to save allocating a new buffer for each MAC.
  116. inDigestBuf, outDigestBuf []byte
  117. config *Config
  118. }
  119. func (hc *halfConn) setErrorLocked(err error) error {
  120. hc.err = err
  121. return err
  122. }
  123. func (hc *halfConn) error() error {
  124. // This should be locked, but I've removed it for the renegotiation
  125. // tests since we don't concurrently read and write the same tls.Conn
  126. // in any case during testing.
  127. err := hc.err
  128. return err
  129. }
  130. // prepareCipherSpec sets the encryption and MAC states
  131. // that a subsequent changeCipherSpec will use.
  132. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  133. hc.version = version
  134. hc.nextCipher = cipher
  135. hc.nextMac = mac
  136. }
  137. // changeCipherSpec changes the encryption and MAC states
  138. // to the ones previously passed to prepareCipherSpec.
  139. func (hc *halfConn) changeCipherSpec(config *Config) error {
  140. if hc.nextCipher == nil {
  141. return alertInternalError
  142. }
  143. hc.cipher = hc.nextCipher
  144. hc.mac = hc.nextMac
  145. hc.nextCipher = nil
  146. hc.nextMac = nil
  147. hc.config = config
  148. hc.incEpoch()
  149. return nil
  150. }
  151. // incSeq increments the sequence number.
  152. func (hc *halfConn) incSeq(isOutgoing bool) {
  153. limit := 0
  154. increment := uint64(1)
  155. if hc.isDTLS {
  156. // Increment up to the epoch in DTLS.
  157. limit = 2
  158. if isOutgoing && hc.config.Bugs.SequenceNumberIncrement != 0 {
  159. increment = hc.config.Bugs.SequenceNumberIncrement
  160. }
  161. }
  162. for i := 7; i >= limit; i-- {
  163. increment += uint64(hc.seq[i])
  164. hc.seq[i] = byte(increment)
  165. increment >>= 8
  166. }
  167. // Not allowed to let sequence number wrap.
  168. // Instead, must renegotiate before it does.
  169. // Not likely enough to bother.
  170. if increment != 0 {
  171. panic("TLS: sequence number wraparound")
  172. }
  173. }
  174. // incNextSeq increments the starting sequence number for the next epoch.
  175. func (hc *halfConn) incNextSeq() {
  176. for i := len(hc.nextSeq) - 1; i >= 0; i-- {
  177. hc.nextSeq[i]++
  178. if hc.nextSeq[i] != 0 {
  179. return
  180. }
  181. }
  182. panic("TLS: sequence number wraparound")
  183. }
  184. // incEpoch resets the sequence number. In DTLS, it also increments the epoch
  185. // half of the sequence number.
  186. func (hc *halfConn) incEpoch() {
  187. if hc.isDTLS {
  188. for i := 1; i >= 0; i-- {
  189. hc.seq[i]++
  190. if hc.seq[i] != 0 {
  191. break
  192. }
  193. if i == 0 {
  194. panic("TLS: epoch number wraparound")
  195. }
  196. }
  197. copy(hc.seq[2:], hc.nextSeq[:])
  198. for i := range hc.nextSeq {
  199. hc.nextSeq[i] = 0
  200. }
  201. } else {
  202. for i := range hc.seq {
  203. hc.seq[i] = 0
  204. }
  205. }
  206. }
  207. func (hc *halfConn) recordHeaderLen() int {
  208. if hc.isDTLS {
  209. return dtlsRecordHeaderLen
  210. }
  211. return tlsRecordHeaderLen
  212. }
  213. // removePadding returns an unpadded slice, in constant time, which is a prefix
  214. // of the input. It also returns a byte which is equal to 255 if the padding
  215. // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  216. func removePadding(payload []byte) ([]byte, byte) {
  217. if len(payload) < 1 {
  218. return payload, 0
  219. }
  220. paddingLen := payload[len(payload)-1]
  221. t := uint(len(payload)-1) - uint(paddingLen)
  222. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  223. good := byte(int32(^t) >> 31)
  224. toCheck := 255 // the maximum possible padding length
  225. // The length of the padded data is public, so we can use an if here
  226. if toCheck+1 > len(payload) {
  227. toCheck = len(payload) - 1
  228. }
  229. for i := 0; i < toCheck; i++ {
  230. t := uint(paddingLen) - uint(i)
  231. // if i <= paddingLen then the MSB of t is zero
  232. mask := byte(int32(^t) >> 31)
  233. b := payload[len(payload)-1-i]
  234. good &^= mask&paddingLen ^ mask&b
  235. }
  236. // We AND together the bits of good and replicate the result across
  237. // all the bits.
  238. good &= good << 4
  239. good &= good << 2
  240. good &= good << 1
  241. good = uint8(int8(good) >> 7)
  242. toRemove := good&paddingLen + 1
  243. return payload[:len(payload)-int(toRemove)], good
  244. }
  245. // removePaddingSSL30 is a replacement for removePadding in the case that the
  246. // protocol version is SSLv3. In this version, the contents of the padding
  247. // are random and cannot be checked.
  248. func removePaddingSSL30(payload []byte) ([]byte, byte) {
  249. if len(payload) < 1 {
  250. return payload, 0
  251. }
  252. paddingLen := int(payload[len(payload)-1]) + 1
  253. if paddingLen > len(payload) {
  254. return payload, 0
  255. }
  256. return payload[:len(payload)-paddingLen], 255
  257. }
  258. func roundUp(a, b int) int {
  259. return a + (b-a%b)%b
  260. }
  261. // cbcMode is an interface for block ciphers using cipher block chaining.
  262. type cbcMode interface {
  263. cipher.BlockMode
  264. SetIV([]byte)
  265. }
  266. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  267. // success boolean, the number of bytes to skip from the start of the record in
  268. // order to get the application payload, and an optional alert value.
  269. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  270. recordHeaderLen := hc.recordHeaderLen()
  271. // pull out payload
  272. payload := b.data[recordHeaderLen:]
  273. macSize := 0
  274. if hc.mac != nil {
  275. macSize = hc.mac.Size()
  276. }
  277. paddingGood := byte(255)
  278. explicitIVLen := 0
  279. seq := hc.seq[:]
  280. if hc.isDTLS {
  281. // DTLS sequence numbers are explicit.
  282. seq = b.data[3:11]
  283. }
  284. // decrypt
  285. if hc.cipher != nil {
  286. switch c := hc.cipher.(type) {
  287. case cipher.Stream:
  288. c.XORKeyStream(payload, payload)
  289. case *tlsAead:
  290. nonce := seq
  291. if c.explicitNonce {
  292. explicitIVLen = 8
  293. if len(payload) < explicitIVLen {
  294. return false, 0, alertBadRecordMAC
  295. }
  296. nonce = payload[:8]
  297. payload = payload[8:]
  298. }
  299. var additionalData [13]byte
  300. copy(additionalData[:], seq)
  301. copy(additionalData[8:], b.data[:3])
  302. n := len(payload) - c.Overhead()
  303. additionalData[11] = byte(n >> 8)
  304. additionalData[12] = byte(n)
  305. var err error
  306. payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
  307. if err != nil {
  308. return false, 0, alertBadRecordMAC
  309. }
  310. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  311. case cbcMode:
  312. blockSize := c.BlockSize()
  313. if hc.version >= VersionTLS11 || hc.isDTLS {
  314. explicitIVLen = blockSize
  315. }
  316. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  317. return false, 0, alertBadRecordMAC
  318. }
  319. if explicitIVLen > 0 {
  320. c.SetIV(payload[:explicitIVLen])
  321. payload = payload[explicitIVLen:]
  322. }
  323. c.CryptBlocks(payload, payload)
  324. if hc.version == VersionSSL30 {
  325. payload, paddingGood = removePaddingSSL30(payload)
  326. } else {
  327. payload, paddingGood = removePadding(payload)
  328. }
  329. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  330. // note that we still have a timing side-channel in the
  331. // MAC check, below. An attacker can align the record
  332. // so that a correct padding will cause one less hash
  333. // block to be calculated. Then they can iteratively
  334. // decrypt a record by breaking each byte. See
  335. // "Password Interception in a SSL/TLS Channel", Brice
  336. // Canvel et al.
  337. //
  338. // However, our behavior matches OpenSSL, so we leak
  339. // only as much as they do.
  340. default:
  341. panic("unknown cipher type")
  342. }
  343. }
  344. // check, strip mac
  345. if hc.mac != nil {
  346. if len(payload) < macSize {
  347. return false, 0, alertBadRecordMAC
  348. }
  349. // strip mac off payload, b.data
  350. n := len(payload) - macSize
  351. b.data[recordHeaderLen-2] = byte(n >> 8)
  352. b.data[recordHeaderLen-1] = byte(n)
  353. b.resize(recordHeaderLen + explicitIVLen + n)
  354. remoteMAC := payload[n:]
  355. localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
  356. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  357. return false, 0, alertBadRecordMAC
  358. }
  359. hc.inDigestBuf = localMAC
  360. }
  361. hc.incSeq(false)
  362. return true, recordHeaderLen + explicitIVLen, 0
  363. }
  364. // padToBlockSize calculates the needed padding block, if any, for a payload.
  365. // On exit, prefix aliases payload and extends to the end of the last full
  366. // block of payload. finalBlock is a fresh slice which contains the contents of
  367. // any suffix of payload as well as the needed padding to make finalBlock a
  368. // full block.
  369. func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
  370. overrun := len(payload) % blockSize
  371. prefix = payload[:len(payload)-overrun]
  372. paddingLen := blockSize - overrun
  373. finalSize := blockSize
  374. if config.Bugs.MaxPadding {
  375. for paddingLen+blockSize <= 256 {
  376. paddingLen += blockSize
  377. }
  378. finalSize = 256
  379. }
  380. finalBlock = make([]byte, finalSize)
  381. for i := range finalBlock {
  382. finalBlock[i] = byte(paddingLen - 1)
  383. }
  384. if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
  385. finalBlock[overrun] ^= 0xff
  386. }
  387. copy(finalBlock, payload[len(payload)-overrun:])
  388. return
  389. }
  390. // encrypt encrypts and macs the data in b.
  391. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  392. recordHeaderLen := hc.recordHeaderLen()
  393. // mac
  394. if hc.mac != nil {
  395. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
  396. n := len(b.data)
  397. b.resize(n + len(mac))
  398. copy(b.data[n:], mac)
  399. hc.outDigestBuf = mac
  400. }
  401. payload := b.data[recordHeaderLen:]
  402. // encrypt
  403. if hc.cipher != nil {
  404. switch c := hc.cipher.(type) {
  405. case cipher.Stream:
  406. c.XORKeyStream(payload, payload)
  407. case *tlsAead:
  408. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  409. b.resize(len(b.data) + c.Overhead())
  410. nonce := hc.seq[:]
  411. if c.explicitNonce {
  412. nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  413. }
  414. payload := b.data[recordHeaderLen+explicitIVLen:]
  415. payload = payload[:payloadLen]
  416. var additionalData [13]byte
  417. copy(additionalData[:], hc.seq[:])
  418. copy(additionalData[8:], b.data[:3])
  419. additionalData[11] = byte(payloadLen >> 8)
  420. additionalData[12] = byte(payloadLen)
  421. c.Seal(payload[:0], nonce, payload, additionalData[:])
  422. case cbcMode:
  423. blockSize := c.BlockSize()
  424. if explicitIVLen > 0 {
  425. c.SetIV(payload[:explicitIVLen])
  426. payload = payload[explicitIVLen:]
  427. }
  428. prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
  429. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  430. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  431. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  432. default:
  433. panic("unknown cipher type")
  434. }
  435. }
  436. // update length to include MAC and any block padding needed.
  437. n := len(b.data) - recordHeaderLen
  438. b.data[recordHeaderLen-2] = byte(n >> 8)
  439. b.data[recordHeaderLen-1] = byte(n)
  440. hc.incSeq(true)
  441. return true, 0
  442. }
  443. // A block is a simple data buffer.
  444. type block struct {
  445. data []byte
  446. off int // index for Read
  447. link *block
  448. }
  449. // resize resizes block to be n bytes, growing if necessary.
  450. func (b *block) resize(n int) {
  451. if n > cap(b.data) {
  452. b.reserve(n)
  453. }
  454. b.data = b.data[0:n]
  455. }
  456. // reserve makes sure that block contains a capacity of at least n bytes.
  457. func (b *block) reserve(n int) {
  458. if cap(b.data) >= n {
  459. return
  460. }
  461. m := cap(b.data)
  462. if m == 0 {
  463. m = 1024
  464. }
  465. for m < n {
  466. m *= 2
  467. }
  468. data := make([]byte, len(b.data), m)
  469. copy(data, b.data)
  470. b.data = data
  471. }
  472. // readFromUntil reads from r into b until b contains at least n bytes
  473. // or else returns an error.
  474. func (b *block) readFromUntil(r io.Reader, n int) error {
  475. // quick case
  476. if len(b.data) >= n {
  477. return nil
  478. }
  479. // read until have enough.
  480. b.reserve(n)
  481. for {
  482. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  483. b.data = b.data[0 : len(b.data)+m]
  484. if len(b.data) >= n {
  485. // TODO(bradfitz,agl): slightly suspicious
  486. // that we're throwing away r.Read's err here.
  487. break
  488. }
  489. if err != nil {
  490. return err
  491. }
  492. }
  493. return nil
  494. }
  495. func (b *block) Read(p []byte) (n int, err error) {
  496. n = copy(p, b.data[b.off:])
  497. b.off += n
  498. return
  499. }
  500. // newBlock allocates a new block, from hc's free list if possible.
  501. func (hc *halfConn) newBlock() *block {
  502. b := hc.bfree
  503. if b == nil {
  504. return new(block)
  505. }
  506. hc.bfree = b.link
  507. b.link = nil
  508. b.resize(0)
  509. return b
  510. }
  511. // freeBlock returns a block to hc's free list.
  512. // The protocol is such that each side only has a block or two on
  513. // its free list at a time, so there's no need to worry about
  514. // trimming the list, etc.
  515. func (hc *halfConn) freeBlock(b *block) {
  516. b.link = hc.bfree
  517. hc.bfree = b
  518. }
  519. // splitBlock splits a block after the first n bytes,
  520. // returning a block with those n bytes and a
  521. // block with the remainder. the latter may be nil.
  522. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  523. if len(b.data) <= n {
  524. return b, nil
  525. }
  526. bb := hc.newBlock()
  527. bb.resize(len(b.data) - n)
  528. copy(bb.data, b.data[n:])
  529. b.data = b.data[0:n]
  530. return b, bb
  531. }
  532. func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
  533. if c.isDTLS {
  534. return c.dtlsDoReadRecord(want)
  535. }
  536. recordHeaderLen := tlsRecordHeaderLen
  537. if c.rawInput == nil {
  538. c.rawInput = c.in.newBlock()
  539. }
  540. b := c.rawInput
  541. // Read header, payload.
  542. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  543. // RFC suggests that EOF without an alertCloseNotify is
  544. // an error, but popular web sites seem to do this,
  545. // so we can't make it an error.
  546. // if err == io.EOF {
  547. // err = io.ErrUnexpectedEOF
  548. // }
  549. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  550. c.in.setErrorLocked(err)
  551. }
  552. return 0, nil, err
  553. }
  554. typ := recordType(b.data[0])
  555. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  556. // start with a uint16 length where the MSB is set and the first record
  557. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  558. // an SSLv2 client.
  559. if want == recordTypeHandshake && typ == 0x80 {
  560. c.sendAlert(alertProtocolVersion)
  561. return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
  562. }
  563. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  564. n := int(b.data[3])<<8 | int(b.data[4])
  565. if c.haveVers {
  566. if vers != c.vers {
  567. c.sendAlert(alertProtocolVersion)
  568. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
  569. }
  570. } else {
  571. if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
  572. c.sendAlert(alertProtocolVersion)
  573. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
  574. }
  575. }
  576. if n > maxCiphertext {
  577. c.sendAlert(alertRecordOverflow)
  578. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
  579. }
  580. if !c.haveVers {
  581. // First message, be extra suspicious:
  582. // this might not be a TLS client.
  583. // Bail out before reading a full 'body', if possible.
  584. // The current max version is 3.1.
  585. // If the version is >= 16.0, it's probably not real.
  586. // Similarly, a clientHello message encodes in
  587. // well under a kilobyte. If the length is >= 12 kB,
  588. // it's probably not real.
  589. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
  590. c.sendAlert(alertUnexpectedMessage)
  591. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
  592. }
  593. }
  594. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  595. if err == io.EOF {
  596. err = io.ErrUnexpectedEOF
  597. }
  598. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  599. c.in.setErrorLocked(err)
  600. }
  601. return 0, nil, err
  602. }
  603. // Process message.
  604. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  605. ok, off, err := c.in.decrypt(b)
  606. if !ok {
  607. c.in.setErrorLocked(c.sendAlert(err))
  608. }
  609. b.off = off
  610. return typ, b, nil
  611. }
  612. // readRecord reads the next TLS record from the connection
  613. // and updates the record layer state.
  614. // c.in.Mutex <= L; c.input == nil.
  615. func (c *Conn) readRecord(want recordType) error {
  616. // Caller must be in sync with connection:
  617. // handshake data if handshake not yet completed,
  618. // else application data.
  619. switch want {
  620. default:
  621. c.sendAlert(alertInternalError)
  622. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  623. case recordTypeHandshake, recordTypeChangeCipherSpec:
  624. if c.handshakeComplete {
  625. c.sendAlert(alertInternalError)
  626. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
  627. }
  628. case recordTypeApplicationData:
  629. if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
  630. c.sendAlert(alertInternalError)
  631. return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
  632. }
  633. }
  634. Again:
  635. typ, b, err := c.doReadRecord(want)
  636. if err != nil {
  637. return err
  638. }
  639. data := b.data[b.off:]
  640. if len(data) > maxPlaintext {
  641. err := c.sendAlert(alertRecordOverflow)
  642. c.in.freeBlock(b)
  643. return c.in.setErrorLocked(err)
  644. }
  645. switch typ {
  646. default:
  647. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  648. case recordTypeAlert:
  649. if len(data) != 2 {
  650. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  651. break
  652. }
  653. if alert(data[1]) == alertCloseNotify {
  654. c.in.setErrorLocked(io.EOF)
  655. break
  656. }
  657. switch data[0] {
  658. case alertLevelWarning:
  659. // drop on the floor
  660. c.in.freeBlock(b)
  661. goto Again
  662. case alertLevelError:
  663. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  664. default:
  665. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  666. }
  667. case recordTypeChangeCipherSpec:
  668. if typ != want || len(data) != 1 || data[0] != 1 {
  669. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  670. break
  671. }
  672. err := c.in.changeCipherSpec(c.config)
  673. if err != nil {
  674. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  675. }
  676. case recordTypeApplicationData:
  677. if typ != want {
  678. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  679. break
  680. }
  681. c.input = b
  682. b = nil
  683. case recordTypeHandshake:
  684. // TODO(rsc): Should at least pick off connection close.
  685. if typ != want {
  686. // A client might need to process a HelloRequest from
  687. // the server, thus receiving a handshake message when
  688. // application data is expected is ok.
  689. if !c.isClient {
  690. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  691. }
  692. }
  693. c.hand.Write(data)
  694. }
  695. if b != nil {
  696. c.in.freeBlock(b)
  697. }
  698. return c.in.err
  699. }
  700. // sendAlert sends a TLS alert message.
  701. // c.out.Mutex <= L.
  702. func (c *Conn) sendAlertLocked(err alert) error {
  703. switch err {
  704. case alertNoRenegotiation, alertCloseNotify:
  705. c.tmp[0] = alertLevelWarning
  706. default:
  707. c.tmp[0] = alertLevelError
  708. }
  709. c.tmp[1] = byte(err)
  710. if c.config.Bugs.FragmentAlert {
  711. c.writeRecord(recordTypeAlert, c.tmp[0:1])
  712. c.writeRecord(recordTypeAlert, c.tmp[1:2])
  713. } else {
  714. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  715. }
  716. // closeNotify is a special case in that it isn't an error:
  717. if err != alertCloseNotify {
  718. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  719. }
  720. return nil
  721. }
  722. // sendAlert sends a TLS alert message.
  723. // L < c.out.Mutex.
  724. func (c *Conn) sendAlert(err alert) error {
  725. c.out.Lock()
  726. defer c.out.Unlock()
  727. return c.sendAlertLocked(err)
  728. }
  729. // writeV2Record writes a record for a V2ClientHello.
  730. func (c *Conn) writeV2Record(data []byte) (n int, err error) {
  731. record := make([]byte, 2+len(data))
  732. record[0] = uint8(len(data)>>8) | 0x80
  733. record[1] = uint8(len(data))
  734. copy(record[2:], data)
  735. return c.conn.Write(record)
  736. }
  737. // writeRecord writes a TLS record with the given type and payload
  738. // to the connection and updates the record layer state.
  739. // c.out.Mutex <= L.
  740. func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
  741. if typ != recordTypeAlert && c.config.Bugs.SendWarningAlerts != 0 {
  742. alert := make([]byte, 2)
  743. alert[0] = alertLevelWarning
  744. alert[1] = byte(c.config.Bugs.SendWarningAlerts)
  745. c.writeRecord(recordTypeAlert, alert)
  746. }
  747. if c.isDTLS {
  748. return c.dtlsWriteRecord(typ, data)
  749. }
  750. recordHeaderLen := tlsRecordHeaderLen
  751. b := c.out.newBlock()
  752. first := true
  753. isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
  754. for len(data) > 0 {
  755. m := len(data)
  756. if m > maxPlaintext {
  757. m = maxPlaintext
  758. }
  759. if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
  760. m = c.config.Bugs.MaxHandshakeRecordLength
  761. // By default, do not fragment the client_version or
  762. // server_version, which are located in the first 6
  763. // bytes.
  764. if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
  765. m = 6
  766. }
  767. }
  768. explicitIVLen := 0
  769. explicitIVIsSeq := false
  770. first = false
  771. var cbc cbcMode
  772. if c.out.version >= VersionTLS11 {
  773. var ok bool
  774. if cbc, ok = c.out.cipher.(cbcMode); ok {
  775. explicitIVLen = cbc.BlockSize()
  776. }
  777. }
  778. if explicitIVLen == 0 {
  779. if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
  780. explicitIVLen = 8
  781. // The AES-GCM construction in TLS has an
  782. // explicit nonce so that the nonce can be
  783. // random. However, the nonce is only 8 bytes
  784. // which is too small for a secure, random
  785. // nonce. Therefore we use the sequence number
  786. // as the nonce.
  787. explicitIVIsSeq = true
  788. }
  789. }
  790. b.resize(recordHeaderLen + explicitIVLen + m)
  791. b.data[0] = byte(typ)
  792. vers := c.vers
  793. if vers == 0 {
  794. // Some TLS servers fail if the record version is
  795. // greater than TLS 1.0 for the initial ClientHello.
  796. vers = VersionTLS10
  797. }
  798. b.data[1] = byte(vers >> 8)
  799. b.data[2] = byte(vers)
  800. b.data[3] = byte(m >> 8)
  801. b.data[4] = byte(m)
  802. if explicitIVLen > 0 {
  803. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  804. if explicitIVIsSeq {
  805. copy(explicitIV, c.out.seq[:])
  806. } else {
  807. if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
  808. break
  809. }
  810. }
  811. }
  812. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  813. c.out.encrypt(b, explicitIVLen)
  814. _, err = c.conn.Write(b.data)
  815. if err != nil {
  816. break
  817. }
  818. n += m
  819. data = data[m:]
  820. }
  821. c.out.freeBlock(b)
  822. if typ == recordTypeChangeCipherSpec {
  823. err = c.out.changeCipherSpec(c.config)
  824. if err != nil {
  825. // Cannot call sendAlert directly,
  826. // because we already hold c.out.Mutex.
  827. c.tmp[0] = alertLevelError
  828. c.tmp[1] = byte(err.(alert))
  829. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  830. return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  831. }
  832. }
  833. return
  834. }
  835. func (c *Conn) doReadHandshake() ([]byte, error) {
  836. if c.isDTLS {
  837. return c.dtlsDoReadHandshake()
  838. }
  839. for c.hand.Len() < 4 {
  840. if err := c.in.err; err != nil {
  841. return nil, err
  842. }
  843. if err := c.readRecord(recordTypeHandshake); err != nil {
  844. return nil, err
  845. }
  846. }
  847. data := c.hand.Bytes()
  848. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  849. if n > maxHandshake {
  850. return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
  851. }
  852. for c.hand.Len() < 4+n {
  853. if err := c.in.err; err != nil {
  854. return nil, err
  855. }
  856. if err := c.readRecord(recordTypeHandshake); err != nil {
  857. return nil, err
  858. }
  859. }
  860. return c.hand.Next(4 + n), nil
  861. }
  862. // readHandshake reads the next handshake message from
  863. // the record layer.
  864. // c.in.Mutex < L; c.out.Mutex < L.
  865. func (c *Conn) readHandshake() (interface{}, error) {
  866. data, err := c.doReadHandshake()
  867. if err != nil {
  868. return nil, err
  869. }
  870. var m handshakeMessage
  871. switch data[0] {
  872. case typeHelloRequest:
  873. m = new(helloRequestMsg)
  874. case typeClientHello:
  875. m = &clientHelloMsg{
  876. isDTLS: c.isDTLS,
  877. }
  878. case typeServerHello:
  879. m = &serverHelloMsg{
  880. isDTLS: c.isDTLS,
  881. }
  882. case typeNewSessionTicket:
  883. m = new(newSessionTicketMsg)
  884. case typeCertificate:
  885. m = new(certificateMsg)
  886. case typeCertificateRequest:
  887. m = &certificateRequestMsg{
  888. hasSignatureAndHash: c.vers >= VersionTLS12,
  889. }
  890. case typeCertificateStatus:
  891. m = new(certificateStatusMsg)
  892. case typeServerKeyExchange:
  893. m = new(serverKeyExchangeMsg)
  894. case typeServerHelloDone:
  895. m = new(serverHelloDoneMsg)
  896. case typeClientKeyExchange:
  897. m = new(clientKeyExchangeMsg)
  898. case typeCertificateVerify:
  899. m = &certificateVerifyMsg{
  900. hasSignatureAndHash: c.vers >= VersionTLS12,
  901. }
  902. case typeNextProtocol:
  903. m = new(nextProtoMsg)
  904. case typeFinished:
  905. m = new(finishedMsg)
  906. case typeHelloVerifyRequest:
  907. m = new(helloVerifyRequestMsg)
  908. case typeEncryptedExtensions:
  909. m = new(encryptedExtensionsMsg)
  910. default:
  911. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  912. }
  913. // The handshake message unmarshallers
  914. // expect to be able to keep references to data,
  915. // so pass in a fresh copy that won't be overwritten.
  916. data = append([]byte(nil), data...)
  917. if !m.unmarshal(data) {
  918. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  919. }
  920. return m, nil
  921. }
  922. // skipPacket processes all the DTLS records in packet. It updates
  923. // sequence number expectations but otherwise ignores them.
  924. func (c *Conn) skipPacket(packet []byte) error {
  925. for len(packet) > 0 {
  926. // Dropped packets are completely ignored save to update
  927. // expected sequence numbers for this and the next epoch. (We
  928. // don't assert on the contents of the packets both for
  929. // simplicity and because a previous test with one shorter
  930. // timeout schedule would have done so.)
  931. epoch := packet[3:5]
  932. seq := packet[5:11]
  933. length := uint16(packet[11])<<8 | uint16(packet[12])
  934. if bytes.Equal(c.in.seq[:2], epoch) {
  935. if !bytes.Equal(c.in.seq[2:], seq) {
  936. return errors.New("tls: sequence mismatch")
  937. }
  938. c.in.incSeq(false)
  939. } else {
  940. if !bytes.Equal(c.in.nextSeq[:], seq) {
  941. return errors.New("tls: sequence mismatch")
  942. }
  943. c.in.incNextSeq()
  944. }
  945. packet = packet[13+length:]
  946. }
  947. return nil
  948. }
  949. // simulatePacketLoss simulates the loss of a handshake leg from the
  950. // peer based on the schedule in c.config.Bugs. If resendFunc is
  951. // non-nil, it is called after each simulated timeout to retransmit
  952. // handshake messages from the local end. This is used in cases where
  953. // the peer retransmits on a stale Finished rather than a timeout.
  954. func (c *Conn) simulatePacketLoss(resendFunc func()) error {
  955. if len(c.config.Bugs.TimeoutSchedule) == 0 {
  956. return nil
  957. }
  958. if !c.isDTLS {
  959. return errors.New("tls: TimeoutSchedule may only be set in DTLS")
  960. }
  961. if c.config.Bugs.PacketAdaptor == nil {
  962. return errors.New("tls: TimeoutSchedule set without PacketAdapter")
  963. }
  964. for _, timeout := range c.config.Bugs.TimeoutSchedule {
  965. // Simulate a timeout.
  966. packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
  967. if err != nil {
  968. return err
  969. }
  970. for _, packet := range packets {
  971. if err := c.skipPacket(packet); err != nil {
  972. return err
  973. }
  974. }
  975. if resendFunc != nil {
  976. resendFunc()
  977. }
  978. }
  979. return nil
  980. }
  981. // Write writes data to the connection.
  982. func (c *Conn) Write(b []byte) (int, error) {
  983. if err := c.Handshake(); err != nil {
  984. return 0, err
  985. }
  986. c.out.Lock()
  987. defer c.out.Unlock()
  988. if err := c.out.err; err != nil {
  989. return 0, err
  990. }
  991. if !c.handshakeComplete {
  992. return 0, alertInternalError
  993. }
  994. if c.config.Bugs.SendSpuriousAlert != 0 {
  995. c.sendAlertLocked(c.config.Bugs.SendSpuriousAlert)
  996. }
  997. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  998. // attack when using block mode ciphers due to predictable IVs.
  999. // This can be prevented by splitting each Application Data
  1000. // record into two records, effectively randomizing the IV.
  1001. //
  1002. // http://www.openssl.org/~bodo/tls-cbc.txt
  1003. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1004. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1005. var m int
  1006. if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
  1007. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1008. n, err := c.writeRecord(recordTypeApplicationData, b[:1])
  1009. if err != nil {
  1010. return n, c.out.setErrorLocked(err)
  1011. }
  1012. m, b = 1, b[1:]
  1013. }
  1014. }
  1015. n, err := c.writeRecord(recordTypeApplicationData, b)
  1016. return n + m, c.out.setErrorLocked(err)
  1017. }
  1018. func (c *Conn) handleRenegotiation() error {
  1019. c.handshakeComplete = false
  1020. if !c.isClient {
  1021. panic("renegotiation should only happen for a client")
  1022. }
  1023. msg, err := c.readHandshake()
  1024. if err != nil {
  1025. return err
  1026. }
  1027. _, ok := msg.(*helloRequestMsg)
  1028. if !ok {
  1029. c.sendAlert(alertUnexpectedMessage)
  1030. return alertUnexpectedMessage
  1031. }
  1032. return c.Handshake()
  1033. }
  1034. func (c *Conn) Renegotiate() error {
  1035. if !c.isClient {
  1036. helloReq := new(helloRequestMsg)
  1037. c.writeRecord(recordTypeHandshake, helloReq.marshal())
  1038. }
  1039. c.handshakeComplete = false
  1040. return c.Handshake()
  1041. }
  1042. // Read can be made to time out and return a net.Error with Timeout() == true
  1043. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1044. func (c *Conn) Read(b []byte) (n int, err error) {
  1045. if err = c.Handshake(); err != nil {
  1046. return
  1047. }
  1048. c.in.Lock()
  1049. defer c.in.Unlock()
  1050. // Some OpenSSL servers send empty records in order to randomize the
  1051. // CBC IV. So this loop ignores a limited number of empty records.
  1052. const maxConsecutiveEmptyRecords = 100
  1053. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1054. for c.input == nil && c.in.err == nil {
  1055. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1056. // Soft error, like EAGAIN
  1057. return 0, err
  1058. }
  1059. if c.hand.Len() > 0 {
  1060. // We received handshake bytes, indicating the
  1061. // start of a renegotiation.
  1062. if err := c.handleRenegotiation(); err != nil {
  1063. return 0, err
  1064. }
  1065. continue
  1066. }
  1067. }
  1068. if err := c.in.err; err != nil {
  1069. return 0, err
  1070. }
  1071. n, err = c.input.Read(b)
  1072. if c.input.off >= len(c.input.data) || c.isDTLS {
  1073. c.in.freeBlock(c.input)
  1074. c.input = nil
  1075. }
  1076. // If a close-notify alert is waiting, read it so that
  1077. // we can return (n, EOF) instead of (n, nil), to signal
  1078. // to the HTTP response reading goroutine that the
  1079. // connection is now closed. This eliminates a race
  1080. // where the HTTP response reading goroutine would
  1081. // otherwise not observe the EOF until its next read,
  1082. // by which time a client goroutine might have already
  1083. // tried to reuse the HTTP connection for a new
  1084. // request.
  1085. // See https://codereview.appspot.com/76400046
  1086. // and http://golang.org/issue/3514
  1087. if ri := c.rawInput; ri != nil &&
  1088. n != 0 && err == nil &&
  1089. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1090. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1091. err = recErr // will be io.EOF on closeNotify
  1092. }
  1093. }
  1094. if n != 0 || err != nil {
  1095. return n, err
  1096. }
  1097. }
  1098. return 0, io.ErrNoProgress
  1099. }
  1100. // Close closes the connection.
  1101. func (c *Conn) Close() error {
  1102. var alertErr error
  1103. c.handshakeMutex.Lock()
  1104. defer c.handshakeMutex.Unlock()
  1105. if c.handshakeComplete {
  1106. alertErr = c.sendAlert(alertCloseNotify)
  1107. }
  1108. if err := c.conn.Close(); err != nil {
  1109. return err
  1110. }
  1111. return alertErr
  1112. }
  1113. // Handshake runs the client or server handshake
  1114. // protocol if it has not yet been run.
  1115. // Most uses of this package need not call Handshake
  1116. // explicitly: the first Read or Write will call it automatically.
  1117. func (c *Conn) Handshake() error {
  1118. c.handshakeMutex.Lock()
  1119. defer c.handshakeMutex.Unlock()
  1120. if err := c.handshakeErr; err != nil {
  1121. return err
  1122. }
  1123. if c.handshakeComplete {
  1124. return nil
  1125. }
  1126. if c.isClient {
  1127. c.handshakeErr = c.clientHandshake()
  1128. } else {
  1129. c.handshakeErr = c.serverHandshake()
  1130. }
  1131. if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
  1132. c.writeRecord(recordType(42), []byte("invalid record"))
  1133. }
  1134. return c.handshakeErr
  1135. }
  1136. // ConnectionState returns basic TLS details about the connection.
  1137. func (c *Conn) ConnectionState() ConnectionState {
  1138. c.handshakeMutex.Lock()
  1139. defer c.handshakeMutex.Unlock()
  1140. var state ConnectionState
  1141. state.HandshakeComplete = c.handshakeComplete
  1142. if c.handshakeComplete {
  1143. state.Version = c.vers
  1144. state.NegotiatedProtocol = c.clientProtocol
  1145. state.DidResume = c.didResume
  1146. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1147. state.NegotiatedProtocolFromALPN = c.usedALPN
  1148. state.CipherSuite = c.cipherSuite.id
  1149. state.PeerCertificates = c.peerCertificates
  1150. state.VerifiedChains = c.verifiedChains
  1151. state.ServerName = c.serverName
  1152. state.ChannelID = c.channelID
  1153. state.SRTPProtectionProfile = c.srtpProtectionProfile
  1154. }
  1155. return state
  1156. }
  1157. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1158. // any. (Only valid for client connections.)
  1159. func (c *Conn) OCSPResponse() []byte {
  1160. c.handshakeMutex.Lock()
  1161. defer c.handshakeMutex.Unlock()
  1162. return c.ocspResponse
  1163. }
  1164. // VerifyHostname checks that the peer certificate chain is valid for
  1165. // connecting to host. If so, it returns nil; if not, it returns an error
  1166. // describing the problem.
  1167. func (c *Conn) VerifyHostname(host string) error {
  1168. c.handshakeMutex.Lock()
  1169. defer c.handshakeMutex.Unlock()
  1170. if !c.isClient {
  1171. return errors.New("tls: VerifyHostname called on TLS server connection")
  1172. }
  1173. if !c.handshakeComplete {
  1174. return errors.New("tls: handshake has not yet been performed")
  1175. }
  1176. return c.peerCertificates[0].VerifyHostname(host)
  1177. }
  1178. // ExportKeyingMaterial exports keying material from the current connection
  1179. // state, as per RFC 5705.
  1180. func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
  1181. c.handshakeMutex.Lock()
  1182. defer c.handshakeMutex.Unlock()
  1183. if !c.handshakeComplete {
  1184. return nil, errors.New("tls: handshake has not yet been performed")
  1185. }
  1186. seedLen := len(c.clientRandom) + len(c.serverRandom)
  1187. if useContext {
  1188. seedLen += 2 + len(context)
  1189. }
  1190. seed := make([]byte, 0, seedLen)
  1191. seed = append(seed, c.clientRandom[:]...)
  1192. seed = append(seed, c.serverRandom[:]...)
  1193. if useContext {
  1194. seed = append(seed, byte(len(context)>>8), byte(len(context)))
  1195. seed = append(seed, context...)
  1196. }
  1197. result := make([]byte, length)
  1198. prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
  1199. return result, nil
  1200. }