Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

1658 wiersze
46 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. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  625. ok, off, alertValue := c.in.decrypt(b)
  626. switch {
  627. case !ok && c.phase == discardingEarlyData:
  628. // If the client said that it's sending early data and we did not
  629. // accept it, we are expected to fail decryption.
  630. c.in.freeBlock(b)
  631. return nil
  632. case ok && c.phase == discardingEarlyData:
  633. c.phase = waitingClientFinished
  634. case !ok:
  635. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  636. c.in.freeBlock(b)
  637. err := c.sendAlert(alertValue)
  638. // If decryption failed because the message is an unencrypted
  639. // alert, return a more meaningful error message
  640. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  641. err = peekedAlert
  642. }
  643. return c.in.setErrorLocked(err)
  644. }
  645. b.off = off
  646. data := b.data[b.off:]
  647. if (c.vers < VersionTLS13 && len(data) > maxPlaintext) || len(data) > maxPlaintext+1 {
  648. c.in.freeBlock(b)
  649. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  650. }
  651. // After checking the plaintext length, remove 1.3 padding and
  652. // extract the real content type.
  653. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  654. if c.vers >= VersionTLS13 {
  655. i := len(data) - 1
  656. for i >= 0 {
  657. if data[i] != 0 {
  658. break
  659. }
  660. i--
  661. }
  662. if i < 0 {
  663. c.in.freeBlock(b)
  664. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  665. }
  666. typ = recordType(data[i])
  667. data = data[:i]
  668. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  669. }
  670. if typ != recordTypeAlert && len(data) > 0 {
  671. // this is a valid non-alert message: reset the count of alerts
  672. c.warnCount = 0
  673. }
  674. switch typ {
  675. default:
  676. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  677. case recordTypeAlert:
  678. if len(data) != 2 {
  679. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  680. break
  681. }
  682. if alert(data[1]) == alertCloseNotify {
  683. c.in.setErrorLocked(io.EOF)
  684. break
  685. }
  686. if alert(data[1]) == alertEndOfEarlyData {
  687. c.handleEndOfEarlyData()
  688. break
  689. }
  690. switch data[0] {
  691. case alertLevelWarning:
  692. // drop on the floor
  693. c.in.freeBlock(b)
  694. c.warnCount++
  695. if c.warnCount > maxWarnAlertCount {
  696. c.sendAlert(alertUnexpectedMessage)
  697. return c.in.setErrorLocked(errors.New("tls: too many warn alerts"))
  698. }
  699. goto Again
  700. case alertLevelError:
  701. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  702. default:
  703. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  704. }
  705. case recordTypeChangeCipherSpec:
  706. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  707. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  708. break
  709. }
  710. // Handshake messages are not allowed to fragment across the CCS
  711. if c.hand.Len() > 0 {
  712. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  713. break
  714. }
  715. // Handshake messages are not allowed to fragment across the CCS
  716. if c.hand.Len() > 0 {
  717. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  718. break
  719. }
  720. err := c.in.changeCipherSpec()
  721. if err != nil {
  722. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  723. }
  724. case recordTypeApplicationData:
  725. if typ != want || c.phase == waitingClientFinished {
  726. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  727. break
  728. }
  729. if c.phase == readingEarlyData {
  730. c.earlyDataBytes += int64(len(b.data) - b.off)
  731. if c.earlyDataBytes > c.ticketMaxEarlyData {
  732. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  733. }
  734. }
  735. c.input = b
  736. b = nil
  737. case recordTypeHandshake:
  738. // TODO(rsc): Should at least pick off connection close.
  739. if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) &&
  740. c.phase != waitingClientFinished {
  741. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  742. }
  743. c.hand.Write(data)
  744. if typ != want && c.phase == waitingClientFinished {
  745. if err := c.hs.readClientFinished13(); err != nil {
  746. c.in.setErrorLocked(err)
  747. break
  748. }
  749. }
  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. vers = VersionTLS10
  933. }
  934. b.data[1] = byte(vers >> 8)
  935. b.data[2] = byte(vers)
  936. b.data[3] = byte(m >> 8)
  937. b.data[4] = byte(m)
  938. if explicitIVLen > 0 {
  939. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  940. if explicitIVIsSeq {
  941. copy(explicitIV, c.out.seq[:])
  942. } else {
  943. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  944. return n, err
  945. }
  946. }
  947. }
  948. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  949. c.out.encrypt(b, explicitIVLen)
  950. if _, err := c.write(b.data); err != nil {
  951. return n, err
  952. }
  953. n += m
  954. data = data[m:]
  955. }
  956. if typ == recordTypeChangeCipherSpec {
  957. if err := c.out.changeCipherSpec(); err != nil {
  958. return n, c.sendAlertLocked(err.(alert))
  959. }
  960. }
  961. return n, nil
  962. }
  963. // writeRecord writes a TLS record with the given type and payload to the
  964. // connection and updates the record layer state.
  965. // L < c.out.Mutex.
  966. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  967. c.out.Lock()
  968. defer c.out.Unlock()
  969. return c.writeRecordLocked(typ, data)
  970. }
  971. // readHandshake reads the next handshake message from
  972. // the record layer.
  973. // c.in.Mutex < L; c.out.Mutex < L.
  974. func (c *Conn) readHandshake() (interface{}, error) {
  975. for c.hand.Len() < 4 {
  976. if err := c.in.err; err != nil {
  977. return nil, err
  978. }
  979. if err := c.readRecord(recordTypeHandshake); err != nil {
  980. return nil, err
  981. }
  982. }
  983. data := c.hand.Bytes()
  984. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  985. if n > maxHandshake {
  986. c.sendAlertLocked(alertInternalError)
  987. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  988. }
  989. for c.hand.Len() < 4+n {
  990. if err := c.in.err; err != nil {
  991. return nil, err
  992. }
  993. if err := c.readRecord(recordTypeHandshake); err != nil {
  994. return nil, err
  995. }
  996. }
  997. data = c.hand.Next(4 + n)
  998. var m handshakeMessage
  999. switch data[0] {
  1000. case typeHelloRequest:
  1001. m = new(helloRequestMsg)
  1002. case typeClientHello:
  1003. m = new(clientHelloMsg)
  1004. case typeServerHello:
  1005. m = new(serverHelloMsg)
  1006. case typeEncryptedExtensions:
  1007. m = new(encryptedExtensionsMsg)
  1008. case typeNewSessionTicket:
  1009. if c.vers >= VersionTLS13 {
  1010. m = new(newSessionTicketMsg13)
  1011. } else {
  1012. m = new(newSessionTicketMsg)
  1013. }
  1014. case typeCertificate:
  1015. if c.vers >= VersionTLS13 {
  1016. m = new(certificateMsg13)
  1017. } else {
  1018. m = new(certificateMsg)
  1019. }
  1020. case typeCertificateRequest:
  1021. m = &certificateRequestMsg{
  1022. hasSignatureAndHash: c.vers >= VersionTLS12,
  1023. }
  1024. case typeCertificateStatus:
  1025. m = new(certificateStatusMsg)
  1026. case typeServerKeyExchange:
  1027. m = new(serverKeyExchangeMsg)
  1028. case typeServerHelloDone:
  1029. m = new(serverHelloDoneMsg)
  1030. case typeClientKeyExchange:
  1031. m = new(clientKeyExchangeMsg)
  1032. case typeCertificateVerify:
  1033. m = &certificateVerifyMsg{
  1034. hasSignatureAndHash: c.vers >= VersionTLS12,
  1035. }
  1036. case typeNextProtocol:
  1037. m = new(nextProtoMsg)
  1038. case typeFinished:
  1039. m = new(finishedMsg)
  1040. default:
  1041. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1042. }
  1043. // The handshake message unmarshalers
  1044. // expect to be able to keep references to data,
  1045. // so pass in a fresh copy that won't be overwritten.
  1046. data = append([]byte(nil), data...)
  1047. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1048. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1049. }
  1050. return m, nil
  1051. }
  1052. var (
  1053. errClosed = errors.New("tls: use of closed connection")
  1054. errShutdown = errors.New("tls: protocol is shutdown")
  1055. )
  1056. // Write writes data to the connection.
  1057. func (c *Conn) Write(b []byte) (int, error) {
  1058. // interlock with Close below
  1059. for {
  1060. x := atomic.LoadInt32(&c.activeCall)
  1061. if x&1 != 0 {
  1062. return 0, errClosed
  1063. }
  1064. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1065. defer atomic.AddInt32(&c.activeCall, -2)
  1066. break
  1067. }
  1068. }
  1069. if err := c.Handshake(); err != nil {
  1070. return 0, err
  1071. }
  1072. c.out.Lock()
  1073. defer c.out.Unlock()
  1074. if err := c.out.err; err != nil {
  1075. return 0, err
  1076. }
  1077. if !c.handshakeComplete {
  1078. return 0, alertInternalError
  1079. }
  1080. if c.closeNotifySent {
  1081. return 0, errShutdown
  1082. }
  1083. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1084. // attack when using block mode ciphers due to predictable IVs.
  1085. // This can be prevented by splitting each Application Data
  1086. // record into two records, effectively randomizing the IV.
  1087. //
  1088. // http://www.openssl.org/~bodo/tls-cbc.txt
  1089. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1090. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1091. var m int
  1092. if len(b) > 1 && c.vers <= VersionTLS10 {
  1093. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1094. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1095. if err != nil {
  1096. return n, c.out.setErrorLocked(err)
  1097. }
  1098. m, b = 1, b[1:]
  1099. }
  1100. }
  1101. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1102. return n + m, c.out.setErrorLocked(err)
  1103. }
  1104. // handleRenegotiation processes a HelloRequest handshake message.
  1105. // c.in.Mutex <= L
  1106. func (c *Conn) handleRenegotiation() error {
  1107. msg, err := c.readHandshake()
  1108. if err != nil {
  1109. return err
  1110. }
  1111. _, ok := msg.(*helloRequestMsg)
  1112. if !ok {
  1113. c.sendAlert(alertUnexpectedMessage)
  1114. return alertUnexpectedMessage
  1115. }
  1116. if !c.isClient {
  1117. return c.sendAlert(alertNoRenegotiation)
  1118. }
  1119. if c.vers >= VersionTLS13 {
  1120. return c.sendAlert(alertNoRenegotiation)
  1121. }
  1122. switch c.config.Renegotiation {
  1123. case RenegotiateNever:
  1124. return c.sendAlert(alertNoRenegotiation)
  1125. case RenegotiateOnceAsClient:
  1126. if c.handshakes > 1 {
  1127. return c.sendAlert(alertNoRenegotiation)
  1128. }
  1129. case RenegotiateFreelyAsClient:
  1130. // Ok.
  1131. default:
  1132. c.sendAlert(alertInternalError)
  1133. return errors.New("tls: unknown Renegotiation value")
  1134. }
  1135. c.handshakeMutex.Lock()
  1136. defer c.handshakeMutex.Unlock()
  1137. c.phase = handshakeRunning
  1138. c.handshakeComplete = false
  1139. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1140. c.handshakes++
  1141. }
  1142. return c.handshakeErr
  1143. }
  1144. // ConfirmHandshake waits for the handshake to reach a point at which
  1145. // the connection is certainly not replayed. That is, after receiving
  1146. // the Client Finished.
  1147. //
  1148. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1149. // returns, the 0-RTT data should not be trusted not to be replayed.
  1150. //
  1151. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1152. // client sent valid 0-RTT data. In any other case it's equivalent to
  1153. // calling Handshake.
  1154. func (c *Conn) ConfirmHandshake() error {
  1155. if err := c.Handshake(); err != nil {
  1156. return err
  1157. }
  1158. if c.vers < VersionTLS13 {
  1159. return nil
  1160. }
  1161. c.confirmMutex.Lock()
  1162. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1163. c.confirmMutex.Unlock()
  1164. return nil
  1165. } else {
  1166. defer func() {
  1167. // If we transitioned to handshakeConfirmed we already released the lock,
  1168. // otherwise do it here.
  1169. if c.phase != handshakeConfirmed {
  1170. c.confirmMutex.Unlock()
  1171. }
  1172. }()
  1173. }
  1174. c.in.Lock()
  1175. defer c.in.Unlock()
  1176. var input *block
  1177. if c.phase == readingEarlyData || c.input != nil {
  1178. buf := &bytes.Buffer{}
  1179. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1180. c.in.setErrorLocked(err)
  1181. return err
  1182. }
  1183. input = &block{data: buf.Bytes()}
  1184. }
  1185. for c.phase != handshakeConfirmed {
  1186. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1187. c.in.setErrorLocked(err)
  1188. return err
  1189. }
  1190. }
  1191. if c.phase != handshakeConfirmed {
  1192. panic("should have reached handshakeConfirmed state")
  1193. }
  1194. if c.input != nil {
  1195. panic("should not have read past the Client Finished")
  1196. }
  1197. c.input = input
  1198. return nil
  1199. }
  1200. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1201. // and still on the wire.
  1202. type earlyDataReader struct {
  1203. c *Conn
  1204. }
  1205. // c.in.Mutex <= L
  1206. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1207. c := r.c
  1208. if c.phase == handshakeConfirmed {
  1209. // c.input might not be early data
  1210. panic("earlyDataReader called at handshakeConfirmed")
  1211. }
  1212. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1213. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1214. return 0, err
  1215. }
  1216. }
  1217. if err := c.in.err; err != nil {
  1218. return 0, err
  1219. }
  1220. if c.input != nil {
  1221. n, err = c.input.Read(b)
  1222. if err == io.EOF {
  1223. err = nil
  1224. c.in.freeBlock(c.input)
  1225. c.input = nil
  1226. }
  1227. }
  1228. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1229. err = io.EOF
  1230. }
  1231. return
  1232. }
  1233. // Read can be made to time out and return a net.Error with Timeout() == true
  1234. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1235. func (c *Conn) Read(b []byte) (n int, err error) {
  1236. if err = c.Handshake(); err != nil {
  1237. return
  1238. }
  1239. if len(b) == 0 {
  1240. // Put this after Handshake, in case people were calling
  1241. // Read(nil) for the side effect of the Handshake.
  1242. return
  1243. }
  1244. c.confirmMutex.Lock()
  1245. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1246. c.confirmMutex.Unlock()
  1247. } else {
  1248. defer func() {
  1249. // If we transitioned to handshakeConfirmed we already released the lock,
  1250. // otherwise do it here.
  1251. if c.phase != handshakeConfirmed {
  1252. c.confirmMutex.Unlock()
  1253. }
  1254. }()
  1255. }
  1256. c.in.Lock()
  1257. defer c.in.Unlock()
  1258. // Some OpenSSL servers send empty records in order to randomize the
  1259. // CBC IV. So this loop ignores a limited number of empty records.
  1260. const maxConsecutiveEmptyRecords = 100
  1261. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1262. for c.input == nil && c.in.err == nil {
  1263. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1264. // Soft error, like EAGAIN
  1265. return 0, err
  1266. }
  1267. if c.hand.Len() > 0 {
  1268. // We received handshake bytes, indicating the
  1269. // start of a renegotiation.
  1270. if err := c.handleRenegotiation(); err != nil {
  1271. return 0, err
  1272. }
  1273. }
  1274. }
  1275. if err := c.in.err; err != nil {
  1276. return 0, err
  1277. }
  1278. n, err = c.input.Read(b)
  1279. if err == io.EOF {
  1280. err = nil
  1281. c.in.freeBlock(c.input)
  1282. c.input = nil
  1283. }
  1284. // If a close-notify alert is waiting, read it so that
  1285. // we can return (n, EOF) instead of (n, nil), to signal
  1286. // to the HTTP response reading goroutine that the
  1287. // connection is now closed. This eliminates a race
  1288. // where the HTTP response reading goroutine would
  1289. // otherwise not observe the EOF until its next read,
  1290. // by which time a client goroutine might have already
  1291. // tried to reuse the HTTP connection for a new
  1292. // request.
  1293. // See https://codereview.appspot.com/76400046
  1294. // and https://golang.org/issue/3514
  1295. if ri := c.rawInput; ri != nil &&
  1296. n != 0 && err == nil &&
  1297. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1298. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1299. err = recErr // will be io.EOF on closeNotify
  1300. }
  1301. }
  1302. if n != 0 || err != nil {
  1303. return n, err
  1304. }
  1305. }
  1306. return 0, io.ErrNoProgress
  1307. }
  1308. // Close closes the connection.
  1309. func (c *Conn) Close() error {
  1310. // Interlock with Conn.Write above.
  1311. var x int32
  1312. for {
  1313. x = atomic.LoadInt32(&c.activeCall)
  1314. if x&1 != 0 {
  1315. return errClosed
  1316. }
  1317. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1318. break
  1319. }
  1320. }
  1321. if x != 0 {
  1322. // io.Writer and io.Closer should not be used concurrently.
  1323. // If Close is called while a Write is currently in-flight,
  1324. // interpret that as a sign that this Close is really just
  1325. // being used to break the Write and/or clean up resources and
  1326. // avoid sending the alertCloseNotify, which may block
  1327. // waiting on handshakeMutex or the c.out mutex.
  1328. return c.conn.Close()
  1329. }
  1330. var alertErr error
  1331. c.handshakeMutex.Lock()
  1332. if c.handshakeComplete {
  1333. alertErr = c.closeNotify()
  1334. }
  1335. c.handshakeMutex.Unlock()
  1336. if err := c.conn.Close(); err != nil {
  1337. return err
  1338. }
  1339. return alertErr
  1340. }
  1341. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1342. // CloseWrite shuts down the writing side of the connection. It should only be
  1343. // called once the handshake has completed and does not call CloseWrite on the
  1344. // underlying connection. Most callers should just use Close.
  1345. func (c *Conn) CloseWrite() error {
  1346. c.handshakeMutex.Lock()
  1347. defer c.handshakeMutex.Unlock()
  1348. if !c.handshakeComplete {
  1349. return errEarlyCloseWrite
  1350. }
  1351. return c.closeNotify()
  1352. }
  1353. func (c *Conn) closeNotify() error {
  1354. c.out.Lock()
  1355. defer c.out.Unlock()
  1356. if !c.closeNotifySent {
  1357. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1358. c.closeNotifySent = true
  1359. }
  1360. return c.closeNotifyErr
  1361. }
  1362. // Handshake runs the client or server handshake
  1363. // protocol if it has not yet been run.
  1364. // Most uses of this package need not call Handshake
  1365. // explicitly: the first Read or Write will call it automatically.
  1366. //
  1367. // In TLS 1.3 Handshake returns after the client and server first flights,
  1368. // without waiting for the Client Finished.
  1369. func (c *Conn) Handshake() error {
  1370. c.handshakeMutex.Lock()
  1371. defer c.handshakeMutex.Unlock()
  1372. if err := c.handshakeErr; err != nil {
  1373. return err
  1374. }
  1375. if c.handshakeComplete {
  1376. return nil
  1377. }
  1378. c.in.Lock()
  1379. defer c.in.Unlock()
  1380. // The handshake cannot have completed when handshakeMutex was unlocked
  1381. // because this goroutine set handshakeCond.
  1382. if c.handshakeErr != nil || c.handshakeComplete {
  1383. panic("handshake should not have been able to complete after handshakeCond was set")
  1384. }
  1385. c.connID = make([]byte, 8)
  1386. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1387. return err
  1388. }
  1389. if c.isClient {
  1390. c.handshakeErr = c.clientHandshake()
  1391. } else {
  1392. c.handshakeErr = c.serverHandshake()
  1393. }
  1394. if c.handshakeErr == nil {
  1395. c.handshakes++
  1396. } else {
  1397. // If an error occurred during the hadshake try to flush the
  1398. // alert that might be left in the buffer.
  1399. c.flush()
  1400. }
  1401. if c.handshakeErr == nil && !c.handshakeComplete {
  1402. panic("handshake should have had a result.")
  1403. }
  1404. return c.handshakeErr
  1405. }
  1406. // ConnectionState returns basic TLS details about the connection.
  1407. func (c *Conn) ConnectionState() ConnectionState {
  1408. c.handshakeMutex.Lock()
  1409. defer c.handshakeMutex.Unlock()
  1410. var state ConnectionState
  1411. state.HandshakeComplete = c.handshakeComplete
  1412. state.ServerName = c.serverName
  1413. if c.handshakeComplete {
  1414. state.ConnectionID = c.connID
  1415. state.ClientHello = c.clientHello
  1416. state.Version = c.vers
  1417. state.NegotiatedProtocol = c.clientProtocol
  1418. state.DidResume = c.didResume
  1419. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1420. state.CipherSuite = c.cipherSuite
  1421. state.PeerCertificates = c.peerCertificates
  1422. state.VerifiedChains = c.verifiedChains
  1423. state.SignedCertificateTimestamps = c.scts
  1424. state.OCSPResponse = c.ocspResponse
  1425. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1426. if !state.HandshakeConfirmed {
  1427. state.Unique0RTTToken = c.binder
  1428. }
  1429. if !c.didResume {
  1430. if c.clientFinishedIsFirst {
  1431. state.TLSUnique = c.clientFinished[:]
  1432. } else {
  1433. state.TLSUnique = c.serverFinished[:]
  1434. }
  1435. }
  1436. }
  1437. return state
  1438. }
  1439. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1440. // any. (Only valid for client connections.)
  1441. func (c *Conn) OCSPResponse() []byte {
  1442. c.handshakeMutex.Lock()
  1443. defer c.handshakeMutex.Unlock()
  1444. return c.ocspResponse
  1445. }
  1446. // VerifyHostname checks that the peer certificate chain is valid for
  1447. // connecting to host. If so, it returns nil; if not, it returns an error
  1448. // describing the problem.
  1449. func (c *Conn) VerifyHostname(host string) error {
  1450. c.handshakeMutex.Lock()
  1451. defer c.handshakeMutex.Unlock()
  1452. if !c.isClient {
  1453. return errors.New("tls: VerifyHostname called on TLS server connection")
  1454. }
  1455. if !c.handshakeComplete {
  1456. return errors.New("tls: handshake has not yet been performed")
  1457. }
  1458. if len(c.verifiedChains) == 0 {
  1459. return errors.New("tls: handshake did not verify certificate chain")
  1460. }
  1461. return c.peerCertificates[0].VerifyHostname(host)
  1462. }