conn.go 49 KB

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