conn.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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. default:
  943. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  944. }
  945. // The handshake message unmarshalers
  946. // expect to be able to keep references to data,
  947. // so pass in a fresh copy that won't be overwritten.
  948. data = append([]byte(nil), data...)
  949. if !m.unmarshal(data) {
  950. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  951. }
  952. return m, nil
  953. }
  954. var (
  955. errClosed = errors.New("tls: use of closed connection")
  956. errShutdown = errors.New("tls: protocol is shutdown")
  957. )
  958. // Write writes data to the connection.
  959. func (c *Conn) Write(b []byte) (int, error) {
  960. // interlock with Close below
  961. for {
  962. x := atomic.LoadInt32(&c.activeCall)
  963. if x&1 != 0 {
  964. return 0, errClosed
  965. }
  966. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  967. defer atomic.AddInt32(&c.activeCall, -2)
  968. break
  969. }
  970. }
  971. if err := c.Handshake(); err != nil {
  972. return 0, err
  973. }
  974. c.out.Lock()
  975. defer c.out.Unlock()
  976. if err := c.out.err; err != nil {
  977. return 0, err
  978. }
  979. if !c.handshakeComplete() {
  980. return 0, alertInternalError
  981. }
  982. if c.closeNotifySent {
  983. return 0, errShutdown
  984. }
  985. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  986. // attack when using block mode ciphers due to predictable IVs.
  987. // This can be prevented by splitting each Application Data
  988. // record into two records, effectively randomizing the IV.
  989. //
  990. // https://www.openssl.org/~bodo/tls-cbc.txt
  991. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  992. // https://www.imperialviolet.org/2012/01/15/beastfollowup.html
  993. var m int
  994. if len(b) > 1 && c.vers <= VersionTLS10 {
  995. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  996. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  997. if err != nil {
  998. return n, c.out.setErrorLocked(err)
  999. }
  1000. m, b = 1, b[1:]
  1001. }
  1002. }
  1003. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1004. return n + m, c.out.setErrorLocked(err)
  1005. }
  1006. // handleRenegotiation processes a HelloRequest handshake message.
  1007. func (c *Conn) handleRenegotiation() error {
  1008. if c.vers == VersionTLS13 {
  1009. return errors.New("tls: internal error: unexpected renegotiation")
  1010. }
  1011. msg, err := c.readHandshake()
  1012. if err != nil {
  1013. return err
  1014. }
  1015. helloReq, ok := msg.(*helloRequestMsg)
  1016. if !ok {
  1017. c.sendAlert(alertUnexpectedMessage)
  1018. return unexpectedMessageError(helloReq, msg)
  1019. }
  1020. if !c.isClient {
  1021. return c.sendAlert(alertNoRenegotiation)
  1022. }
  1023. switch c.config.Renegotiation {
  1024. case RenegotiateNever:
  1025. return c.sendAlert(alertNoRenegotiation)
  1026. case RenegotiateOnceAsClient:
  1027. if c.handshakes > 1 {
  1028. return c.sendAlert(alertNoRenegotiation)
  1029. }
  1030. case RenegotiateFreelyAsClient:
  1031. // Ok.
  1032. default:
  1033. c.sendAlert(alertInternalError)
  1034. return errors.New("tls: unknown Renegotiation value")
  1035. }
  1036. c.handshakeMutex.Lock()
  1037. defer c.handshakeMutex.Unlock()
  1038. atomic.StoreUint32(&c.handshakeStatus, 0)
  1039. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1040. c.handshakes++
  1041. }
  1042. return c.handshakeErr
  1043. }
  1044. // handlePostHandshakeMessage processes a handshake message arrived after the
  1045. // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.
  1046. func (c *Conn) handlePostHandshakeMessage() error {
  1047. if c.vers != VersionTLS13 {
  1048. return c.handleRenegotiation()
  1049. }
  1050. msg, err := c.readHandshake()
  1051. if err != nil {
  1052. return err
  1053. }
  1054. c.retryCount++
  1055. if c.retryCount > maxUselessRecords {
  1056. c.sendAlert(alertUnexpectedMessage)
  1057. return c.in.setErrorLocked(errors.New("tls: too many non-advancing records"))
  1058. }
  1059. switch msg := msg.(type) {
  1060. case *newSessionTicketMsgTLS13:
  1061. return c.handleNewSessionTicket(msg)
  1062. case *keyUpdateMsg:
  1063. return c.handleKeyUpdate(msg)
  1064. default:
  1065. c.sendAlert(alertUnexpectedMessage)
  1066. return fmt.Errorf("tls: received unexpected handshake message of type %T", msg)
  1067. }
  1068. }
  1069. func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error {
  1070. cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  1071. if cipherSuite == nil {
  1072. return c.in.setErrorLocked(c.sendAlert(alertInternalError))
  1073. }
  1074. newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret)
  1075. c.in.setTrafficSecret(cipherSuite, newSecret)
  1076. if keyUpdate.updateRequested {
  1077. c.out.Lock()
  1078. defer c.out.Unlock()
  1079. msg := &keyUpdateMsg{}
  1080. _, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal())
  1081. if err != nil {
  1082. // Surface the error at the next write.
  1083. c.out.setErrorLocked(err)
  1084. return nil
  1085. }
  1086. newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret)
  1087. c.out.setTrafficSecret(cipherSuite, newSecret)
  1088. }
  1089. return nil
  1090. }
  1091. // Read can be made to time out and return a net.Error with Timeout() == true
  1092. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1093. func (c *Conn) Read(b []byte) (int, error) {
  1094. if err := c.Handshake(); err != nil {
  1095. return 0, err
  1096. }
  1097. if len(b) == 0 {
  1098. // Put this after Handshake, in case people were calling
  1099. // Read(nil) for the side effect of the Handshake.
  1100. return 0, nil
  1101. }
  1102. c.in.Lock()
  1103. defer c.in.Unlock()
  1104. for c.input.Len() == 0 {
  1105. if err := c.readRecord(); err != nil {
  1106. return 0, err
  1107. }
  1108. for c.hand.Len() > 0 {
  1109. if err := c.handlePostHandshakeMessage(); err != nil {
  1110. return 0, err
  1111. }
  1112. }
  1113. }
  1114. n, _ := c.input.Read(b)
  1115. // If a close-notify alert is waiting, read it so that we can return (n,
  1116. // EOF) instead of (n, nil), to signal to the HTTP response reading
  1117. // goroutine that the connection is now closed. This eliminates a race
  1118. // where the HTTP response reading goroutine would otherwise not observe
  1119. // the EOF until its next read, by which time a client goroutine might
  1120. // have already tried to reuse the HTTP connection for a new request.
  1121. // See https://golang.org/cl/76400046 and https://golang.org/issue/3514
  1122. if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 &&
  1123. recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
  1124. if err := c.readRecord(); err != nil {
  1125. return n, err // will be io.EOF on closeNotify
  1126. }
  1127. }
  1128. return n, nil
  1129. }
  1130. // Close closes the connection.
  1131. func (c *Conn) Close() error {
  1132. // Interlock with Conn.Write above.
  1133. var x int32
  1134. for {
  1135. x = atomic.LoadInt32(&c.activeCall)
  1136. if x&1 != 0 {
  1137. return errClosed
  1138. }
  1139. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1140. break
  1141. }
  1142. }
  1143. if x != 0 {
  1144. // io.Writer and io.Closer should not be used concurrently.
  1145. // If Close is called while a Write is currently in-flight,
  1146. // interpret that as a sign that this Close is really just
  1147. // being used to break the Write and/or clean up resources and
  1148. // avoid sending the alertCloseNotify, which may block
  1149. // waiting on handshakeMutex or the c.out mutex.
  1150. return c.conn.Close()
  1151. }
  1152. var alertErr error
  1153. if c.handshakeComplete() {
  1154. alertErr = c.closeNotify()
  1155. }
  1156. if err := c.conn.Close(); err != nil {
  1157. return err
  1158. }
  1159. return alertErr
  1160. }
  1161. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1162. // CloseWrite shuts down the writing side of the connection. It should only be
  1163. // called once the handshake has completed and does not call CloseWrite on the
  1164. // underlying connection. Most callers should just use Close.
  1165. func (c *Conn) CloseWrite() error {
  1166. if !c.handshakeComplete() {
  1167. return errEarlyCloseWrite
  1168. }
  1169. return c.closeNotify()
  1170. }
  1171. func (c *Conn) closeNotify() error {
  1172. c.out.Lock()
  1173. defer c.out.Unlock()
  1174. if !c.closeNotifySent {
  1175. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1176. c.closeNotifySent = true
  1177. }
  1178. return c.closeNotifyErr
  1179. }
  1180. // Handshake runs the client or server handshake
  1181. // protocol if it has not yet been run.
  1182. // Most uses of this package need not call Handshake
  1183. // explicitly: the first Read or Write will call it automatically.
  1184. func (c *Conn) Handshake() error {
  1185. c.handshakeMutex.Lock()
  1186. defer c.handshakeMutex.Unlock()
  1187. if err := c.handshakeErr; err != nil {
  1188. return err
  1189. }
  1190. if c.handshakeComplete() {
  1191. return nil
  1192. }
  1193. c.in.Lock()
  1194. defer c.in.Unlock()
  1195. if c.isClient {
  1196. c.handshakeErr = c.clientHandshake()
  1197. } else {
  1198. c.handshakeErr = c.serverHandshake()
  1199. }
  1200. if c.handshakeErr == nil {
  1201. c.handshakes++
  1202. } else {
  1203. // If an error occurred during the hadshake try to flush the
  1204. // alert that might be left in the buffer.
  1205. c.flush()
  1206. }
  1207. if c.handshakeErr == nil && !c.handshakeComplete() {
  1208. c.handshakeErr = errors.New("tls: internal error: handshake should have had a result")
  1209. }
  1210. return c.handshakeErr
  1211. }
  1212. // ConnectionState returns basic TLS details about the connection.
  1213. func (c *Conn) ConnectionState() ConnectionState {
  1214. c.handshakeMutex.Lock()
  1215. defer c.handshakeMutex.Unlock()
  1216. var state ConnectionState
  1217. state.HandshakeComplete = c.handshakeComplete()
  1218. state.ServerName = c.serverName
  1219. if state.HandshakeComplete {
  1220. state.Version = c.vers
  1221. state.NegotiatedProtocol = c.clientProtocol
  1222. state.DidResume = c.didResume
  1223. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1224. state.CipherSuite = c.cipherSuite
  1225. state.PeerCertificates = c.peerCertificates
  1226. state.VerifiedChains = c.verifiedChains
  1227. state.SignedCertificateTimestamps = c.scts
  1228. state.OCSPResponse = c.ocspResponse
  1229. if !c.didResume && c.vers != VersionTLS13 {
  1230. if c.clientFinishedIsFirst {
  1231. state.TLSUnique = c.clientFinished[:]
  1232. } else {
  1233. state.TLSUnique = c.serverFinished[:]
  1234. }
  1235. }
  1236. if c.config.Renegotiation != RenegotiateNever {
  1237. state.ekm = noExportedKeyingMaterial
  1238. } else {
  1239. state.ekm = c.ekm
  1240. }
  1241. }
  1242. return state
  1243. }
  1244. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1245. // any. (Only valid for client connections.)
  1246. func (c *Conn) OCSPResponse() []byte {
  1247. c.handshakeMutex.Lock()
  1248. defer c.handshakeMutex.Unlock()
  1249. return c.ocspResponse
  1250. }
  1251. // VerifyHostname checks that the peer certificate chain is valid for
  1252. // connecting to host. If so, it returns nil; if not, it returns an error
  1253. // describing the problem.
  1254. func (c *Conn) VerifyHostname(host string) error {
  1255. c.handshakeMutex.Lock()
  1256. defer c.handshakeMutex.Unlock()
  1257. if !c.isClient {
  1258. return errors.New("tls: VerifyHostname called on TLS server connection")
  1259. }
  1260. if !c.handshakeComplete() {
  1261. return errors.New("tls: handshake has not yet been performed")
  1262. }
  1263. if len(c.verifiedChains) == 0 {
  1264. return errors.New("tls: handshake did not verify certificate chain")
  1265. }
  1266. return c.peerCertificates[0].VerifyHostname(host)
  1267. }
  1268. func (c *Conn) handshakeComplete() bool {
  1269. return atomic.LoadUint32(&c.handshakeStatus) == 1
  1270. }