選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

1639 行
45 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 tls
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net"
  15. "sync"
  16. "sync/atomic"
  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. isClient bool
  25. phase handshakeStatus // protected by in.Mutex
  26. // handshakeConfirmed is an atomic bool for phase == handshakeConfirmed
  27. handshakeConfirmed int32
  28. // confirmMutex is held by any read operation before handshakeConfirmed
  29. confirmMutex sync.Mutex
  30. // constant after handshake; protected by handshakeMutex
  31. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  32. handshakeErr error // error resulting from handshake
  33. connID []byte // Random connection id
  34. clientHello []byte // ClientHello packet contents
  35. vers uint16 // TLS version
  36. haveVers bool // version has been negotiated
  37. config *Config // configuration passed to constructor
  38. // handshakeComplete is true if the connection reached application data
  39. // and it's equivalent to phase > handshakeRunning
  40. handshakeComplete bool
  41. // handshakes counts the number of handshakes performed on the
  42. // connection so far. If renegotiation is disabled then this is either
  43. // zero or one.
  44. handshakes int
  45. didResume bool // whether this connection was a session resumption
  46. cipherSuite uint16
  47. ocspResponse []byte // stapled OCSP response
  48. scts [][]byte // signed certificate timestamps from server
  49. peerCertificates []*x509.Certificate
  50. // verifiedChains contains the certificate chains that we built, as
  51. // opposed to the ones presented by the server.
  52. verifiedChains [][]*x509.Certificate
  53. // serverName contains the server name indicated by the client, if any.
  54. serverName string
  55. // secureRenegotiation is true if the server echoed the secure
  56. // renegotiation extension. (This is meaningless as a server because
  57. // renegotiation is not supported in that case.)
  58. secureRenegotiation bool
  59. // clientFinishedIsFirst is true if the client sent the first Finished
  60. // message during the most recent handshake. This is recorded because
  61. // the first transmitted Finished message is the tls-unique
  62. // channel-binding value.
  63. clientFinishedIsFirst bool
  64. // closeNotifyErr is any error from sending the alertCloseNotify record.
  65. closeNotifyErr error
  66. // closeNotifySent is true if the Conn attempted to send an
  67. // alertCloseNotify record.
  68. closeNotifySent bool
  69. // clientFinished and serverFinished contain the Finished message sent
  70. // by the client or server in the most recent handshake. This is
  71. // retained to support the renegotiation extension and tls-unique
  72. // channel-binding.
  73. clientFinished [12]byte
  74. serverFinished [12]byte
  75. clientProtocol string
  76. clientProtocolFallback bool
  77. // ticketMaxEarlyData is the maximum bytes of 0-RTT application data
  78. // that the client is allowed to send on the ticket it used.
  79. ticketMaxEarlyData int64
  80. // input/output
  81. in, out halfConn // in.Mutex < out.Mutex
  82. rawInput *block // raw input, right off the wire
  83. input *block // application data waiting to be read
  84. hand bytes.Buffer // handshake data waiting to be read
  85. buffering bool // whether records are buffered in sendBuf
  86. sendBuf []byte // a buffer of records waiting to be sent
  87. // bytesSent counts the bytes of application data sent.
  88. // packetsSent counts packets.
  89. bytesSent int64
  90. packetsSent int64
  91. // activeCall is an atomic int32; the low bit is whether Close has
  92. // been called. the rest of the bits are the number of goroutines
  93. // in Conn.Write.
  94. activeCall int32
  95. // TLS 1.3 needs the server state until it reaches the Client Finished
  96. hs *serverHandshakeState
  97. // earlyDataBytes is the number of bytes of early data received so
  98. // far. Tracked to enforce max_early_data_size.
  99. // We don't keep track of rejected 0-RTT data since there's no need
  100. // to ever buffer it. in.Mutex.
  101. earlyDataBytes int64
  102. // binder is the value of the PSK binder that was validated to
  103. // accept the 0-RTT data. Exposed as ConnectionState.Unique0RTTToken.
  104. binder []byte
  105. tmp [16]byte
  106. }
  107. type handshakeStatus int
  108. const (
  109. handshakeRunning handshakeStatus = iota
  110. discardingEarlyData
  111. readingEarlyData
  112. waitingClientFinished
  113. readingClientFinished
  114. handshakeConfirmed
  115. )
  116. // Access to net.Conn methods.
  117. // Cannot just embed net.Conn because that would
  118. // export the struct field too.
  119. // LocalAddr returns the local network address.
  120. func (c *Conn) LocalAddr() net.Addr {
  121. return c.conn.LocalAddr()
  122. }
  123. // RemoteAddr returns the remote network address.
  124. func (c *Conn) RemoteAddr() net.Addr {
  125. return c.conn.RemoteAddr()
  126. }
  127. // SetDeadline sets the read and write deadlines associated with the connection.
  128. // A zero value for t means Read and Write will not time out.
  129. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  130. func (c *Conn) SetDeadline(t time.Time) error {
  131. return c.conn.SetDeadline(t)
  132. }
  133. // SetReadDeadline sets the read deadline on the underlying connection.
  134. // A zero value for t means Read will not time out.
  135. func (c *Conn) SetReadDeadline(t time.Time) error {
  136. return c.conn.SetReadDeadline(t)
  137. }
  138. // SetWriteDeadline sets the write deadline on the underlying connection.
  139. // A zero value for t means Write will not time out.
  140. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  141. func (c *Conn) SetWriteDeadline(t time.Time) error {
  142. return c.conn.SetWriteDeadline(t)
  143. }
  144. // A halfConn represents one direction of the record layer
  145. // connection, either sending or receiving.
  146. type halfConn struct {
  147. sync.Mutex
  148. err error // first permanent error
  149. version uint16 // protocol version
  150. cipher interface{} // cipher algorithm
  151. mac macFunction
  152. seq [8]byte // 64-bit sequence number
  153. bfree *block // list of free blocks
  154. additionalData [13]byte // to avoid allocs; interface method args escape
  155. nextCipher interface{} // next encryption state
  156. nextMac macFunction // next MAC algorithm
  157. // used to save allocating a new buffer for each MAC.
  158. inDigestBuf, outDigestBuf []byte
  159. traceErr func(error)
  160. }
  161. func (hc *halfConn) setErrorLocked(err error) error {
  162. hc.err = err
  163. if hc.traceErr != nil {
  164. hc.traceErr(err)
  165. }
  166. return err
  167. }
  168. // prepareCipherSpec sets the encryption and MAC states
  169. // that a subsequent changeCipherSpec will use.
  170. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  171. hc.version = version
  172. hc.nextCipher = cipher
  173. hc.nextMac = mac
  174. }
  175. // changeCipherSpec changes the encryption and MAC states
  176. // to the ones previously passed to prepareCipherSpec.
  177. func (hc *halfConn) changeCipherSpec() error {
  178. if hc.nextCipher == nil {
  179. return alertInternalError
  180. }
  181. hc.cipher = hc.nextCipher
  182. hc.mac = hc.nextMac
  183. hc.nextCipher = nil
  184. hc.nextMac = nil
  185. for i := range hc.seq {
  186. hc.seq[i] = 0
  187. }
  188. return nil
  189. }
  190. func (hc *halfConn) setCipher(version uint16, cipher interface{}) {
  191. hc.version = version
  192. hc.cipher = cipher
  193. for i := range hc.seq {
  194. hc.seq[i] = 0
  195. }
  196. }
  197. // incSeq increments the sequence number.
  198. func (hc *halfConn) incSeq() {
  199. for i := 7; i >= 0; i-- {
  200. hc.seq[i]++
  201. if hc.seq[i] != 0 {
  202. return
  203. }
  204. }
  205. // Not allowed to let sequence number wrap.
  206. // Instead, must renegotiate before it does.
  207. // Not likely enough to bother.
  208. panic("TLS: sequence number wraparound")
  209. }
  210. // extractPadding returns, in constant time, the length of the padding to remove
  211. // from the end of payload. It also returns a byte which is equal to 255 if the
  212. // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  213. func extractPadding(payload []byte) (toRemove int, good byte) {
  214. if len(payload) < 1 {
  215. return 0, 0
  216. }
  217. paddingLen := payload[len(payload)-1]
  218. t := uint(len(payload)-1) - uint(paddingLen)
  219. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  220. good = byte(int32(^t) >> 31)
  221. toCheck := 255 // the maximum possible padding length
  222. // The length of the padded data is public, so we can use an if here
  223. if toCheck+1 > len(payload) {
  224. toCheck = len(payload) - 1
  225. }
  226. for i := 0; i < toCheck; i++ {
  227. t := uint(paddingLen) - uint(i)
  228. // if i <= paddingLen then the MSB of t is zero
  229. mask := byte(int32(^t) >> 31)
  230. b := payload[len(payload)-1-i]
  231. good &^= mask&paddingLen ^ mask&b
  232. }
  233. // We AND together the bits of good and replicate the result across
  234. // all the bits.
  235. good &= good << 4
  236. good &= good << 2
  237. good &= good << 1
  238. good = uint8(int8(good) >> 7)
  239. toRemove = int(paddingLen) + 1
  240. return
  241. }
  242. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  243. // protocol version is SSLv3. In this version, the contents of the padding
  244. // are random and cannot be checked.
  245. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  246. if len(payload) < 1 {
  247. return 0, 0
  248. }
  249. paddingLen := int(payload[len(payload)-1]) + 1
  250. if paddingLen > len(payload) {
  251. return 0, 0
  252. }
  253. return paddingLen, 255
  254. }
  255. func roundUp(a, b int) int {
  256. return a + (b-a%b)%b
  257. }
  258. // cbcMode is an interface for block ciphers using cipher block chaining.
  259. type cbcMode interface {
  260. cipher.BlockMode
  261. SetIV([]byte)
  262. }
  263. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  264. // success boolean, the number of bytes to skip from the start of the record in
  265. // order to get the application payload, and an optional alert value.
  266. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  267. // pull out payload
  268. payload := b.data[recordHeaderLen:]
  269. macSize := 0
  270. if hc.mac != nil {
  271. macSize = hc.mac.Size()
  272. }
  273. paddingGood := byte(255)
  274. paddingLen := 0
  275. explicitIVLen := 0
  276. // decrypt
  277. if hc.cipher != nil {
  278. switch c := hc.cipher.(type) {
  279. case cipher.Stream:
  280. c.XORKeyStream(payload, payload)
  281. case aead:
  282. explicitIVLen = c.explicitNonceLen()
  283. if len(payload) < explicitIVLen {
  284. return false, 0, alertBadRecordMAC
  285. }
  286. nonce := payload[:explicitIVLen]
  287. payload = payload[explicitIVLen:]
  288. if len(nonce) == 0 {
  289. nonce = hc.seq[:]
  290. }
  291. var additionalData []byte
  292. if hc.version < VersionTLS13 {
  293. copy(hc.additionalData[:], hc.seq[:])
  294. copy(hc.additionalData[8:], b.data[:3])
  295. n := len(payload) - c.Overhead()
  296. hc.additionalData[11] = byte(n >> 8)
  297. hc.additionalData[12] = byte(n)
  298. additionalData = hc.additionalData[:]
  299. }
  300. var err error
  301. payload, err = c.Open(payload[:0], nonce, payload, additionalData)
  302. if err != nil {
  303. return false, 0, alertBadRecordMAC
  304. }
  305. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  306. case cbcMode:
  307. blockSize := c.BlockSize()
  308. if hc.version >= VersionTLS11 {
  309. explicitIVLen = blockSize
  310. }
  311. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  312. return false, 0, alertBadRecordMAC
  313. }
  314. if explicitIVLen > 0 {
  315. c.SetIV(payload[:explicitIVLen])
  316. payload = payload[explicitIVLen:]
  317. }
  318. c.CryptBlocks(payload, payload)
  319. if hc.version == VersionSSL30 {
  320. paddingLen, paddingGood = extractPaddingSSL30(payload)
  321. } else {
  322. paddingLen, paddingGood = extractPadding(payload)
  323. // To protect against CBC padding oracles like Lucky13, the data
  324. // past paddingLen (which is secret) is passed to the MAC
  325. // function as extra data, to be fed into the HMAC after
  326. // computing the digest. This makes the MAC constant time as
  327. // long as the digest computation is constant time and does not
  328. // affect the subsequent write.
  329. }
  330. default:
  331. panic("unknown cipher type")
  332. }
  333. }
  334. // check, strip mac
  335. if hc.mac != nil {
  336. if len(payload) < macSize {
  337. return false, 0, alertBadRecordMAC
  338. }
  339. // strip mac off payload, b.data
  340. n := len(payload) - macSize - paddingLen
  341. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  342. b.data[3] = byte(n >> 8)
  343. b.data[4] = byte(n)
  344. remoteMAC := payload[n : n+macSize]
  345. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
  346. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  347. return false, 0, alertBadRecordMAC
  348. }
  349. hc.inDigestBuf = localMAC
  350. b.resize(recordHeaderLen + explicitIVLen + n)
  351. }
  352. hc.incSeq()
  353. return true, recordHeaderLen + explicitIVLen, 0
  354. }
  355. // padToBlockSize calculates the needed padding block, if any, for a payload.
  356. // On exit, prefix aliases payload and extends to the end of the last full
  357. // block of payload. finalBlock is a fresh slice which contains the contents of
  358. // any suffix of payload as well as the needed padding to make finalBlock a
  359. // full block.
  360. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  361. overrun := len(payload) % blockSize
  362. paddingLen := blockSize - overrun
  363. prefix = payload[:len(payload)-overrun]
  364. finalBlock = make([]byte, blockSize)
  365. copy(finalBlock, payload[len(payload)-overrun:])
  366. for i := overrun; i < blockSize; i++ {
  367. finalBlock[i] = byte(paddingLen - 1)
  368. }
  369. return
  370. }
  371. // encrypt encrypts and macs the data in b.
  372. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  373. // mac
  374. if hc.mac != nil {
  375. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
  376. n := len(b.data)
  377. b.resize(n + len(mac))
  378. copy(b.data[n:], mac)
  379. hc.outDigestBuf = mac
  380. }
  381. payload := b.data[recordHeaderLen:]
  382. // encrypt
  383. if hc.cipher != nil {
  384. switch c := hc.cipher.(type) {
  385. case cipher.Stream:
  386. c.XORKeyStream(payload, payload)
  387. case aead:
  388. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  389. overhead := c.Overhead()
  390. if hc.version >= VersionTLS13 {
  391. overhead++
  392. }
  393. b.resize(len(b.data) + overhead)
  394. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  395. if len(nonce) == 0 {
  396. nonce = hc.seq[:]
  397. }
  398. payload = b.data[recordHeaderLen+explicitIVLen:]
  399. payload = payload[:payloadLen]
  400. var additionalData []byte
  401. if hc.version < VersionTLS13 {
  402. copy(hc.additionalData[:], hc.seq[:])
  403. copy(hc.additionalData[8:], b.data[:3])
  404. hc.additionalData[11] = byte(payloadLen >> 8)
  405. hc.additionalData[12] = byte(payloadLen)
  406. additionalData = hc.additionalData[:]
  407. }
  408. if hc.version >= VersionTLS13 {
  409. // opaque type
  410. payload = payload[:len(payload)+1]
  411. payload[len(payload)-1] = b.data[0]
  412. b.data[0] = byte(recordTypeApplicationData)
  413. }
  414. c.Seal(payload[:0], nonce, payload, additionalData)
  415. case cbcMode:
  416. blockSize := c.BlockSize()
  417. if explicitIVLen > 0 {
  418. c.SetIV(payload[:explicitIVLen])
  419. payload = payload[explicitIVLen:]
  420. }
  421. prefix, finalBlock := padToBlockSize(payload, blockSize)
  422. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  423. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  424. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  425. default:
  426. panic("unknown cipher type")
  427. }
  428. }
  429. // update length to include MAC and any block padding needed.
  430. n := len(b.data) - recordHeaderLen
  431. b.data[3] = byte(n >> 8)
  432. b.data[4] = byte(n)
  433. hc.incSeq()
  434. return true, 0
  435. }
  436. // A block is a simple data buffer.
  437. type block struct {
  438. data []byte
  439. off int // index for Read
  440. link *block
  441. }
  442. // resize resizes block to be n bytes, growing if necessary.
  443. func (b *block) resize(n int) {
  444. if n > cap(b.data) {
  445. b.reserve(n)
  446. }
  447. b.data = b.data[0:n]
  448. }
  449. // reserve makes sure that block contains a capacity of at least n bytes.
  450. func (b *block) reserve(n int) {
  451. if cap(b.data) >= n {
  452. return
  453. }
  454. m := cap(b.data)
  455. if m == 0 {
  456. m = 1024
  457. }
  458. for m < n {
  459. m *= 2
  460. }
  461. data := make([]byte, len(b.data), m)
  462. copy(data, b.data)
  463. b.data = data
  464. }
  465. // readFromUntil reads from r into b until b contains at least n bytes
  466. // or else returns an error.
  467. func (b *block) readFromUntil(r io.Reader, n int) error {
  468. // quick case
  469. if len(b.data) >= n {
  470. return nil
  471. }
  472. // read until have enough.
  473. b.reserve(n)
  474. for {
  475. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  476. b.data = b.data[0 : len(b.data)+m]
  477. if len(b.data) >= n {
  478. // TODO(bradfitz,agl): slightly suspicious
  479. // that we're throwing away r.Read's err here.
  480. break
  481. }
  482. if err != nil {
  483. return err
  484. }
  485. }
  486. return nil
  487. }
  488. func (b *block) Read(p []byte) (n int, err error) {
  489. n = copy(p, b.data[b.off:])
  490. b.off += n
  491. if b.off >= len(b.data) {
  492. err = io.EOF
  493. }
  494. return
  495. }
  496. // newBlock allocates a new block, from hc's free list if possible.
  497. func (hc *halfConn) newBlock() *block {
  498. b := hc.bfree
  499. if b == nil {
  500. return new(block)
  501. }
  502. hc.bfree = b.link
  503. b.link = nil
  504. b.resize(0)
  505. return b
  506. }
  507. // freeBlock returns a block to hc's free list.
  508. // The protocol is such that each side only has a block or two on
  509. // its free list at a time, so there's no need to worry about
  510. // trimming the list, etc.
  511. func (hc *halfConn) freeBlock(b *block) {
  512. b.link = hc.bfree
  513. hc.bfree = b
  514. }
  515. // splitBlock splits a block after the first n bytes,
  516. // returning a block with those n bytes and a
  517. // block with the remainder. the latter may be nil.
  518. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  519. if len(b.data) <= n {
  520. return b, nil
  521. }
  522. bb := hc.newBlock()
  523. bb.resize(len(b.data) - n)
  524. copy(bb.data, b.data[n:])
  525. b.data = b.data[0:n]
  526. return b, bb
  527. }
  528. // RecordHeaderError results when a TLS record header is invalid.
  529. type RecordHeaderError struct {
  530. // Msg contains a human readable string that describes the error.
  531. Msg string
  532. // RecordHeader contains the five bytes of TLS record header that
  533. // triggered the error.
  534. RecordHeader [5]byte
  535. }
  536. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  537. func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
  538. err.Msg = msg
  539. copy(err.RecordHeader[:], c.rawInput.data)
  540. return err
  541. }
  542. // readRecord reads the next TLS record from the connection
  543. // and updates the record layer state.
  544. // c.in.Mutex <= L; c.input == nil.
  545. // c.input can still be nil after a call, retry if so.
  546. func (c *Conn) readRecord(want recordType) error {
  547. // Caller must be in sync with connection:
  548. // handshake data if handshake not yet completed,
  549. // else application data.
  550. switch want {
  551. default:
  552. c.sendAlert(alertInternalError)
  553. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  554. case recordTypeHandshake, recordTypeChangeCipherSpec:
  555. if c.phase != handshakeRunning && c.phase != readingClientFinished {
  556. c.sendAlert(alertInternalError)
  557. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
  558. }
  559. case recordTypeApplicationData:
  560. if c.phase == handshakeRunning || c.phase == readingClientFinished {
  561. c.sendAlert(alertInternalError)
  562. return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
  563. }
  564. }
  565. if c.rawInput == nil {
  566. c.rawInput = c.in.newBlock()
  567. }
  568. b := c.rawInput
  569. // Read header, payload.
  570. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  571. // RFC suggests that EOF without an alertCloseNotify is
  572. // an error, but popular web sites seem to do this,
  573. // so we can't make it an error.
  574. // if err == io.EOF {
  575. // err = io.ErrUnexpectedEOF
  576. // }
  577. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  578. c.in.setErrorLocked(err)
  579. }
  580. return err
  581. }
  582. typ := recordType(b.data[0])
  583. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  584. // start with a uint16 length where the MSB is set and the first record
  585. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  586. // an SSLv2 client.
  587. if want == recordTypeHandshake && typ == 0x80 {
  588. c.sendAlert(alertProtocolVersion)
  589. return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
  590. }
  591. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  592. n := int(b.data[3])<<8 | int(b.data[4])
  593. if n > maxCiphertext {
  594. c.sendAlert(alertRecordOverflow)
  595. msg := fmt.Sprintf("oversized record received with length %d", n)
  596. return c.in.setErrorLocked(c.newRecordHeaderError(msg))
  597. }
  598. if !c.haveVers {
  599. // First message, be extra suspicious: this might not be a TLS
  600. // client. Bail out before reading a full 'body', if possible.
  601. // The current max version is 3.3 so if the version is >= 16.0,
  602. // it's probably not real.
  603. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  604. c.sendAlert(alertUnexpectedMessage)
  605. return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
  606. }
  607. }
  608. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  609. if err == io.EOF {
  610. err = io.ErrUnexpectedEOF
  611. }
  612. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  613. c.in.setErrorLocked(err)
  614. }
  615. return err
  616. }
  617. // Process message.
  618. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  619. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  620. ok, off, alertValue := c.in.decrypt(b)
  621. switch {
  622. case !ok && c.phase == discardingEarlyData:
  623. // If the client said that it's sending early data and we did not
  624. // accept it, we are expected to fail decryption.
  625. c.in.freeBlock(b)
  626. return nil
  627. case ok && c.phase == discardingEarlyData:
  628. c.phase = waitingClientFinished
  629. case !ok:
  630. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  631. c.in.freeBlock(b)
  632. err := c.sendAlert(alertValue)
  633. // If decryption failed because the message is an unencrypted
  634. // alert, return a more meaningful error message
  635. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  636. err = peekedAlert
  637. }
  638. return c.in.setErrorLocked(err)
  639. }
  640. b.off = off
  641. data := b.data[b.off:]
  642. if len(data) > maxPlaintext {
  643. c.in.freeBlock(b)
  644. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  645. }
  646. // After checking the plaintext length, remove 1.3 padding and
  647. // extract the real content type.
  648. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  649. if c.vers >= VersionTLS13 {
  650. i := len(data) - 1
  651. for i >= 0 {
  652. if data[i] != 0 {
  653. break
  654. }
  655. i--
  656. }
  657. if i < 0 {
  658. c.in.freeBlock(b)
  659. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  660. }
  661. typ = recordType(data[i])
  662. data = data[:i]
  663. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  664. }
  665. switch typ {
  666. default:
  667. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  668. case recordTypeAlert:
  669. if len(data) != 2 {
  670. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  671. break
  672. }
  673. if alert(data[1]) == alertCloseNotify {
  674. c.in.setErrorLocked(io.EOF)
  675. break
  676. }
  677. if alert(data[1]) == alertEndOfEarlyData {
  678. c.handleEndOfEarlyData()
  679. break
  680. }
  681. switch data[0] {
  682. case alertLevelWarning:
  683. // drop on the floor
  684. c.in.freeBlock(b)
  685. return nil
  686. case alertLevelError:
  687. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  688. default:
  689. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  690. }
  691. case recordTypeChangeCipherSpec:
  692. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  693. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  694. break
  695. }
  696. // Handshake messages are not allowed to fragment across the CCS
  697. if c.hand.Len() > 0 {
  698. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  699. break
  700. }
  701. err := c.in.changeCipherSpec()
  702. if err != nil {
  703. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  704. }
  705. case recordTypeApplicationData:
  706. if typ != want || c.phase == waitingClientFinished {
  707. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  708. break
  709. }
  710. if c.phase == readingEarlyData {
  711. c.earlyDataBytes += int64(len(b.data) - b.off)
  712. if c.earlyDataBytes > c.ticketMaxEarlyData {
  713. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  714. }
  715. }
  716. c.input = b
  717. b = nil
  718. case recordTypeHandshake:
  719. // TODO(rsc): Should at least pick off connection close.
  720. if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) &&
  721. c.phase != waitingClientFinished {
  722. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  723. }
  724. c.hand.Write(data)
  725. if typ != want && c.phase == waitingClientFinished {
  726. if err := c.hs.readClientFinished13(); err != nil {
  727. c.in.setErrorLocked(err)
  728. break
  729. }
  730. }
  731. }
  732. if b != nil {
  733. c.in.freeBlock(b)
  734. }
  735. return c.in.err
  736. }
  737. // peekAlert looks at a message to spot an unencrypted alert. It must be
  738. // called before decryption to avoid a side channel, and its result must
  739. // only be used if decryption fails, to avoid false positives.
  740. func peekAlert(b *block) error {
  741. if len(b.data) < 7 {
  742. return nil
  743. }
  744. if recordType(b.data[0]) != recordTypeAlert {
  745. return nil
  746. }
  747. return &net.OpError{Op: "remote error", Err: alert(b.data[6])}
  748. }
  749. // sendAlert sends a TLS alert message.
  750. // c.out.Mutex <= L.
  751. func (c *Conn) sendAlertLocked(err alert) error {
  752. switch err {
  753. case alertNoRenegotiation, alertCloseNotify:
  754. c.tmp[0] = alertLevelWarning
  755. default:
  756. c.tmp[0] = alertLevelError
  757. }
  758. c.tmp[1] = byte(err)
  759. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  760. if err == alertCloseNotify {
  761. // closeNotify is a special case in that it isn't an error.
  762. return writeErr
  763. }
  764. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  765. }
  766. // sendAlert sends a TLS alert message.
  767. // L < c.out.Mutex.
  768. func (c *Conn) sendAlert(err alert) error {
  769. c.out.Lock()
  770. defer c.out.Unlock()
  771. return c.sendAlertLocked(err)
  772. }
  773. const (
  774. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  775. // size (MSS). A constant is used, rather than querying the kernel for
  776. // the actual MSS, to avoid complexity. The value here is the IPv6
  777. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  778. // bytes) and a TCP header with timestamps (32 bytes).
  779. tcpMSSEstimate = 1208
  780. // recordSizeBoostThreshold is the number of bytes of application data
  781. // sent after which the TLS record size will be increased to the
  782. // maximum.
  783. recordSizeBoostThreshold = 128 * 1024
  784. )
  785. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  786. // next application data record. There is the following trade-off:
  787. //
  788. // - For latency-sensitive applications, such as web browsing, each TLS
  789. // record should fit in one TCP segment.
  790. // - For throughput-sensitive applications, such as large file transfers,
  791. // larger TLS records better amortize framing and encryption overheads.
  792. //
  793. // A simple heuristic that works well in practice is to use small records for
  794. // the first 1MB of data, then use larger records for subsequent data, and
  795. // reset back to smaller records after the connection becomes idle. See "High
  796. // Performance Web Networking", Chapter 4, or:
  797. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  798. //
  799. // In the interests of simplicity and determinism, this code does not attempt
  800. // to reset the record size once the connection is idle, however.
  801. //
  802. // c.out.Mutex <= L.
  803. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  804. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  805. return maxPlaintext
  806. }
  807. if c.bytesSent >= recordSizeBoostThreshold {
  808. return maxPlaintext
  809. }
  810. // Subtract TLS overheads to get the maximum payload size.
  811. macSize := 0
  812. if c.out.mac != nil {
  813. macSize = c.out.mac.Size()
  814. }
  815. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  816. if c.out.cipher != nil {
  817. switch ciph := c.out.cipher.(type) {
  818. case cipher.Stream:
  819. payloadBytes -= macSize
  820. case cipher.AEAD:
  821. payloadBytes -= ciph.Overhead()
  822. if c.vers >= VersionTLS13 {
  823. payloadBytes -= 1 // ContentType
  824. }
  825. case cbcMode:
  826. blockSize := ciph.BlockSize()
  827. // The payload must fit in a multiple of blockSize, with
  828. // room for at least one padding byte.
  829. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  830. // The MAC is appended before padding so affects the
  831. // payload size directly.
  832. payloadBytes -= macSize
  833. default:
  834. panic("unknown cipher type")
  835. }
  836. }
  837. // Allow packet growth in arithmetic progression up to max.
  838. pkt := c.packetsSent
  839. c.packetsSent++
  840. if pkt > 1000 {
  841. return maxPlaintext // avoid overflow in multiply below
  842. }
  843. n := payloadBytes * int(pkt+1)
  844. if n > maxPlaintext {
  845. n = maxPlaintext
  846. }
  847. return n
  848. }
  849. // c.out.Mutex <= L.
  850. func (c *Conn) write(data []byte) (int, error) {
  851. if c.buffering {
  852. c.sendBuf = append(c.sendBuf, data...)
  853. return len(data), nil
  854. }
  855. n, err := c.conn.Write(data)
  856. c.bytesSent += int64(n)
  857. return n, err
  858. }
  859. func (c *Conn) flush() (int, error) {
  860. if len(c.sendBuf) == 0 {
  861. return 0, nil
  862. }
  863. n, err := c.conn.Write(c.sendBuf)
  864. c.bytesSent += int64(n)
  865. c.sendBuf = nil
  866. c.buffering = false
  867. return n, err
  868. }
  869. // writeRecordLocked writes a TLS record with the given type and payload to the
  870. // connection and updates the record layer state.
  871. // c.out.Mutex <= L.
  872. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  873. b := c.out.newBlock()
  874. defer c.out.freeBlock(b)
  875. var n int
  876. for len(data) > 0 {
  877. explicitIVLen := 0
  878. explicitIVIsSeq := false
  879. var cbc cbcMode
  880. if c.out.version >= VersionTLS11 {
  881. var ok bool
  882. if cbc, ok = c.out.cipher.(cbcMode); ok {
  883. explicitIVLen = cbc.BlockSize()
  884. }
  885. }
  886. if explicitIVLen == 0 {
  887. if c, ok := c.out.cipher.(aead); ok {
  888. explicitIVLen = c.explicitNonceLen()
  889. // The AES-GCM construction in TLS has an
  890. // explicit nonce so that the nonce can be
  891. // random. However, the nonce is only 8 bytes
  892. // which is too small for a secure, random
  893. // nonce. Therefore we use the sequence number
  894. // as the nonce.
  895. explicitIVIsSeq = explicitIVLen > 0
  896. }
  897. }
  898. m := len(data)
  899. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  900. m = maxPayload
  901. }
  902. b.resize(recordHeaderLen + explicitIVLen + m)
  903. b.data[0] = byte(typ)
  904. vers := c.vers
  905. if vers == 0 {
  906. // Some TLS servers fail if the record version is
  907. // greater than TLS 1.0 for the initial ClientHello.
  908. vers = VersionTLS10
  909. }
  910. if c.vers >= VersionTLS13 {
  911. // TLS 1.3 froze the record layer version at { 3, 1 }.
  912. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.1.
  913. vers = VersionTLS10
  914. }
  915. b.data[1] = byte(vers >> 8)
  916. b.data[2] = byte(vers)
  917. b.data[3] = byte(m >> 8)
  918. b.data[4] = byte(m)
  919. if explicitIVLen > 0 {
  920. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  921. if explicitIVIsSeq {
  922. copy(explicitIV, c.out.seq[:])
  923. } else {
  924. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  925. return n, err
  926. }
  927. }
  928. }
  929. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  930. c.out.encrypt(b, explicitIVLen)
  931. if _, err := c.write(b.data); err != nil {
  932. return n, err
  933. }
  934. n += m
  935. data = data[m:]
  936. }
  937. if typ == recordTypeChangeCipherSpec {
  938. if err := c.out.changeCipherSpec(); err != nil {
  939. return n, c.sendAlertLocked(err.(alert))
  940. }
  941. }
  942. return n, nil
  943. }
  944. // writeRecord writes a TLS record with the given type and payload to the
  945. // connection and updates the record layer state.
  946. // L < c.out.Mutex.
  947. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  948. c.out.Lock()
  949. defer c.out.Unlock()
  950. return c.writeRecordLocked(typ, data)
  951. }
  952. // readHandshake reads the next handshake message from
  953. // the record layer.
  954. // c.in.Mutex < L; c.out.Mutex < L.
  955. func (c *Conn) readHandshake() (interface{}, error) {
  956. for c.hand.Len() < 4 {
  957. if err := c.in.err; err != nil {
  958. return nil, err
  959. }
  960. if err := c.readRecord(recordTypeHandshake); err != nil {
  961. return nil, err
  962. }
  963. }
  964. data := c.hand.Bytes()
  965. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  966. if n > maxHandshake {
  967. c.sendAlertLocked(alertInternalError)
  968. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  969. }
  970. for c.hand.Len() < 4+n {
  971. if err := c.in.err; err != nil {
  972. return nil, err
  973. }
  974. if err := c.readRecord(recordTypeHandshake); err != nil {
  975. return nil, err
  976. }
  977. }
  978. data = c.hand.Next(4 + n)
  979. var m handshakeMessage
  980. switch data[0] {
  981. case typeHelloRequest:
  982. m = new(helloRequestMsg)
  983. case typeClientHello:
  984. m = new(clientHelloMsg)
  985. case typeServerHello:
  986. if c.vers >= VersionTLS13 {
  987. m = new(serverHelloMsg13)
  988. } else {
  989. m = new(serverHelloMsg)
  990. }
  991. case typeEncryptedExtensions:
  992. m = new(encryptedExtensionsMsg)
  993. case typeNewSessionTicket:
  994. if c.vers >= VersionTLS13 {
  995. m = new(newSessionTicketMsg13)
  996. } else {
  997. m = new(newSessionTicketMsg)
  998. }
  999. case typeCertificate:
  1000. if c.vers >= VersionTLS13 {
  1001. m = new(certificateMsg13)
  1002. } else {
  1003. m = new(certificateMsg)
  1004. }
  1005. case typeCertificateRequest:
  1006. m = &certificateRequestMsg{
  1007. hasSignatureAndHash: c.vers >= VersionTLS12,
  1008. }
  1009. case typeCertificateStatus:
  1010. m = new(certificateStatusMsg)
  1011. case typeServerKeyExchange:
  1012. m = new(serverKeyExchangeMsg)
  1013. case typeServerHelloDone:
  1014. m = new(serverHelloDoneMsg)
  1015. case typeClientKeyExchange:
  1016. m = new(clientKeyExchangeMsg)
  1017. case typeCertificateVerify:
  1018. m = &certificateVerifyMsg{
  1019. hasSignatureAndHash: c.vers >= VersionTLS12,
  1020. }
  1021. case typeNextProtocol:
  1022. m = new(nextProtoMsg)
  1023. case typeFinished:
  1024. m = new(finishedMsg)
  1025. default:
  1026. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1027. }
  1028. // The handshake message unmarshalers
  1029. // expect to be able to keep references to data,
  1030. // so pass in a fresh copy that won't be overwritten.
  1031. data = append([]byte(nil), data...)
  1032. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1033. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1034. }
  1035. return m, nil
  1036. }
  1037. var (
  1038. errClosed = errors.New("tls: use of closed connection")
  1039. errShutdown = errors.New("tls: protocol is shutdown")
  1040. )
  1041. // Write writes data to the connection.
  1042. func (c *Conn) Write(b []byte) (int, error) {
  1043. // interlock with Close below
  1044. for {
  1045. x := atomic.LoadInt32(&c.activeCall)
  1046. if x&1 != 0 {
  1047. return 0, errClosed
  1048. }
  1049. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1050. defer atomic.AddInt32(&c.activeCall, -2)
  1051. break
  1052. }
  1053. }
  1054. if err := c.Handshake(); err != nil {
  1055. return 0, err
  1056. }
  1057. c.out.Lock()
  1058. defer c.out.Unlock()
  1059. if err := c.out.err; err != nil {
  1060. return 0, err
  1061. }
  1062. if !c.handshakeComplete {
  1063. return 0, alertInternalError
  1064. }
  1065. if c.closeNotifySent {
  1066. return 0, errShutdown
  1067. }
  1068. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1069. // attack when using block mode ciphers due to predictable IVs.
  1070. // This can be prevented by splitting each Application Data
  1071. // record into two records, effectively randomizing the IV.
  1072. //
  1073. // http://www.openssl.org/~bodo/tls-cbc.txt
  1074. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1075. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1076. var m int
  1077. if len(b) > 1 && c.vers <= VersionTLS10 {
  1078. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1079. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1080. if err != nil {
  1081. return n, c.out.setErrorLocked(err)
  1082. }
  1083. m, b = 1, b[1:]
  1084. }
  1085. }
  1086. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1087. return n + m, c.out.setErrorLocked(err)
  1088. }
  1089. // handleRenegotiation processes a HelloRequest handshake message.
  1090. // c.in.Mutex <= L
  1091. func (c *Conn) handleRenegotiation() error {
  1092. msg, err := c.readHandshake()
  1093. if err != nil {
  1094. return err
  1095. }
  1096. _, ok := msg.(*helloRequestMsg)
  1097. if !ok {
  1098. c.sendAlert(alertUnexpectedMessage)
  1099. return alertUnexpectedMessage
  1100. }
  1101. if !c.isClient {
  1102. return c.sendAlert(alertNoRenegotiation)
  1103. }
  1104. if c.vers >= VersionTLS13 {
  1105. return c.sendAlert(alertNoRenegotiation)
  1106. }
  1107. switch c.config.Renegotiation {
  1108. case RenegotiateNever:
  1109. return c.sendAlert(alertNoRenegotiation)
  1110. case RenegotiateOnceAsClient:
  1111. if c.handshakes > 1 {
  1112. return c.sendAlert(alertNoRenegotiation)
  1113. }
  1114. case RenegotiateFreelyAsClient:
  1115. // Ok.
  1116. default:
  1117. c.sendAlert(alertInternalError)
  1118. return errors.New("tls: unknown Renegotiation value")
  1119. }
  1120. c.handshakeMutex.Lock()
  1121. defer c.handshakeMutex.Unlock()
  1122. c.phase = handshakeRunning
  1123. c.handshakeComplete = false
  1124. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1125. c.handshakes++
  1126. }
  1127. return c.handshakeErr
  1128. }
  1129. // ConfirmHandshake waits for the handshake to reach a point at which
  1130. // the connection is certainly not replayed. That is, after receiving
  1131. // the Client Finished.
  1132. //
  1133. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1134. // returns, the 0-RTT data should not be trusted not to be replayed.
  1135. //
  1136. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1137. // client sent valid 0-RTT data. In any other case it's equivalent to
  1138. // calling Handshake.
  1139. func (c *Conn) ConfirmHandshake() error {
  1140. if err := c.Handshake(); err != nil {
  1141. return err
  1142. }
  1143. if c.vers < VersionTLS13 {
  1144. return nil
  1145. }
  1146. c.confirmMutex.Lock()
  1147. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1148. c.confirmMutex.Unlock()
  1149. return nil
  1150. } else {
  1151. defer func() {
  1152. // If we transitioned to handshakeConfirmed we already released the lock,
  1153. // otherwise do it here.
  1154. if c.phase != handshakeConfirmed {
  1155. c.confirmMutex.Unlock()
  1156. }
  1157. }()
  1158. }
  1159. c.in.Lock()
  1160. defer c.in.Unlock()
  1161. var input *block
  1162. if c.phase == readingEarlyData || c.input != nil {
  1163. buf := &bytes.Buffer{}
  1164. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1165. c.in.setErrorLocked(err)
  1166. return err
  1167. }
  1168. input = &block{data: buf.Bytes()}
  1169. }
  1170. for c.phase != handshakeConfirmed {
  1171. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1172. c.in.setErrorLocked(err)
  1173. return err
  1174. }
  1175. }
  1176. if c.phase != handshakeConfirmed {
  1177. panic("should have reached handshakeConfirmed state")
  1178. }
  1179. if c.input != nil {
  1180. panic("should not have read past the Client Finished")
  1181. }
  1182. c.input = input
  1183. return nil
  1184. }
  1185. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1186. // and still on the wire.
  1187. type earlyDataReader struct {
  1188. c *Conn
  1189. }
  1190. // c.in.Mutex <= L
  1191. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1192. c := r.c
  1193. if c.phase == handshakeConfirmed {
  1194. // c.input might not be early data
  1195. panic("earlyDataReader called at handshakeConfirmed")
  1196. }
  1197. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1198. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1199. return 0, err
  1200. }
  1201. }
  1202. if err := c.in.err; err != nil {
  1203. return 0, err
  1204. }
  1205. if c.input != nil {
  1206. n, err = c.input.Read(b)
  1207. if err == io.EOF {
  1208. err = nil
  1209. c.in.freeBlock(c.input)
  1210. c.input = nil
  1211. }
  1212. }
  1213. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1214. err = io.EOF
  1215. }
  1216. return
  1217. }
  1218. // Read can be made to time out and return a net.Error with Timeout() == true
  1219. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1220. func (c *Conn) Read(b []byte) (n int, err error) {
  1221. if err = c.Handshake(); err != nil {
  1222. return
  1223. }
  1224. if len(b) == 0 {
  1225. // Put this after Handshake, in case people were calling
  1226. // Read(nil) for the side effect of the Handshake.
  1227. return
  1228. }
  1229. c.confirmMutex.Lock()
  1230. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1231. c.confirmMutex.Unlock()
  1232. } else {
  1233. defer func() {
  1234. // If we transitioned to handshakeConfirmed we already released the lock,
  1235. // otherwise do it here.
  1236. if c.phase != handshakeConfirmed {
  1237. c.confirmMutex.Unlock()
  1238. }
  1239. }()
  1240. }
  1241. c.in.Lock()
  1242. defer c.in.Unlock()
  1243. // Some OpenSSL servers send empty records in order to randomize the
  1244. // CBC IV. So this loop ignores a limited number of empty records.
  1245. const maxConsecutiveEmptyRecords = 100
  1246. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1247. for c.input == nil && c.in.err == nil {
  1248. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1249. // Soft error, like EAGAIN
  1250. return 0, err
  1251. }
  1252. if c.hand.Len() > 0 {
  1253. // We received handshake bytes, indicating the
  1254. // start of a renegotiation.
  1255. if err := c.handleRenegotiation(); err != nil {
  1256. return 0, err
  1257. }
  1258. }
  1259. }
  1260. if err := c.in.err; err != nil {
  1261. return 0, err
  1262. }
  1263. n, err = c.input.Read(b)
  1264. if err == io.EOF {
  1265. err = nil
  1266. c.in.freeBlock(c.input)
  1267. c.input = nil
  1268. }
  1269. // If a close-notify alert is waiting, read it so that
  1270. // we can return (n, EOF) instead of (n, nil), to signal
  1271. // to the HTTP response reading goroutine that the
  1272. // connection is now closed. This eliminates a race
  1273. // where the HTTP response reading goroutine would
  1274. // otherwise not observe the EOF until its next read,
  1275. // by which time a client goroutine might have already
  1276. // tried to reuse the HTTP connection for a new
  1277. // request.
  1278. // See https://codereview.appspot.com/76400046
  1279. // and https://golang.org/issue/3514
  1280. if ri := c.rawInput; ri != nil &&
  1281. n != 0 && err == nil &&
  1282. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1283. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1284. err = recErr // will be io.EOF on closeNotify
  1285. }
  1286. }
  1287. if n != 0 || err != nil {
  1288. return n, err
  1289. }
  1290. }
  1291. return 0, io.ErrNoProgress
  1292. }
  1293. // Close closes the connection.
  1294. func (c *Conn) Close() error {
  1295. // Interlock with Conn.Write above.
  1296. var x int32
  1297. for {
  1298. x = atomic.LoadInt32(&c.activeCall)
  1299. if x&1 != 0 {
  1300. return errClosed
  1301. }
  1302. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1303. break
  1304. }
  1305. }
  1306. if x != 0 {
  1307. // io.Writer and io.Closer should not be used concurrently.
  1308. // If Close is called while a Write is currently in-flight,
  1309. // interpret that as a sign that this Close is really just
  1310. // being used to break the Write and/or clean up resources and
  1311. // avoid sending the alertCloseNotify, which may block
  1312. // waiting on handshakeMutex or the c.out mutex.
  1313. return c.conn.Close()
  1314. }
  1315. var alertErr error
  1316. c.handshakeMutex.Lock()
  1317. if c.handshakeComplete {
  1318. alertErr = c.closeNotify()
  1319. }
  1320. c.handshakeMutex.Unlock()
  1321. if err := c.conn.Close(); err != nil {
  1322. return err
  1323. }
  1324. return alertErr
  1325. }
  1326. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1327. // CloseWrite shuts down the writing side of the connection. It should only be
  1328. // called once the handshake has completed and does not call CloseWrite on the
  1329. // underlying connection. Most callers should just use Close.
  1330. func (c *Conn) CloseWrite() error {
  1331. c.handshakeMutex.Lock()
  1332. defer c.handshakeMutex.Unlock()
  1333. if !c.handshakeComplete {
  1334. return errEarlyCloseWrite
  1335. }
  1336. return c.closeNotify()
  1337. }
  1338. func (c *Conn) closeNotify() error {
  1339. c.out.Lock()
  1340. defer c.out.Unlock()
  1341. if !c.closeNotifySent {
  1342. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1343. c.closeNotifySent = true
  1344. }
  1345. return c.closeNotifyErr
  1346. }
  1347. // Handshake runs the client or server handshake
  1348. // protocol if it has not yet been run.
  1349. // Most uses of this package need not call Handshake
  1350. // explicitly: the first Read or Write will call it automatically.
  1351. //
  1352. // In TLS 1.3 Handshake returns after the client and server first flights,
  1353. // without waiting for the Client Finished.
  1354. func (c *Conn) Handshake() error {
  1355. c.handshakeMutex.Lock()
  1356. defer c.handshakeMutex.Unlock()
  1357. if err := c.handshakeErr; err != nil {
  1358. return err
  1359. }
  1360. if c.handshakeComplete {
  1361. return nil
  1362. }
  1363. c.in.Lock()
  1364. defer c.in.Unlock()
  1365. // The handshake cannot have completed when handshakeMutex was unlocked
  1366. // because this goroutine set handshakeCond.
  1367. if c.handshakeErr != nil || c.handshakeComplete {
  1368. panic("handshake should not have been able to complete after handshakeCond was set")
  1369. }
  1370. c.connID = make([]byte, 8)
  1371. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1372. return err
  1373. }
  1374. if c.isClient {
  1375. c.handshakeErr = c.clientHandshake()
  1376. } else {
  1377. c.handshakeErr = c.serverHandshake()
  1378. }
  1379. if c.handshakeErr == nil {
  1380. c.handshakes++
  1381. } else {
  1382. // If an error occurred during the hadshake try to flush the
  1383. // alert that might be left in the buffer.
  1384. c.flush()
  1385. }
  1386. if c.handshakeErr == nil && !c.handshakeComplete {
  1387. panic("handshake should have had a result.")
  1388. }
  1389. return c.handshakeErr
  1390. }
  1391. // ConnectionState returns basic TLS details about the connection.
  1392. func (c *Conn) ConnectionState() ConnectionState {
  1393. c.handshakeMutex.Lock()
  1394. defer c.handshakeMutex.Unlock()
  1395. var state ConnectionState
  1396. state.HandshakeComplete = c.handshakeComplete
  1397. state.ServerName = c.serverName
  1398. if c.handshakeComplete {
  1399. state.ConnectionID = c.connID
  1400. state.ClientHello = c.clientHello
  1401. state.Version = c.vers
  1402. state.NegotiatedProtocol = c.clientProtocol
  1403. state.DidResume = c.didResume
  1404. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1405. state.CipherSuite = c.cipherSuite
  1406. state.PeerCertificates = c.peerCertificates
  1407. state.VerifiedChains = c.verifiedChains
  1408. state.SignedCertificateTimestamps = c.scts
  1409. state.OCSPResponse = c.ocspResponse
  1410. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1411. if !state.HandshakeConfirmed {
  1412. state.Unique0RTTToken = c.binder
  1413. }
  1414. if !c.didResume {
  1415. if c.clientFinishedIsFirst {
  1416. state.TLSUnique = c.clientFinished[:]
  1417. } else {
  1418. state.TLSUnique = c.serverFinished[:]
  1419. }
  1420. }
  1421. }
  1422. return state
  1423. }
  1424. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1425. // any. (Only valid for client connections.)
  1426. func (c *Conn) OCSPResponse() []byte {
  1427. c.handshakeMutex.Lock()
  1428. defer c.handshakeMutex.Unlock()
  1429. return c.ocspResponse
  1430. }
  1431. // VerifyHostname checks that the peer certificate chain is valid for
  1432. // connecting to host. If so, it returns nil; if not, it returns an error
  1433. // describing the problem.
  1434. func (c *Conn) VerifyHostname(host string) error {
  1435. c.handshakeMutex.Lock()
  1436. defer c.handshakeMutex.Unlock()
  1437. if !c.isClient {
  1438. return errors.New("tls: VerifyHostname called on TLS server connection")
  1439. }
  1440. if !c.handshakeComplete {
  1441. return errors.New("tls: handshake has not yet been performed")
  1442. }
  1443. if len(c.verifiedChains) == 0 {
  1444. return errors.New("tls: handshake did not verify certificate chain")
  1445. }
  1446. return c.peerCertificates[0].VerifyHostname(host)
  1447. }