conn.go 54 KB

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