conn.go 52 KB

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