Alternative TLS implementation in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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