conn.go 53 KB

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