conn.go 43 KB

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