Alternative TLS implementation in Go
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1626 lines
45 KiB

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