Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1640 lignes
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. Again:
  566. if c.rawInput == nil {
  567. c.rawInput = c.in.newBlock()
  568. }
  569. b := c.rawInput
  570. // Read header, payload.
  571. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  572. // RFC suggests that EOF without an alertCloseNotify is
  573. // an error, but popular web sites seem to do this,
  574. // so we can't make it an error.
  575. // if err == io.EOF {
  576. // err = io.ErrUnexpectedEOF
  577. // }
  578. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  579. c.in.setErrorLocked(err)
  580. }
  581. return err
  582. }
  583. typ := recordType(b.data[0])
  584. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  585. // start with a uint16 length where the MSB is set and the first record
  586. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  587. // an SSLv2 client.
  588. if want == recordTypeHandshake && typ == 0x80 {
  589. c.sendAlert(alertProtocolVersion)
  590. return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
  591. }
  592. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  593. n := int(b.data[3])<<8 | int(b.data[4])
  594. if n > maxCiphertext {
  595. c.sendAlert(alertRecordOverflow)
  596. msg := fmt.Sprintf("oversized record received with length %d", n)
  597. return c.in.setErrorLocked(c.newRecordHeaderError(msg))
  598. }
  599. if !c.haveVers {
  600. // First message, be extra suspicious: this might not be a TLS
  601. // client. Bail out before reading a full 'body', if possible.
  602. // The current max version is 3.3 so if the version is >= 16.0,
  603. // it's probably not real.
  604. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  605. c.sendAlert(alertUnexpectedMessage)
  606. return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
  607. }
  608. }
  609. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  610. if err == io.EOF {
  611. err = io.ErrUnexpectedEOF
  612. }
  613. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  614. c.in.setErrorLocked(err)
  615. }
  616. return err
  617. }
  618. // Process message.
  619. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  620. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  621. ok, off, alertValue := c.in.decrypt(b)
  622. switch {
  623. case !ok && c.phase == discardingEarlyData:
  624. // If the client said that it's sending early data and we did not
  625. // accept it, we are expected to fail decryption.
  626. c.in.freeBlock(b)
  627. return nil
  628. case ok && c.phase == discardingEarlyData:
  629. c.phase = waitingClientFinished
  630. case !ok:
  631. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  632. c.in.freeBlock(b)
  633. err := c.sendAlert(alertValue)
  634. // If decryption failed because the message is an unencrypted
  635. // alert, return a more meaningful error message
  636. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  637. err = peekedAlert
  638. }
  639. return c.in.setErrorLocked(err)
  640. }
  641. b.off = off
  642. data := b.data[b.off:]
  643. if len(data) > maxPlaintext {
  644. c.in.freeBlock(b)
  645. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  646. }
  647. // After checking the plaintext length, remove 1.3 padding and
  648. // extract the real content type.
  649. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  650. if c.vers >= VersionTLS13 {
  651. i := len(data) - 1
  652. for i >= 0 {
  653. if data[i] != 0 {
  654. break
  655. }
  656. i--
  657. }
  658. if i < 0 {
  659. c.in.freeBlock(b)
  660. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  661. }
  662. typ = recordType(data[i])
  663. data = data[:i]
  664. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  665. }
  666. switch typ {
  667. default:
  668. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  669. case recordTypeAlert:
  670. if len(data) != 2 {
  671. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  672. break
  673. }
  674. if alert(data[1]) == alertCloseNotify {
  675. c.in.setErrorLocked(io.EOF)
  676. break
  677. }
  678. if alert(data[1]) == alertEndOfEarlyData {
  679. c.handleEndOfEarlyData()
  680. break
  681. }
  682. switch data[0] {
  683. case alertLevelWarning:
  684. // drop on the floor
  685. c.in.freeBlock(b)
  686. goto Again
  687. case alertLevelError:
  688. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  689. default:
  690. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  691. }
  692. case recordTypeChangeCipherSpec:
  693. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  694. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  695. break
  696. }
  697. // Handshake messages are not allowed to fragment across the CCS
  698. if c.hand.Len() > 0 {
  699. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  700. break
  701. }
  702. err := c.in.changeCipherSpec()
  703. if err != nil {
  704. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  705. }
  706. case recordTypeApplicationData:
  707. if typ != want || c.phase == waitingClientFinished {
  708. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  709. break
  710. }
  711. if c.phase == readingEarlyData {
  712. c.earlyDataBytes += int64(len(b.data) - b.off)
  713. if c.earlyDataBytes > c.ticketMaxEarlyData {
  714. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  715. }
  716. }
  717. c.input = b
  718. b = nil
  719. case recordTypeHandshake:
  720. // TODO(rsc): Should at least pick off connection close.
  721. if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) &&
  722. c.phase != waitingClientFinished {
  723. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  724. }
  725. c.hand.Write(data)
  726. if typ != want && c.phase == waitingClientFinished {
  727. if err := c.hs.readClientFinished13(); err != nil {
  728. c.in.setErrorLocked(err)
  729. break
  730. }
  731. }
  732. }
  733. if b != nil {
  734. c.in.freeBlock(b)
  735. }
  736. return c.in.err
  737. }
  738. // peekAlert looks at a message to spot an unencrypted alert. It must be
  739. // called before decryption to avoid a side channel, and its result must
  740. // only be used if decryption fails, to avoid false positives.
  741. func peekAlert(b *block) error {
  742. if len(b.data) < 7 {
  743. return nil
  744. }
  745. if recordType(b.data[0]) != recordTypeAlert {
  746. return nil
  747. }
  748. return &net.OpError{Op: "remote error", Err: alert(b.data[6])}
  749. }
  750. // sendAlert sends a TLS alert message.
  751. // c.out.Mutex <= L.
  752. func (c *Conn) sendAlertLocked(err alert) error {
  753. switch err {
  754. case alertNoRenegotiation, alertCloseNotify:
  755. c.tmp[0] = alertLevelWarning
  756. default:
  757. c.tmp[0] = alertLevelError
  758. }
  759. c.tmp[1] = byte(err)
  760. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  761. if err == alertCloseNotify {
  762. // closeNotify is a special case in that it isn't an error.
  763. return writeErr
  764. }
  765. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  766. }
  767. // sendAlert sends a TLS alert message.
  768. // L < c.out.Mutex.
  769. func (c *Conn) sendAlert(err alert) error {
  770. c.out.Lock()
  771. defer c.out.Unlock()
  772. return c.sendAlertLocked(err)
  773. }
  774. const (
  775. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  776. // size (MSS). A constant is used, rather than querying the kernel for
  777. // the actual MSS, to avoid complexity. The value here is the IPv6
  778. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  779. // bytes) and a TCP header with timestamps (32 bytes).
  780. tcpMSSEstimate = 1208
  781. // recordSizeBoostThreshold is the number of bytes of application data
  782. // sent after which the TLS record size will be increased to the
  783. // maximum.
  784. recordSizeBoostThreshold = 128 * 1024
  785. )
  786. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  787. // next application data record. There is the following trade-off:
  788. //
  789. // - For latency-sensitive applications, such as web browsing, each TLS
  790. // record should fit in one TCP segment.
  791. // - For throughput-sensitive applications, such as large file transfers,
  792. // larger TLS records better amortize framing and encryption overheads.
  793. //
  794. // A simple heuristic that works well in practice is to use small records for
  795. // the first 1MB of data, then use larger records for subsequent data, and
  796. // reset back to smaller records after the connection becomes idle. See "High
  797. // Performance Web Networking", Chapter 4, or:
  798. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  799. //
  800. // In the interests of simplicity and determinism, this code does not attempt
  801. // to reset the record size once the connection is idle, however.
  802. //
  803. // c.out.Mutex <= L.
  804. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  805. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  806. return maxPlaintext
  807. }
  808. if c.bytesSent >= recordSizeBoostThreshold {
  809. return maxPlaintext
  810. }
  811. // Subtract TLS overheads to get the maximum payload size.
  812. macSize := 0
  813. if c.out.mac != nil {
  814. macSize = c.out.mac.Size()
  815. }
  816. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  817. if c.out.cipher != nil {
  818. switch ciph := c.out.cipher.(type) {
  819. case cipher.Stream:
  820. payloadBytes -= macSize
  821. case cipher.AEAD:
  822. payloadBytes -= ciph.Overhead()
  823. if c.vers >= VersionTLS13 {
  824. payloadBytes -= 1 // ContentType
  825. }
  826. case cbcMode:
  827. blockSize := ciph.BlockSize()
  828. // The payload must fit in a multiple of blockSize, with
  829. // room for at least one padding byte.
  830. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  831. // The MAC is appended before padding so affects the
  832. // payload size directly.
  833. payloadBytes -= macSize
  834. default:
  835. panic("unknown cipher type")
  836. }
  837. }
  838. // Allow packet growth in arithmetic progression up to max.
  839. pkt := c.packetsSent
  840. c.packetsSent++
  841. if pkt > 1000 {
  842. return maxPlaintext // avoid overflow in multiply below
  843. }
  844. n := payloadBytes * int(pkt+1)
  845. if n > maxPlaintext {
  846. n = maxPlaintext
  847. }
  848. return n
  849. }
  850. // c.out.Mutex <= L.
  851. func (c *Conn) write(data []byte) (int, error) {
  852. if c.buffering {
  853. c.sendBuf = append(c.sendBuf, data...)
  854. return len(data), nil
  855. }
  856. n, err := c.conn.Write(data)
  857. c.bytesSent += int64(n)
  858. return n, err
  859. }
  860. func (c *Conn) flush() (int, error) {
  861. if len(c.sendBuf) == 0 {
  862. return 0, nil
  863. }
  864. n, err := c.conn.Write(c.sendBuf)
  865. c.bytesSent += int64(n)
  866. c.sendBuf = nil
  867. c.buffering = false
  868. return n, err
  869. }
  870. // writeRecordLocked writes a TLS record with the given type and payload to the
  871. // connection and updates the record layer state.
  872. // c.out.Mutex <= L.
  873. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  874. b := c.out.newBlock()
  875. defer c.out.freeBlock(b)
  876. var n int
  877. for len(data) > 0 {
  878. explicitIVLen := 0
  879. explicitIVIsSeq := false
  880. var cbc cbcMode
  881. if c.out.version >= VersionTLS11 {
  882. var ok bool
  883. if cbc, ok = c.out.cipher.(cbcMode); ok {
  884. explicitIVLen = cbc.BlockSize()
  885. }
  886. }
  887. if explicitIVLen == 0 {
  888. if c, ok := c.out.cipher.(aead); ok {
  889. explicitIVLen = c.explicitNonceLen()
  890. // The AES-GCM construction in TLS has an
  891. // explicit nonce so that the nonce can be
  892. // random. However, the nonce is only 8 bytes
  893. // which is too small for a secure, random
  894. // nonce. Therefore we use the sequence number
  895. // as the nonce.
  896. explicitIVIsSeq = explicitIVLen > 0
  897. }
  898. }
  899. m := len(data)
  900. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  901. m = maxPayload
  902. }
  903. b.resize(recordHeaderLen + explicitIVLen + m)
  904. b.data[0] = byte(typ)
  905. vers := c.vers
  906. if vers == 0 {
  907. // Some TLS servers fail if the record version is
  908. // greater than TLS 1.0 for the initial ClientHello.
  909. vers = VersionTLS10
  910. }
  911. if c.vers >= VersionTLS13 {
  912. // TLS 1.3 froze the record layer version at { 3, 1 }.
  913. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.1.
  914. vers = VersionTLS10
  915. }
  916. b.data[1] = byte(vers >> 8)
  917. b.data[2] = byte(vers)
  918. b.data[3] = byte(m >> 8)
  919. b.data[4] = byte(m)
  920. if explicitIVLen > 0 {
  921. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  922. if explicitIVIsSeq {
  923. copy(explicitIV, c.out.seq[:])
  924. } else {
  925. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  926. return n, err
  927. }
  928. }
  929. }
  930. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  931. c.out.encrypt(b, explicitIVLen)
  932. if _, err := c.write(b.data); err != nil {
  933. return n, err
  934. }
  935. n += m
  936. data = data[m:]
  937. }
  938. if typ == recordTypeChangeCipherSpec {
  939. if err := c.out.changeCipherSpec(); err != nil {
  940. return n, c.sendAlertLocked(err.(alert))
  941. }
  942. }
  943. return n, nil
  944. }
  945. // writeRecord writes a TLS record with the given type and payload to the
  946. // connection and updates the record layer state.
  947. // L < c.out.Mutex.
  948. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  949. c.out.Lock()
  950. defer c.out.Unlock()
  951. return c.writeRecordLocked(typ, data)
  952. }
  953. // readHandshake reads the next handshake message from
  954. // the record layer.
  955. // c.in.Mutex < L; c.out.Mutex < L.
  956. func (c *Conn) readHandshake() (interface{}, error) {
  957. for c.hand.Len() < 4 {
  958. if err := c.in.err; err != nil {
  959. return nil, err
  960. }
  961. if err := c.readRecord(recordTypeHandshake); err != nil {
  962. return nil, err
  963. }
  964. }
  965. data := c.hand.Bytes()
  966. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  967. if n > maxHandshake {
  968. c.sendAlertLocked(alertInternalError)
  969. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  970. }
  971. for c.hand.Len() < 4+n {
  972. if err := c.in.err; err != nil {
  973. return nil, err
  974. }
  975. if err := c.readRecord(recordTypeHandshake); err != nil {
  976. return nil, err
  977. }
  978. }
  979. data = c.hand.Next(4 + n)
  980. var m handshakeMessage
  981. switch data[0] {
  982. case typeHelloRequest:
  983. m = new(helloRequestMsg)
  984. case typeClientHello:
  985. m = new(clientHelloMsg)
  986. case typeServerHello:
  987. if c.vers >= VersionTLS13 {
  988. m = new(serverHelloMsg13)
  989. } else {
  990. m = new(serverHelloMsg)
  991. }
  992. case typeEncryptedExtensions:
  993. m = new(encryptedExtensionsMsg)
  994. case typeNewSessionTicket:
  995. if c.vers >= VersionTLS13 {
  996. m = new(newSessionTicketMsg13)
  997. } else {
  998. m = new(newSessionTicketMsg)
  999. }
  1000. case typeCertificate:
  1001. if c.vers >= VersionTLS13 {
  1002. m = new(certificateMsg13)
  1003. } else {
  1004. m = new(certificateMsg)
  1005. }
  1006. case typeCertificateRequest:
  1007. m = &certificateRequestMsg{
  1008. hasSignatureAndHash: c.vers >= VersionTLS12,
  1009. }
  1010. case typeCertificateStatus:
  1011. m = new(certificateStatusMsg)
  1012. case typeServerKeyExchange:
  1013. m = new(serverKeyExchangeMsg)
  1014. case typeServerHelloDone:
  1015. m = new(serverHelloDoneMsg)
  1016. case typeClientKeyExchange:
  1017. m = new(clientKeyExchangeMsg)
  1018. case typeCertificateVerify:
  1019. m = &certificateVerifyMsg{
  1020. hasSignatureAndHash: c.vers >= VersionTLS12,
  1021. }
  1022. case typeNextProtocol:
  1023. m = new(nextProtoMsg)
  1024. case typeFinished:
  1025. m = new(finishedMsg)
  1026. default:
  1027. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1028. }
  1029. // The handshake message unmarshalers
  1030. // expect to be able to keep references to data,
  1031. // so pass in a fresh copy that won't be overwritten.
  1032. data = append([]byte(nil), data...)
  1033. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1034. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1035. }
  1036. return m, nil
  1037. }
  1038. var (
  1039. errClosed = errors.New("tls: use of closed connection")
  1040. errShutdown = errors.New("tls: protocol is shutdown")
  1041. )
  1042. // Write writes data to the connection.
  1043. func (c *Conn) Write(b []byte) (int, error) {
  1044. // interlock with Close below
  1045. for {
  1046. x := atomic.LoadInt32(&c.activeCall)
  1047. if x&1 != 0 {
  1048. return 0, errClosed
  1049. }
  1050. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1051. defer atomic.AddInt32(&c.activeCall, -2)
  1052. break
  1053. }
  1054. }
  1055. if err := c.Handshake(); err != nil {
  1056. return 0, err
  1057. }
  1058. c.out.Lock()
  1059. defer c.out.Unlock()
  1060. if err := c.out.err; err != nil {
  1061. return 0, err
  1062. }
  1063. if !c.handshakeComplete {
  1064. return 0, alertInternalError
  1065. }
  1066. if c.closeNotifySent {
  1067. return 0, errShutdown
  1068. }
  1069. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1070. // attack when using block mode ciphers due to predictable IVs.
  1071. // This can be prevented by splitting each Application Data
  1072. // record into two records, effectively randomizing the IV.
  1073. //
  1074. // http://www.openssl.org/~bodo/tls-cbc.txt
  1075. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1076. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1077. var m int
  1078. if len(b) > 1 && c.vers <= VersionTLS10 {
  1079. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1080. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1081. if err != nil {
  1082. return n, c.out.setErrorLocked(err)
  1083. }
  1084. m, b = 1, b[1:]
  1085. }
  1086. }
  1087. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1088. return n + m, c.out.setErrorLocked(err)
  1089. }
  1090. // handleRenegotiation processes a HelloRequest handshake message.
  1091. // c.in.Mutex <= L
  1092. func (c *Conn) handleRenegotiation() error {
  1093. msg, err := c.readHandshake()
  1094. if err != nil {
  1095. return err
  1096. }
  1097. _, ok := msg.(*helloRequestMsg)
  1098. if !ok {
  1099. c.sendAlert(alertUnexpectedMessage)
  1100. return alertUnexpectedMessage
  1101. }
  1102. if !c.isClient {
  1103. return c.sendAlert(alertNoRenegotiation)
  1104. }
  1105. if c.vers >= VersionTLS13 {
  1106. return c.sendAlert(alertNoRenegotiation)
  1107. }
  1108. switch c.config.Renegotiation {
  1109. case RenegotiateNever:
  1110. return c.sendAlert(alertNoRenegotiation)
  1111. case RenegotiateOnceAsClient:
  1112. if c.handshakes > 1 {
  1113. return c.sendAlert(alertNoRenegotiation)
  1114. }
  1115. case RenegotiateFreelyAsClient:
  1116. // Ok.
  1117. default:
  1118. c.sendAlert(alertInternalError)
  1119. return errors.New("tls: unknown Renegotiation value")
  1120. }
  1121. c.handshakeMutex.Lock()
  1122. defer c.handshakeMutex.Unlock()
  1123. c.phase = handshakeRunning
  1124. c.handshakeComplete = false
  1125. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1126. c.handshakes++
  1127. }
  1128. return c.handshakeErr
  1129. }
  1130. // ConfirmHandshake waits for the handshake to reach a point at which
  1131. // the connection is certainly not replayed. That is, after receiving
  1132. // the Client Finished.
  1133. //
  1134. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1135. // returns, the 0-RTT data should not be trusted not to be replayed.
  1136. //
  1137. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1138. // client sent valid 0-RTT data. In any other case it's equivalent to
  1139. // calling Handshake.
  1140. func (c *Conn) ConfirmHandshake() error {
  1141. if err := c.Handshake(); err != nil {
  1142. return err
  1143. }
  1144. if c.vers < VersionTLS13 {
  1145. return nil
  1146. }
  1147. c.confirmMutex.Lock()
  1148. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1149. c.confirmMutex.Unlock()
  1150. return nil
  1151. } else {
  1152. defer func() {
  1153. // If we transitioned to handshakeConfirmed we already released the lock,
  1154. // otherwise do it here.
  1155. if c.phase != handshakeConfirmed {
  1156. c.confirmMutex.Unlock()
  1157. }
  1158. }()
  1159. }
  1160. c.in.Lock()
  1161. defer c.in.Unlock()
  1162. var input *block
  1163. if c.phase == readingEarlyData || c.input != nil {
  1164. buf := &bytes.Buffer{}
  1165. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1166. c.in.setErrorLocked(err)
  1167. return err
  1168. }
  1169. input = &block{data: buf.Bytes()}
  1170. }
  1171. for c.phase != handshakeConfirmed {
  1172. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1173. c.in.setErrorLocked(err)
  1174. return err
  1175. }
  1176. }
  1177. if c.phase != handshakeConfirmed {
  1178. panic("should have reached handshakeConfirmed state")
  1179. }
  1180. if c.input != nil {
  1181. panic("should not have read past the Client Finished")
  1182. }
  1183. c.input = input
  1184. return nil
  1185. }
  1186. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1187. // and still on the wire.
  1188. type earlyDataReader struct {
  1189. c *Conn
  1190. }
  1191. // c.in.Mutex <= L
  1192. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1193. c := r.c
  1194. if c.phase == handshakeConfirmed {
  1195. // c.input might not be early data
  1196. panic("earlyDataReader called at handshakeConfirmed")
  1197. }
  1198. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1199. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1200. return 0, err
  1201. }
  1202. }
  1203. if err := c.in.err; err != nil {
  1204. return 0, err
  1205. }
  1206. if c.input != nil {
  1207. n, err = c.input.Read(b)
  1208. if err == io.EOF {
  1209. err = nil
  1210. c.in.freeBlock(c.input)
  1211. c.input = nil
  1212. }
  1213. }
  1214. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1215. err = io.EOF
  1216. }
  1217. return
  1218. }
  1219. // Read can be made to time out and return a net.Error with Timeout() == true
  1220. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1221. func (c *Conn) Read(b []byte) (n int, err error) {
  1222. if err = c.Handshake(); err != nil {
  1223. return
  1224. }
  1225. if len(b) == 0 {
  1226. // Put this after Handshake, in case people were calling
  1227. // Read(nil) for the side effect of the Handshake.
  1228. return
  1229. }
  1230. c.confirmMutex.Lock()
  1231. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1232. c.confirmMutex.Unlock()
  1233. } else {
  1234. defer func() {
  1235. // If we transitioned to handshakeConfirmed we already released the lock,
  1236. // otherwise do it here.
  1237. if c.phase != handshakeConfirmed {
  1238. c.confirmMutex.Unlock()
  1239. }
  1240. }()
  1241. }
  1242. c.in.Lock()
  1243. defer c.in.Unlock()
  1244. // Some OpenSSL servers send empty records in order to randomize the
  1245. // CBC IV. So this loop ignores a limited number of empty records.
  1246. const maxConsecutiveEmptyRecords = 100
  1247. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1248. for c.input == nil && c.in.err == nil {
  1249. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1250. // Soft error, like EAGAIN
  1251. return 0, err
  1252. }
  1253. if c.hand.Len() > 0 {
  1254. // We received handshake bytes, indicating the
  1255. // start of a renegotiation.
  1256. if err := c.handleRenegotiation(); err != nil {
  1257. return 0, err
  1258. }
  1259. }
  1260. }
  1261. if err := c.in.err; err != nil {
  1262. return 0, err
  1263. }
  1264. n, err = c.input.Read(b)
  1265. if err == io.EOF {
  1266. err = nil
  1267. c.in.freeBlock(c.input)
  1268. c.input = nil
  1269. }
  1270. // If a close-notify alert is waiting, read it so that
  1271. // we can return (n, EOF) instead of (n, nil), to signal
  1272. // to the HTTP response reading goroutine that the
  1273. // connection is now closed. This eliminates a race
  1274. // where the HTTP response reading goroutine would
  1275. // otherwise not observe the EOF until its next read,
  1276. // by which time a client goroutine might have already
  1277. // tried to reuse the HTTP connection for a new
  1278. // request.
  1279. // See https://codereview.appspot.com/76400046
  1280. // and https://golang.org/issue/3514
  1281. if ri := c.rawInput; ri != nil &&
  1282. n != 0 && err == nil &&
  1283. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1284. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1285. err = recErr // will be io.EOF on closeNotify
  1286. }
  1287. }
  1288. if n != 0 || err != nil {
  1289. return n, err
  1290. }
  1291. }
  1292. return 0, io.ErrNoProgress
  1293. }
  1294. // Close closes the connection.
  1295. func (c *Conn) Close() error {
  1296. // Interlock with Conn.Write above.
  1297. var x int32
  1298. for {
  1299. x = atomic.LoadInt32(&c.activeCall)
  1300. if x&1 != 0 {
  1301. return errClosed
  1302. }
  1303. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1304. break
  1305. }
  1306. }
  1307. if x != 0 {
  1308. // io.Writer and io.Closer should not be used concurrently.
  1309. // If Close is called while a Write is currently in-flight,
  1310. // interpret that as a sign that this Close is really just
  1311. // being used to break the Write and/or clean up resources and
  1312. // avoid sending the alertCloseNotify, which may block
  1313. // waiting on handshakeMutex or the c.out mutex.
  1314. return c.conn.Close()
  1315. }
  1316. var alertErr error
  1317. c.handshakeMutex.Lock()
  1318. if c.handshakeComplete {
  1319. alertErr = c.closeNotify()
  1320. }
  1321. c.handshakeMutex.Unlock()
  1322. if err := c.conn.Close(); err != nil {
  1323. return err
  1324. }
  1325. return alertErr
  1326. }
  1327. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1328. // CloseWrite shuts down the writing side of the connection. It should only be
  1329. // called once the handshake has completed and does not call CloseWrite on the
  1330. // underlying connection. Most callers should just use Close.
  1331. func (c *Conn) CloseWrite() error {
  1332. c.handshakeMutex.Lock()
  1333. defer c.handshakeMutex.Unlock()
  1334. if !c.handshakeComplete {
  1335. return errEarlyCloseWrite
  1336. }
  1337. return c.closeNotify()
  1338. }
  1339. func (c *Conn) closeNotify() error {
  1340. c.out.Lock()
  1341. defer c.out.Unlock()
  1342. if !c.closeNotifySent {
  1343. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1344. c.closeNotifySent = true
  1345. }
  1346. return c.closeNotifyErr
  1347. }
  1348. // Handshake runs the client or server handshake
  1349. // protocol if it has not yet been run.
  1350. // Most uses of this package need not call Handshake
  1351. // explicitly: the first Read or Write will call it automatically.
  1352. //
  1353. // In TLS 1.3 Handshake returns after the client and server first flights,
  1354. // without waiting for the Client Finished.
  1355. func (c *Conn) Handshake() error {
  1356. c.handshakeMutex.Lock()
  1357. defer c.handshakeMutex.Unlock()
  1358. if err := c.handshakeErr; err != nil {
  1359. return err
  1360. }
  1361. if c.handshakeComplete {
  1362. return nil
  1363. }
  1364. c.in.Lock()
  1365. defer c.in.Unlock()
  1366. // The handshake cannot have completed when handshakeMutex was unlocked
  1367. // because this goroutine set handshakeCond.
  1368. if c.handshakeErr != nil || c.handshakeComplete {
  1369. panic("handshake should not have been able to complete after handshakeCond was set")
  1370. }
  1371. c.connID = make([]byte, 8)
  1372. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1373. return err
  1374. }
  1375. if c.isClient {
  1376. c.handshakeErr = c.clientHandshake()
  1377. } else {
  1378. c.handshakeErr = c.serverHandshake()
  1379. }
  1380. if c.handshakeErr == nil {
  1381. c.handshakes++
  1382. } else {
  1383. // If an error occurred during the hadshake try to flush the
  1384. // alert that might be left in the buffer.
  1385. c.flush()
  1386. }
  1387. if c.handshakeErr == nil && !c.handshakeComplete {
  1388. panic("handshake should have had a result.")
  1389. }
  1390. return c.handshakeErr
  1391. }
  1392. // ConnectionState returns basic TLS details about the connection.
  1393. func (c *Conn) ConnectionState() ConnectionState {
  1394. c.handshakeMutex.Lock()
  1395. defer c.handshakeMutex.Unlock()
  1396. var state ConnectionState
  1397. state.HandshakeComplete = c.handshakeComplete
  1398. state.ServerName = c.serverName
  1399. if c.handshakeComplete {
  1400. state.ConnectionID = c.connID
  1401. state.ClientHello = c.clientHello
  1402. state.Version = c.vers
  1403. state.NegotiatedProtocol = c.clientProtocol
  1404. state.DidResume = c.didResume
  1405. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1406. state.CipherSuite = c.cipherSuite
  1407. state.PeerCertificates = c.peerCertificates
  1408. state.VerifiedChains = c.verifiedChains
  1409. state.SignedCertificateTimestamps = c.scts
  1410. state.OCSPResponse = c.ocspResponse
  1411. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1412. if !state.HandshakeConfirmed {
  1413. state.Unique0RTTToken = c.binder
  1414. }
  1415. if !c.didResume {
  1416. if c.clientFinishedIsFirst {
  1417. state.TLSUnique = c.clientFinished[:]
  1418. } else {
  1419. state.TLSUnique = c.serverFinished[:]
  1420. }
  1421. }
  1422. }
  1423. return state
  1424. }
  1425. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1426. // any. (Only valid for client connections.)
  1427. func (c *Conn) OCSPResponse() []byte {
  1428. c.handshakeMutex.Lock()
  1429. defer c.handshakeMutex.Unlock()
  1430. return c.ocspResponse
  1431. }
  1432. // VerifyHostname checks that the peer certificate chain is valid for
  1433. // connecting to host. If so, it returns nil; if not, it returns an error
  1434. // describing the problem.
  1435. func (c *Conn) VerifyHostname(host string) error {
  1436. c.handshakeMutex.Lock()
  1437. defer c.handshakeMutex.Unlock()
  1438. if !c.isClient {
  1439. return errors.New("tls: VerifyHostname called on TLS server connection")
  1440. }
  1441. if !c.handshakeComplete {
  1442. return errors.New("tls: handshake has not yet been performed")
  1443. }
  1444. if len(c.verifiedChains) == 0 {
  1445. return errors.New("tls: handshake did not verify certificate chain")
  1446. }
  1447. return c.peerCertificates[0].VerifyHostname(host)
  1448. }