conn.go 52 KB

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