conn.go 48 KB

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