Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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