conn.go 52 KB

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