conn.go 52 KB

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