conn.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. // handshakeStatus is 1 if the connection is currently transferring
  26. // application data (i.e. is not currently processing a handshake).
  27. // This field is only to be accessed with sync/atomic.
  28. handshakeStatus uint32
  29. // constant after handshake; protected by handshakeMutex
  30. handshakeMutex sync.Mutex
  31. handshakeErr error // error resulting from handshake
  32. vers uint16 // TLS version
  33. haveVers bool // version has been negotiated
  34. config *Config // configuration passed to constructor
  35. // handshakes counts the number of handshakes performed on the
  36. // connection so far. If renegotiation is disabled then this is either
  37. // zero or one.
  38. handshakes int
  39. didResume bool // whether this connection was a session resumption
  40. cipherSuite uint16
  41. ocspResponse []byte // stapled OCSP response
  42. scts [][]byte // signed certificate timestamps from server
  43. peerCertificates []*x509.Certificate
  44. // verifiedChains contains the certificate chains that we built, as
  45. // opposed to the ones presented by the server.
  46. verifiedChains [][]*x509.Certificate
  47. // serverName contains the server name indicated by the client, if any.
  48. serverName string
  49. // secureRenegotiation is true if the server echoed the secure
  50. // renegotiation extension. (This is meaningless as a server because
  51. // renegotiation is not supported in that case.)
  52. secureRenegotiation bool
  53. // ekm is a closure for exporting keying material.
  54. ekm func(label string, context []byte, length int) ([]byte, error)
  55. // resumptionSecret is the resumption_master_secret for handling
  56. // NewSessionTicket messages. nil if config.SessionTicketsDisabled.
  57. resumptionSecret []byte
  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. // input/output
  77. in, out halfConn
  78. rawInput bytes.Buffer // raw input, starting with a record header
  79. input bytes.Reader // application data waiting to be read, from rawInput.Next
  80. hand bytes.Buffer // handshake data waiting to be read
  81. outBuf []byte // scratch buffer used by out.encrypt
  82. buffering bool // whether records are buffered in sendBuf
  83. sendBuf []byte // a buffer of records waiting to be sent
  84. // bytesSent counts the bytes of application data sent.
  85. // packetsSent counts packets.
  86. bytesSent int64
  87. packetsSent int64
  88. // retryCount counts the number of consecutive non-advancing records
  89. // received by Conn.readRecord. That is, records that neither advance the
  90. // handshake, nor deliver application data. Protected by in.Mutex.
  91. retryCount int
  92. // activeCall is an atomic int32; the low bit is whether Close has
  93. // been called. the rest of the bits are the number of goroutines
  94. // in Conn.Write.
  95. activeCall int32
  96. tmp [16]byte
  97. }
  98. // Access to net.Conn methods.
  99. // Cannot just embed net.Conn because that would
  100. // export the struct field too.
  101. // LocalAddr returns the local network address.
  102. func (c *Conn) LocalAddr() net.Addr {
  103. return c.conn.LocalAddr()
  104. }
  105. // RemoteAddr returns the remote network address.
  106. func (c *Conn) RemoteAddr() net.Addr {
  107. return c.conn.RemoteAddr()
  108. }
  109. // SetDeadline sets the read and write deadlines associated with the connection.
  110. // A zero value for t means Read and Write will not time out.
  111. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  112. func (c *Conn) SetDeadline(t time.Time) error {
  113. return c.conn.SetDeadline(t)
  114. }
  115. // SetReadDeadline sets the read deadline on the underlying connection.
  116. // A zero value for t means Read will not time out.
  117. func (c *Conn) SetReadDeadline(t time.Time) error {
  118. return c.conn.SetReadDeadline(t)
  119. }
  120. // SetWriteDeadline sets the write deadline on the underlying connection.
  121. // A zero value for t means Write will not time out.
  122. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  123. func (c *Conn) SetWriteDeadline(t time.Time) error {
  124. return c.conn.SetWriteDeadline(t)
  125. }
  126. // A halfConn represents one direction of the record layer
  127. // connection, either sending or receiving.
  128. type halfConn struct {
  129. sync.Mutex
  130. err error // first permanent error
  131. version uint16 // protocol version
  132. cipher interface{} // cipher algorithm
  133. mac macFunction
  134. seq [8]byte // 64-bit sequence number
  135. additionalData [13]byte // to avoid allocs; interface method args escape
  136. nextCipher interface{} // next encryption state
  137. nextMac macFunction // next MAC algorithm
  138. trafficSecret []byte // current TLS 1.3 traffic secret
  139. }
  140. func (hc *halfConn) setErrorLocked(err error) error {
  141. hc.err = err
  142. return err
  143. }
  144. // prepareCipherSpec sets the encryption and MAC states
  145. // that a subsequent changeCipherSpec will use.
  146. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  147. hc.version = version
  148. hc.nextCipher = cipher
  149. hc.nextMac = mac
  150. }
  151. // changeCipherSpec changes the encryption and MAC states
  152. // to the ones previously passed to prepareCipherSpec.
  153. func (hc *halfConn) changeCipherSpec() error {
  154. if hc.nextCipher == nil || hc.version == VersionTLS13 {
  155. return alertInternalError
  156. }
  157. hc.cipher = hc.nextCipher
  158. hc.mac = hc.nextMac
  159. hc.nextCipher = nil
  160. hc.nextMac = nil
  161. for i := range hc.seq {
  162. hc.seq[i] = 0
  163. }
  164. return nil
  165. }
  166. func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) {
  167. hc.trafficSecret = secret
  168. key, iv := suite.trafficKey(secret)
  169. hc.cipher = suite.aead(key, iv)
  170. for i := range hc.seq {
  171. hc.seq[i] = 0
  172. }
  173. }
  174. // incSeq increments the sequence number.
  175. func (hc *halfConn) incSeq() {
  176. for i := 7; i >= 0; i-- {
  177. hc.seq[i]++
  178. if hc.seq[i] != 0 {
  179. return
  180. }
  181. }
  182. // Not allowed to let sequence number wrap.
  183. // Instead, must renegotiate before it does.
  184. // Not likely enough to bother.
  185. panic("TLS: sequence number wraparound")
  186. }
  187. // explicitNonceLen returns the number of bytes of explicit nonce or IV included
  188. // in each record. Explicit nonces are present only in CBC modes after TLS 1.0
  189. // and in certain AEAD modes in TLS 1.2.
  190. func (hc *halfConn) explicitNonceLen() int {
  191. if hc.cipher == nil {
  192. return 0
  193. }
  194. switch c := hc.cipher.(type) {
  195. case cipher.Stream:
  196. return 0
  197. case aead:
  198. return c.explicitNonceLen()
  199. case cbcMode:
  200. // TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack.
  201. if hc.version >= VersionTLS11 {
  202. return c.BlockSize()
  203. }
  204. return 0
  205. default:
  206. panic("unknown cipher type")
  207. }
  208. }
  209. // extractPadding returns, in constant time, the length of the padding to remove
  210. // from the end of payload. It also returns a byte which is equal to 255 if the
  211. // padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
  212. func extractPadding(payload []byte) (toRemove int, good byte) {
  213. if len(payload) < 1 {
  214. return 0, 0
  215. }
  216. paddingLen := payload[len(payload)-1]
  217. t := uint(len(payload)-1) - uint(paddingLen)
  218. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  219. good = byte(int32(^t) >> 31)
  220. // The maximum possible padding length plus the actual length field
  221. toCheck := 256
  222. // The length of the padded data is public, so we can use an if here
  223. if toCheck > len(payload) {
  224. toCheck = len(payload)
  225. }
  226. for i := 0; i < toCheck; i++ {
  227. t := uint(paddingLen) - uint(i)
  228. // if i <= paddingLen then the MSB of t is zero
  229. mask := byte(int32(^t) >> 31)
  230. b := payload[len(payload)-1-i]
  231. good &^= mask&paddingLen ^ mask&b
  232. }
  233. // We AND together the bits of good and replicate the result across
  234. // all the bits.
  235. good &= good << 4
  236. good &= good << 2
  237. good &= good << 1
  238. good = uint8(int8(good) >> 7)
  239. toRemove = int(paddingLen) + 1
  240. return
  241. }
  242. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  243. // protocol version is SSLv3. In this version, the contents of the padding
  244. // are random and cannot be checked.
  245. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  246. if len(payload) < 1 {
  247. return 0, 0
  248. }
  249. paddingLen := int(payload[len(payload)-1]) + 1
  250. if paddingLen > len(payload) {
  251. return 0, 0
  252. }
  253. return paddingLen, 255
  254. }
  255. func roundUp(a, b int) int {
  256. return a + (b-a%b)%b
  257. }
  258. // cbcMode is an interface for block ciphers using cipher block chaining.
  259. type cbcMode interface {
  260. cipher.BlockMode
  261. SetIV([]byte)
  262. }
  263. // decrypt authenticates and decrypts the record if protection is active at
  264. // this stage. The returned plaintext might overlap with the input.
  265. func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) {
  266. var plaintext []byte
  267. typ := recordType(record[0])
  268. payload := record[recordHeaderLen:]
  269. // In TLS 1.3, change_cipher_spec messages are to be ignored without being
  270. // decrypted. See RFC 8446, Appendix D.4.
  271. if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec {
  272. return payload, typ, nil
  273. }
  274. paddingGood := byte(255)
  275. paddingLen := 0
  276. explicitNonceLen := hc.explicitNonceLen()
  277. if hc.cipher != nil {
  278. switch c := hc.cipher.(type) {
  279. case cipher.Stream:
  280. c.XORKeyStream(payload, payload)
  281. case aead:
  282. if len(payload) < explicitNonceLen {
  283. return nil, 0, alertBadRecordMAC
  284. }
  285. nonce := payload[:explicitNonceLen]
  286. if len(nonce) == 0 {
  287. nonce = hc.seq[:]
  288. }
  289. payload = payload[explicitNonceLen:]
  290. additionalData := hc.additionalData[:]
  291. if hc.version == VersionTLS13 {
  292. additionalData = record[:recordHeaderLen]
  293. } else {
  294. copy(additionalData, hc.seq[:])
  295. copy(additionalData[8:], record[:3])
  296. n := len(payload) - c.Overhead()
  297. additionalData[11] = byte(n >> 8)
  298. additionalData[12] = byte(n)
  299. }
  300. var err error
  301. plaintext, err = c.Open(payload[:0], nonce, payload, additionalData)
  302. if err != nil {
  303. return nil, 0, alertBadRecordMAC
  304. }
  305. case cbcMode:
  306. blockSize := c.BlockSize()
  307. minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize)
  308. if len(payload)%blockSize != 0 || len(payload) < minPayload {
  309. return nil, 0, alertBadRecordMAC
  310. }
  311. if explicitNonceLen > 0 {
  312. c.SetIV(payload[:explicitNonceLen])
  313. payload = payload[explicitNonceLen:]
  314. }
  315. c.CryptBlocks(payload, payload)
  316. // In a limited attempt to protect against CBC padding oracles like
  317. // Lucky13, the data past paddingLen (which is secret) is passed to
  318. // the MAC function as extra data, to be fed into the HMAC after
  319. // computing the digest. This makes the MAC roughly constant time as
  320. // long as the digest computation is constant time and does not
  321. // affect the subsequent write, modulo cache effects.
  322. if hc.version == VersionSSL30 {
  323. paddingLen, paddingGood = extractPaddingSSL30(payload)
  324. } else {
  325. paddingLen, paddingGood = extractPadding(payload)
  326. }
  327. default:
  328. panic("unknown cipher type")
  329. }
  330. if hc.version == VersionTLS13 {
  331. if typ != recordTypeApplicationData {
  332. return nil, 0, alertUnexpectedMessage
  333. }
  334. if len(plaintext) > maxPlaintext+1 {
  335. return nil, 0, alertRecordOverflow
  336. }
  337. // Remove padding and find the ContentType scanning from the end.
  338. for i := len(plaintext) - 1; i >= 0; i-- {
  339. if plaintext[i] != 0 {
  340. typ = recordType(plaintext[i])
  341. plaintext = plaintext[:i]
  342. break
  343. }
  344. if i == 0 {
  345. return nil, 0, alertUnexpectedMessage
  346. }
  347. }
  348. }
  349. } else {
  350. plaintext = payload
  351. }
  352. if hc.mac != nil {
  353. macSize := hc.mac.Size()
  354. if len(payload) < macSize {
  355. return nil, 0, alertBadRecordMAC
  356. }
  357. n := len(payload) - macSize - paddingLen
  358. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  359. record[3] = byte(n >> 8)
  360. record[4] = byte(n)
  361. remoteMAC := payload[n : n+macSize]
  362. localMAC := hc.mac.MAC(hc.seq[0:], record[:recordHeaderLen], payload[:n], payload[n+macSize:])
  363. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  364. return nil, 0, alertBadRecordMAC
  365. }
  366. plaintext = payload[:n]
  367. }
  368. hc.incSeq()
  369. return plaintext, typ, nil
  370. }
  371. // sliceForAppend extends the input slice by n bytes. head is the full extended
  372. // slice, while tail is the appended part. If the original slice has sufficient
  373. // capacity no allocation is performed.
  374. func sliceForAppend(in []byte, n int) (head, tail []byte) {
  375. if total := len(in) + n; cap(in) >= total {
  376. head = in[:total]
  377. } else {
  378. head = make([]byte, total)
  379. copy(head, in)
  380. }
  381. tail = head[len(in):]
  382. return
  383. }
  384. // encrypt encrypts payload, adding the appropriate nonce and/or MAC, and
  385. // appends it to record, which contains the record header.
  386. func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) {
  387. if hc.cipher == nil {
  388. return append(record, payload...), nil
  389. }
  390. var explicitNonce []byte
  391. if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 {
  392. record, explicitNonce = sliceForAppend(record, explicitNonceLen)
  393. if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 {
  394. // The AES-GCM construction in TLS has an explicit nonce so that the
  395. // nonce can be random. However, the nonce is only 8 bytes which is
  396. // too small for a secure, random nonce. Therefore we use the
  397. // sequence number as the nonce. The 3DES-CBC construction also has
  398. // an 8 bytes nonce but its nonces must be unpredictable (see RFC
  399. // 5246, Appendix F.3), forcing us to use randomness. That's not
  400. // 3DES' biggest problem anyway because the birthday bound on block
  401. // collision is reached first due to its simlarly small block size
  402. // (see the Sweet32 attack).
  403. copy(explicitNonce, hc.seq[:])
  404. } else {
  405. if _, err := io.ReadFull(rand, explicitNonce); err != nil {
  406. return nil, err
  407. }
  408. }
  409. }
  410. var mac []byte
  411. if hc.mac != nil {
  412. mac = hc.mac.MAC(hc.seq[:], record[:recordHeaderLen], payload, nil)
  413. }
  414. var dst []byte
  415. switch c := hc.cipher.(type) {
  416. case cipher.Stream:
  417. record, dst = sliceForAppend(record, len(payload)+len(mac))
  418. c.XORKeyStream(dst[:len(payload)], payload)
  419. c.XORKeyStream(dst[len(payload):], mac)
  420. case aead:
  421. nonce := explicitNonce
  422. if len(nonce) == 0 {
  423. nonce = hc.seq[:]
  424. }
  425. if hc.version == VersionTLS13 {
  426. record = append(record, payload...)
  427. // Encrypt the actual ContentType and replace the plaintext one.
  428. record = append(record, record[0])
  429. record[0] = byte(recordTypeApplicationData)
  430. n := len(payload) + 1 + c.Overhead()
  431. record[3] = byte(n >> 8)
  432. record[4] = byte(n)
  433. record = c.Seal(record[:recordHeaderLen],
  434. nonce, record[recordHeaderLen:], record[:recordHeaderLen])
  435. } else {
  436. copy(hc.additionalData[:], hc.seq[:])
  437. copy(hc.additionalData[8:], record)
  438. record = c.Seal(record, nonce, payload, hc.additionalData[:])
  439. }
  440. case cbcMode:
  441. blockSize := c.BlockSize()
  442. plaintextLen := len(payload) + len(mac)
  443. paddingLen := blockSize - plaintextLen%blockSize
  444. record, dst = sliceForAppend(record, plaintextLen+paddingLen)
  445. copy(dst, payload)
  446. copy(dst[len(payload):], mac)
  447. for i := plaintextLen; i < len(dst); i++ {
  448. dst[i] = byte(paddingLen - 1)
  449. }
  450. if len(explicitNonce) > 0 {
  451. c.SetIV(explicitNonce)
  452. }
  453. c.CryptBlocks(dst, dst)
  454. default:
  455. panic("unknown cipher type")
  456. }
  457. // Update length to include nonce, MAC and any block padding needed.
  458. n := len(record) - recordHeaderLen
  459. record[3] = byte(n >> 8)
  460. record[4] = byte(n)
  461. hc.incSeq()
  462. return record, nil
  463. }
  464. // RecordHeaderError is returned when a TLS record header is invalid.
  465. type RecordHeaderError struct {
  466. // Msg contains a human readable string that describes the error.
  467. Msg string
  468. // RecordHeader contains the five bytes of TLS record header that
  469. // triggered the error.
  470. RecordHeader [5]byte
  471. // Conn provides the underlying net.Conn in the case that a client
  472. // sent an initial handshake that didn't look like TLS.
  473. // It is nil if there's already been a handshake or a TLS alert has
  474. // been written to the connection.
  475. Conn net.Conn
  476. }
  477. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  478. func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) {
  479. err.Msg = msg
  480. err.Conn = conn
  481. copy(err.RecordHeader[:], c.rawInput.Bytes())
  482. return err
  483. }
  484. func (c *Conn) readRecord() error {
  485. return c.readRecordOrCCS(false)
  486. }
  487. func (c *Conn) readChangeCipherSpec() error {
  488. return c.readRecordOrCCS(true)
  489. }
  490. // readRecordOrCCS reads one or more TLS records from the connection and
  491. // updates the record layer state. Some invariants:
  492. // * c.in must be locked
  493. // * c.input must be empty
  494. // During the handshake one and only one of the following will happen:
  495. // - c.hand grows
  496. // - c.in.changeCipherSpec is called
  497. // - an error is returned
  498. // After the handshake one and only one of the following will happen:
  499. // - c.hand grows
  500. // - c.input is set
  501. // - an error is returned
  502. func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error {
  503. if c.in.err != nil {
  504. return c.in.err
  505. }
  506. handshakeComplete := c.handshakeComplete()
  507. // This function modifies c.rawInput, which owns the c.input memory.
  508. if c.input.Len() != 0 {
  509. return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data"))
  510. }
  511. c.input.Reset(nil)
  512. // Read header, payload.
  513. if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil {
  514. // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
  515. // is an error, but popular web sites seem to do this, so we accept it
  516. // if and only if at the record boundary.
  517. if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 {
  518. err = io.EOF
  519. }
  520. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  521. c.in.setErrorLocked(err)
  522. }
  523. return err
  524. }
  525. hdr := c.rawInput.Bytes()[:recordHeaderLen]
  526. typ := recordType(hdr[0])
  527. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  528. // start with a uint16 length where the MSB is set and the first record
  529. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  530. // an SSLv2 client.
  531. if !handshakeComplete && typ == 0x80 {
  532. c.sendAlert(alertProtocolVersion)
  533. return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received"))
  534. }
  535. vers := uint16(hdr[1])<<8 | uint16(hdr[2])
  536. n := int(hdr[3])<<8 | int(hdr[4])
  537. if c.haveVers && c.vers != VersionTLS13 && vers != c.vers {
  538. c.sendAlert(alertProtocolVersion)
  539. msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
  540. return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
  541. }
  542. if !c.haveVers {
  543. // First message, be extra suspicious: this might not be a TLS
  544. // client. Bail out before reading a full 'body', if possible.
  545. // The current max version is 3.3 so if the version is >= 16.0,
  546. // it's probably not real.
  547. if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
  548. return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
  549. }
  550. }
  551. if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext {
  552. c.sendAlert(alertRecordOverflow)
  553. msg := fmt.Sprintf("oversized record received with length %d", n)
  554. return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
  555. }
  556. if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  557. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  558. c.in.setErrorLocked(err)
  559. }
  560. return err
  561. }
  562. // Process message.
  563. record := c.rawInput.Next(recordHeaderLen + n)
  564. data, typ, err := c.in.decrypt(record)
  565. if err != nil {
  566. return c.in.setErrorLocked(c.sendAlert(err.(alert)))
  567. }
  568. if len(data) > maxPlaintext {
  569. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  570. }
  571. // Application Data messages are always protected.
  572. if c.in.cipher == nil && typ == recordTypeApplicationData {
  573. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  574. }
  575. if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
  576. // This is a state-advancing message: reset the retry count.
  577. c.retryCount = 0
  578. }
  579. // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
  580. if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 {
  581. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  582. }
  583. switch typ {
  584. default:
  585. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  586. case recordTypeAlert:
  587. if len(data) != 2 {
  588. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  589. }
  590. if alert(data[1]) == alertCloseNotify {
  591. return c.in.setErrorLocked(io.EOF)
  592. }
  593. if c.vers == VersionTLS13 {
  594. return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  595. }
  596. switch data[0] {
  597. case alertLevelWarning:
  598. // Drop the record on the floor and retry.
  599. return c.retryReadRecord(expectChangeCipherSpec)
  600. case alertLevelError:
  601. return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  602. default:
  603. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  604. }
  605. case recordTypeChangeCipherSpec:
  606. if len(data) != 1 || data[0] != 1 {
  607. return c.in.setErrorLocked(c.sendAlert(alertDecodeError))
  608. }
  609. // Handshake messages are not allowed to fragment across the CCS.
  610. if c.hand.Len() > 0 {
  611. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  612. }
  613. // In TLS 1.3, change_cipher_spec records are ignored until the
  614. // Finished. See RFC 8446, Appendix D.4. Note that according to Section
  615. // 5, a server can send a ChangeCipherSpec before its ServerHello, when
  616. // c.vers is still unset. That's not useful though and suspicious if the
  617. // server then selects a lower protocol version, so don't allow that.
  618. if c.vers == VersionTLS13 {
  619. return c.retryReadRecord(expectChangeCipherSpec)
  620. }
  621. if !expectChangeCipherSpec {
  622. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  623. }
  624. if err := c.in.changeCipherSpec(); err != nil {
  625. return c.in.setErrorLocked(c.sendAlert(err.(alert)))
  626. }
  627. case recordTypeApplicationData:
  628. if !handshakeComplete || expectChangeCipherSpec {
  629. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  630. }
  631. // Some OpenSSL servers send empty records in order to randomize the
  632. // CBC IV. Ignore a limited number of empty records.
  633. if len(data) == 0 {
  634. return c.retryReadRecord(expectChangeCipherSpec)
  635. }
  636. // Note that data is owned by c.rawInput, following the Next call above,
  637. // to avoid copying the plaintext. This is safe because c.rawInput is
  638. // not read from or written to until c.input is drained.
  639. c.input.Reset(data)
  640. case recordTypeHandshake:
  641. if len(data) == 0 || expectChangeCipherSpec {
  642. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  643. }
  644. c.hand.Write(data)
  645. }
  646. return nil
  647. }
  648. // retryReadRecord recurses into readRecordOrCCS to drop a non-advancing record, like
  649. // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
  650. func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error {
  651. c.retryCount++
  652. if c.retryCount > maxUselessRecords {
  653. c.sendAlert(alertUnexpectedMessage)
  654. return c.in.setErrorLocked(errors.New("tls: too many ignored records"))
  655. }
  656. return c.readRecordOrCCS(expectChangeCipherSpec)
  657. }
  658. // atLeastReader reads from R, stopping with EOF once at least N bytes have been
  659. // read. It is different from an io.LimitedReader in that it doesn't cut short
  660. // the last Read call, and in that it considers an early EOF an error.
  661. type atLeastReader struct {
  662. R io.Reader
  663. N int64
  664. }
  665. func (r *atLeastReader) Read(p []byte) (int, error) {
  666. if r.N <= 0 {
  667. return 0, io.EOF
  668. }
  669. n, err := r.R.Read(p)
  670. r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
  671. if r.N > 0 && err == io.EOF {
  672. return n, io.ErrUnexpectedEOF
  673. }
  674. if r.N <= 0 && err == nil {
  675. return n, io.EOF
  676. }
  677. return n, err
  678. }
  679. // readFromUntil reads from r into c.rawInput until c.rawInput contains
  680. // at least n bytes or else returns an error.
  681. func (c *Conn) readFromUntil(r io.Reader, n int) error {
  682. if c.rawInput.Len() >= n {
  683. return nil
  684. }
  685. needs := n - c.rawInput.Len()
  686. // There might be extra input waiting on the wire. Make a best effort
  687. // attempt to fetch it so that it can be used in (*Conn).Read to
  688. // "predict" closeNotify alerts.
  689. c.rawInput.Grow(needs + bytes.MinRead)
  690. _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)})
  691. return err
  692. }
  693. // sendAlert sends a TLS alert message.
  694. func (c *Conn) sendAlertLocked(err alert) error {
  695. switch err {
  696. case alertNoRenegotiation, alertCloseNotify:
  697. c.tmp[0] = alertLevelWarning
  698. default:
  699. c.tmp[0] = alertLevelError
  700. }
  701. c.tmp[1] = byte(err)
  702. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  703. if err == alertCloseNotify {
  704. // closeNotify is a special case in that it isn't an error.
  705. return writeErr
  706. }
  707. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  708. }
  709. // sendAlert sends a TLS alert message.
  710. func (c *Conn) sendAlert(err alert) error {
  711. c.out.Lock()
  712. defer c.out.Unlock()
  713. return c.sendAlertLocked(err)
  714. }
  715. const (
  716. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  717. // size (MSS). A constant is used, rather than querying the kernel for
  718. // the actual MSS, to avoid complexity. The value here is the IPv6
  719. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  720. // bytes) and a TCP header with timestamps (32 bytes).
  721. tcpMSSEstimate = 1208
  722. // recordSizeBoostThreshold is the number of bytes of application data
  723. // sent after which the TLS record size will be increased to the
  724. // maximum.
  725. recordSizeBoostThreshold = 128 * 1024
  726. )
  727. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  728. // next application data record. There is the following trade-off:
  729. //
  730. // - For latency-sensitive applications, such as web browsing, each TLS
  731. // record should fit in one TCP segment.
  732. // - For throughput-sensitive applications, such as large file transfers,
  733. // larger TLS records better amortize framing and encryption overheads.
  734. //
  735. // A simple heuristic that works well in practice is to use small records for
  736. // the first 1MB of data, then use larger records for subsequent data, and
  737. // reset back to smaller records after the connection becomes idle. See "High
  738. // Performance Web Networking", Chapter 4, or:
  739. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  740. //
  741. // In the interests of simplicity and determinism, this code does not attempt
  742. // to reset the record size once the connection is idle, however.
  743. func (c *Conn) maxPayloadSizeForWrite(typ recordType) int {
  744. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  745. return maxPlaintext
  746. }
  747. if c.bytesSent >= recordSizeBoostThreshold {
  748. return maxPlaintext
  749. }
  750. // Subtract TLS overheads to get the maximum payload size.
  751. payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen()
  752. if c.out.cipher != nil {
  753. switch ciph := c.out.cipher.(type) {
  754. case cipher.Stream:
  755. payloadBytes -= c.out.mac.Size()
  756. case cipher.AEAD:
  757. payloadBytes -= ciph.Overhead()
  758. case cbcMode:
  759. blockSize := ciph.BlockSize()
  760. // The payload must fit in a multiple of blockSize, with
  761. // room for at least one padding byte.
  762. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  763. // The MAC is appended before padding so affects the
  764. // payload size directly.
  765. payloadBytes -= c.out.mac.Size()
  766. default:
  767. panic("unknown cipher type")
  768. }
  769. }
  770. if c.vers == VersionTLS13 {
  771. payloadBytes-- // encrypted ContentType
  772. }
  773. // Allow packet growth in arithmetic progression up to max.
  774. pkt := c.packetsSent
  775. c.packetsSent++
  776. if pkt > 1000 {
  777. return maxPlaintext // avoid overflow in multiply below
  778. }
  779. n := payloadBytes * int(pkt+1)
  780. if n > maxPlaintext {
  781. n = maxPlaintext
  782. }
  783. return n
  784. }
  785. func (c *Conn) write(data []byte) (int, error) {
  786. if c.buffering {
  787. c.sendBuf = append(c.sendBuf, data...)
  788. return len(data), nil
  789. }
  790. n, err := c.conn.Write(data)
  791. c.bytesSent += int64(n)
  792. return n, err
  793. }
  794. func (c *Conn) flush() (int, error) {
  795. if len(c.sendBuf) == 0 {
  796. return 0, nil
  797. }
  798. n, err := c.conn.Write(c.sendBuf)
  799. c.bytesSent += int64(n)
  800. c.sendBuf = nil
  801. c.buffering = false
  802. return n, err
  803. }
  804. // writeRecordLocked writes a TLS record with the given type and payload to the
  805. // connection and updates the record layer state.
  806. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  807. var n int
  808. for len(data) > 0 {
  809. m := len(data)
  810. if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload {
  811. m = maxPayload
  812. }
  813. _, c.outBuf = sliceForAppend(c.outBuf[:0], recordHeaderLen)
  814. c.outBuf[0] = byte(typ)
  815. vers := c.vers
  816. if vers == 0 {
  817. // Some TLS servers fail if the record version is
  818. // greater than TLS 1.0 for the initial ClientHello.
  819. vers = VersionTLS10
  820. } else if vers == VersionTLS13 {
  821. // TLS 1.3 froze the record layer version to 1.2.
  822. // See RFC 8446, Section 5.1.
  823. vers = VersionTLS12
  824. }
  825. c.outBuf[1] = byte(vers >> 8)
  826. c.outBuf[2] = byte(vers)
  827. c.outBuf[3] = byte(m >> 8)
  828. c.outBuf[4] = byte(m)
  829. var err error
  830. c.outBuf, err = c.out.encrypt(c.outBuf, data[:m], c.config.rand())
  831. if err != nil {
  832. return n, err
  833. }
  834. if _, err := c.write(c.outBuf); err != nil {
  835. return n, err
  836. }
  837. n += m
  838. data = data[m:]
  839. }
  840. if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 {
  841. if err := c.out.changeCipherSpec(); err != nil {
  842. return n, c.sendAlertLocked(err.(alert))
  843. }
  844. }
  845. return n, nil
  846. }
  847. // writeRecord writes a TLS record with the given type and payload to the
  848. // connection and updates the record layer state.
  849. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  850. c.out.Lock()
  851. defer c.out.Unlock()
  852. return c.writeRecordLocked(typ, data)
  853. }
  854. // readHandshake reads the next handshake message from
  855. // the record layer.
  856. func (c *Conn) readHandshake() (interface{}, error) {
  857. for c.hand.Len() < 4 {
  858. if err := c.readRecord(); err != nil {
  859. return nil, err
  860. }
  861. }
  862. data := c.hand.Bytes()
  863. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  864. if n > maxHandshake {
  865. c.sendAlertLocked(alertInternalError)
  866. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  867. }
  868. for c.hand.Len() < 4+n {
  869. if err := c.readRecord(); err != nil {
  870. return nil, err
  871. }
  872. }
  873. data = c.hand.Next(4 + n)
  874. var m handshakeMessage
  875. switch data[0] {
  876. case typeHelloRequest:
  877. m = new(helloRequestMsg)
  878. case typeClientHello:
  879. m = new(clientHelloMsg)
  880. case typeServerHello:
  881. m = new(serverHelloMsg)
  882. case typeNewSessionTicket:
  883. if c.vers == VersionTLS13 {
  884. m = new(newSessionTicketMsgTLS13)
  885. } else {
  886. m = new(newSessionTicketMsg)
  887. }
  888. case typeCertificate:
  889. if c.vers == VersionTLS13 {
  890. m = new(certificateMsgTLS13)
  891. } else {
  892. m = new(certificateMsg)
  893. }
  894. case typeCertificateRequest:
  895. if c.vers == VersionTLS13 {
  896. m = new(certificateRequestMsgTLS13)
  897. } else {
  898. m = &certificateRequestMsg{
  899. hasSignatureAlgorithm: c.vers >= VersionTLS12,
  900. }
  901. }
  902. case typeCertificateStatus:
  903. m = new(certificateStatusMsg)
  904. case typeServerKeyExchange:
  905. m = new(serverKeyExchangeMsg)
  906. case typeServerHelloDone:
  907. m = new(serverHelloDoneMsg)
  908. case typeClientKeyExchange:
  909. m = new(clientKeyExchangeMsg)
  910. case typeCertificateVerify:
  911. m = &certificateVerifyMsg{
  912. hasSignatureAlgorithm: c.vers >= VersionTLS12,
  913. }
  914. case typeNextProtocol:
  915. m = new(nextProtoMsg)
  916. case typeFinished:
  917. m = new(finishedMsg)
  918. case typeEncryptedExtensions:
  919. m = new(encryptedExtensionsMsg)
  920. case typeEndOfEarlyData:
  921. m = new(endOfEarlyDataMsg)
  922. case typeKeyUpdate:
  923. m = new(keyUpdateMsg)
  924. default:
  925. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  926. }
  927. // The handshake message unmarshalers
  928. // expect to be able to keep references to data,
  929. // so pass in a fresh copy that won't be overwritten.
  930. data = append([]byte(nil), data...)
  931. if !m.unmarshal(data) {
  932. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  933. }
  934. return m, nil
  935. }
  936. var (
  937. errClosed = errors.New("tls: use of closed connection")
  938. errShutdown = errors.New("tls: protocol is shutdown")
  939. )
  940. // Write writes data to the connection.
  941. func (c *Conn) Write(b []byte) (int, error) {
  942. // interlock with Close below
  943. for {
  944. x := atomic.LoadInt32(&c.activeCall)
  945. if x&1 != 0 {
  946. return 0, errClosed
  947. }
  948. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  949. defer atomic.AddInt32(&c.activeCall, -2)
  950. break
  951. }
  952. }
  953. if err := c.Handshake(); err != nil {
  954. return 0, err
  955. }
  956. c.out.Lock()
  957. defer c.out.Unlock()
  958. if err := c.out.err; err != nil {
  959. return 0, err
  960. }
  961. if !c.handshakeComplete() {
  962. return 0, alertInternalError
  963. }
  964. if c.closeNotifySent {
  965. return 0, errShutdown
  966. }
  967. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  968. // attack when using block mode ciphers due to predictable IVs.
  969. // This can be prevented by splitting each Application Data
  970. // record into two records, effectively randomizing the IV.
  971. //
  972. // https://www.openssl.org/~bodo/tls-cbc.txt
  973. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  974. // https://www.imperialviolet.org/2012/01/15/beastfollowup.html
  975. var m int
  976. if len(b) > 1 && c.vers <= VersionTLS10 {
  977. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  978. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  979. if err != nil {
  980. return n, c.out.setErrorLocked(err)
  981. }
  982. m, b = 1, b[1:]
  983. }
  984. }
  985. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  986. return n + m, c.out.setErrorLocked(err)
  987. }
  988. // handleRenegotiation processes a HelloRequest handshake message.
  989. func (c *Conn) handleRenegotiation() error {
  990. if c.vers == VersionTLS13 {
  991. return errors.New("tls: internal error: unexpected renegotiation")
  992. }
  993. msg, err := c.readHandshake()
  994. if err != nil {
  995. return err
  996. }
  997. helloReq, ok := msg.(*helloRequestMsg)
  998. if !ok {
  999. c.sendAlert(alertUnexpectedMessage)
  1000. return unexpectedMessageError(helloReq, msg)
  1001. }
  1002. if !c.isClient {
  1003. return c.sendAlert(alertNoRenegotiation)
  1004. }
  1005. switch c.config.Renegotiation {
  1006. case RenegotiateNever:
  1007. return c.sendAlert(alertNoRenegotiation)
  1008. case RenegotiateOnceAsClient:
  1009. if c.handshakes > 1 {
  1010. return c.sendAlert(alertNoRenegotiation)
  1011. }
  1012. case RenegotiateFreelyAsClient:
  1013. // Ok.
  1014. default:
  1015. c.sendAlert(alertInternalError)
  1016. return errors.New("tls: unknown Renegotiation value")
  1017. }
  1018. c.handshakeMutex.Lock()
  1019. defer c.handshakeMutex.Unlock()
  1020. atomic.StoreUint32(&c.handshakeStatus, 0)
  1021. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1022. c.handshakes++
  1023. }
  1024. return c.handshakeErr
  1025. }
  1026. // handlePostHandshakeMessage processes a handshake message arrived after the
  1027. // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.
  1028. func (c *Conn) handlePostHandshakeMessage() error {
  1029. if c.vers != VersionTLS13 {
  1030. return c.handleRenegotiation()
  1031. }
  1032. msg, err := c.readHandshake()
  1033. if err != nil {
  1034. return err
  1035. }
  1036. c.retryCount++
  1037. if c.retryCount > maxUselessRecords {
  1038. c.sendAlert(alertUnexpectedMessage)
  1039. return c.in.setErrorLocked(errors.New("tls: too many non-advancing records"))
  1040. }
  1041. switch msg := msg.(type) {
  1042. case *newSessionTicketMsgTLS13:
  1043. return c.handleNewSessionTicket(msg)
  1044. case *keyUpdateMsg:
  1045. return c.handleKeyUpdate(msg)
  1046. default:
  1047. c.sendAlert(alertUnexpectedMessage)
  1048. return fmt.Errorf("tls: received unexpected handshake message of type %T", msg)
  1049. }
  1050. }
  1051. func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error {
  1052. cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  1053. if cipherSuite == nil {
  1054. return c.in.setErrorLocked(c.sendAlert(alertInternalError))
  1055. }
  1056. newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret)
  1057. c.in.setTrafficSecret(cipherSuite, newSecret)
  1058. if keyUpdate.updateRequested {
  1059. c.out.Lock()
  1060. defer c.out.Unlock()
  1061. msg := &keyUpdateMsg{}
  1062. _, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal())
  1063. if err != nil {
  1064. // Surface the error at the next write.
  1065. c.out.setErrorLocked(err)
  1066. return nil
  1067. }
  1068. newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret)
  1069. c.out.setTrafficSecret(cipherSuite, newSecret)
  1070. }
  1071. return nil
  1072. }
  1073. // Read can be made to time out and return a net.Error with Timeout() == true
  1074. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1075. func (c *Conn) Read(b []byte) (int, error) {
  1076. if err := c.Handshake(); err != nil {
  1077. return 0, err
  1078. }
  1079. if len(b) == 0 {
  1080. // Put this after Handshake, in case people were calling
  1081. // Read(nil) for the side effect of the Handshake.
  1082. return 0, nil
  1083. }
  1084. c.in.Lock()
  1085. defer c.in.Unlock()
  1086. for c.input.Len() == 0 {
  1087. if err := c.readRecord(); err != nil {
  1088. return 0, err
  1089. }
  1090. for c.hand.Len() > 0 {
  1091. if err := c.handlePostHandshakeMessage(); err != nil {
  1092. return 0, err
  1093. }
  1094. }
  1095. }
  1096. n, _ := c.input.Read(b)
  1097. // If a close-notify alert is waiting, read it so that we can return (n,
  1098. // EOF) instead of (n, nil), to signal to the HTTP response reading
  1099. // goroutine that the connection is now closed. This eliminates a race
  1100. // where the HTTP response reading goroutine would otherwise not observe
  1101. // the EOF until its next read, by which time a client goroutine might
  1102. // have already tried to reuse the HTTP connection for a new request.
  1103. // See https://golang.org/cl/76400046 and https://golang.org/issue/3514
  1104. if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 &&
  1105. recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
  1106. if err := c.readRecord(); err != nil {
  1107. return n, err // will be io.EOF on closeNotify
  1108. }
  1109. }
  1110. return n, nil
  1111. }
  1112. // Close closes the connection.
  1113. func (c *Conn) Close() error {
  1114. // Interlock with Conn.Write above.
  1115. var x int32
  1116. for {
  1117. x = atomic.LoadInt32(&c.activeCall)
  1118. if x&1 != 0 {
  1119. return errClosed
  1120. }
  1121. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1122. break
  1123. }
  1124. }
  1125. if x != 0 {
  1126. // io.Writer and io.Closer should not be used concurrently.
  1127. // If Close is called while a Write is currently in-flight,
  1128. // interpret that as a sign that this Close is really just
  1129. // being used to break the Write and/or clean up resources and
  1130. // avoid sending the alertCloseNotify, which may block
  1131. // waiting on handshakeMutex or the c.out mutex.
  1132. return c.conn.Close()
  1133. }
  1134. var alertErr error
  1135. if c.handshakeComplete() {
  1136. alertErr = c.closeNotify()
  1137. }
  1138. if err := c.conn.Close(); err != nil {
  1139. return err
  1140. }
  1141. return alertErr
  1142. }
  1143. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1144. // CloseWrite shuts down the writing side of the connection. It should only be
  1145. // called once the handshake has completed and does not call CloseWrite on the
  1146. // underlying connection. Most callers should just use Close.
  1147. func (c *Conn) CloseWrite() error {
  1148. if !c.handshakeComplete() {
  1149. return errEarlyCloseWrite
  1150. }
  1151. return c.closeNotify()
  1152. }
  1153. func (c *Conn) closeNotify() error {
  1154. c.out.Lock()
  1155. defer c.out.Unlock()
  1156. if !c.closeNotifySent {
  1157. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1158. c.closeNotifySent = true
  1159. }
  1160. return c.closeNotifyErr
  1161. }
  1162. // Handshake runs the client or server handshake
  1163. // protocol if it has not yet been run.
  1164. // Most uses of this package need not call Handshake
  1165. // explicitly: the first Read or Write will call it automatically.
  1166. func (c *Conn) Handshake() error {
  1167. c.handshakeMutex.Lock()
  1168. defer c.handshakeMutex.Unlock()
  1169. if err := c.handshakeErr; err != nil {
  1170. return err
  1171. }
  1172. if c.handshakeComplete() {
  1173. return nil
  1174. }
  1175. c.in.Lock()
  1176. defer c.in.Unlock()
  1177. if c.isClient {
  1178. c.handshakeErr = c.clientHandshake()
  1179. } else {
  1180. c.handshakeErr = c.serverHandshake()
  1181. }
  1182. if c.handshakeErr == nil {
  1183. c.handshakes++
  1184. } else {
  1185. // If an error occurred during the hadshake try to flush the
  1186. // alert that might be left in the buffer.
  1187. c.flush()
  1188. }
  1189. if c.handshakeErr == nil && !c.handshakeComplete() {
  1190. c.handshakeErr = errors.New("tls: internal error: handshake should have had a result")
  1191. }
  1192. return c.handshakeErr
  1193. }
  1194. // ConnectionState returns basic TLS details about the connection.
  1195. func (c *Conn) ConnectionState() ConnectionState {
  1196. c.handshakeMutex.Lock()
  1197. defer c.handshakeMutex.Unlock()
  1198. var state ConnectionState
  1199. state.HandshakeComplete = c.handshakeComplete()
  1200. state.ServerName = c.serverName
  1201. if state.HandshakeComplete {
  1202. state.Version = c.vers
  1203. state.NegotiatedProtocol = c.clientProtocol
  1204. state.DidResume = c.didResume
  1205. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1206. state.CipherSuite = c.cipherSuite
  1207. state.PeerCertificates = c.peerCertificates
  1208. state.VerifiedChains = c.verifiedChains
  1209. state.SignedCertificateTimestamps = c.scts
  1210. state.OCSPResponse = c.ocspResponse
  1211. if !c.didResume && c.vers != VersionTLS13 {
  1212. if c.clientFinishedIsFirst {
  1213. state.TLSUnique = c.clientFinished[:]
  1214. } else {
  1215. state.TLSUnique = c.serverFinished[:]
  1216. }
  1217. }
  1218. if c.config.Renegotiation != RenegotiateNever {
  1219. state.ekm = noExportedKeyingMaterial
  1220. } else {
  1221. state.ekm = c.ekm
  1222. }
  1223. }
  1224. return state
  1225. }
  1226. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1227. // any. (Only valid for client connections.)
  1228. func (c *Conn) OCSPResponse() []byte {
  1229. c.handshakeMutex.Lock()
  1230. defer c.handshakeMutex.Unlock()
  1231. return c.ocspResponse
  1232. }
  1233. // VerifyHostname checks that the peer certificate chain is valid for
  1234. // connecting to host. If so, it returns nil; if not, it returns an error
  1235. // describing the problem.
  1236. func (c *Conn) VerifyHostname(host string) error {
  1237. c.handshakeMutex.Lock()
  1238. defer c.handshakeMutex.Unlock()
  1239. if !c.isClient {
  1240. return errors.New("tls: VerifyHostname called on TLS server connection")
  1241. }
  1242. if !c.handshakeComplete() {
  1243. return errors.New("tls: handshake has not yet been performed")
  1244. }
  1245. if len(c.verifiedChains) == 0 {
  1246. return errors.New("tls: handshake did not verify certificate chain")
  1247. }
  1248. return c.peerCertificates[0].VerifyHostname(host)
  1249. }
  1250. func (c *Conn) handshakeComplete() bool {
  1251. return atomic.LoadUint32(&c.handshakeStatus) == 1
  1252. }