conn.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  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 qtls
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "encoding/binary"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "sync"
  17. "sync/atomic"
  18. "time"
  19. )
  20. // A Conn represents a secured connection.
  21. // It implements the net.Conn interface.
  22. type Conn struct {
  23. // constant
  24. conn net.Conn
  25. isClient bool
  26. phase handshakeStatus // protected by in.Mutex
  27. // handshakeConfirmed is an atomic bool for phase == handshakeConfirmed
  28. handshakeConfirmed int32
  29. // confirmMutex is held by any read operation before handshakeConfirmed
  30. confirmMutex sync.Mutex
  31. // constant after handshake; protected by handshakeMutex
  32. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  33. handshakeErr error // error resulting from handshake
  34. connID []byte // Random connection id
  35. clientHello []byte // ClientHello packet contents
  36. vers uint16 // TLS version
  37. haveVers bool // version has been negotiated
  38. config *Config // configuration passed to constructor
  39. // handshakeComplete is true if the connection reached application data
  40. // and it's equivalent to phase > handshakeRunning
  41. handshakeComplete bool
  42. // handshakes counts the number of handshakes performed on the
  43. // connection so far. If renegotiation is disabled then this is either
  44. // zero or one.
  45. handshakes int
  46. didResume bool // whether this connection was a session resumption
  47. cipherSuite uint16
  48. ocspResponse []byte // stapled OCSP response
  49. scts [][]byte // Signed certificate timestamps from server
  50. peerCertificates []*x509.Certificate
  51. // verifiedChains contains the certificate chains that we built, as
  52. // opposed to the ones presented by the server.
  53. verifiedChains [][]*x509.Certificate
  54. // verifiedDc is set by a client who negotiates the use of a valid delegated
  55. // credential.
  56. verifiedDc *delegatedCredential
  57. // serverName contains the server name indicated by the client, if any.
  58. serverName string
  59. // secureRenegotiation is true if the server echoed the secure
  60. // renegotiation extension. (This is meaningless as a server because
  61. // renegotiation is not supported in that case.)
  62. secureRenegotiation bool
  63. // indicates wether extended MasterSecret extension is used (see RFC7627)
  64. useEMS bool
  65. // clientFinishedIsFirst is true if the client sent the first Finished
  66. // message during the most recent handshake. This is recorded because
  67. // the first transmitted Finished message is the tls-unique
  68. // channel-binding value.
  69. clientFinishedIsFirst bool
  70. // closeNotifyErr is any error from sending the alertCloseNotify record.
  71. closeNotifyErr error
  72. // closeNotifySent is true if the Conn attempted to send an
  73. // alertCloseNotify record.
  74. closeNotifySent bool
  75. // clientFinished and serverFinished contain the Finished message sent
  76. // by the client or server in the most recent handshake. This is
  77. // retained to support the renegotiation extension and tls-unique
  78. // channel-binding.
  79. clientFinished [12]byte
  80. serverFinished [12]byte
  81. clientProtocol string
  82. clientProtocolFallback bool
  83. // ticketMaxEarlyData is the maximum bytes of 0-RTT application data
  84. // that the client is allowed to send on the ticket it used.
  85. ticketMaxEarlyData int64
  86. // input/output
  87. in, out halfConn // in.Mutex < out.Mutex
  88. rawInput *block // raw input, right off the wire
  89. input *block // application data waiting to be read
  90. hand bytes.Buffer // handshake data waiting to be read
  91. buffering bool // whether records are buffered in sendBuf
  92. sendBuf []byte // a buffer of records waiting to be sent
  93. // bytesSent counts the bytes of application data sent.
  94. // packetsSent counts packets.
  95. bytesSent int64
  96. packetsSent int64
  97. // warnCount counts the number of consecutive warning alerts received
  98. // by Conn.readRecord. Protected by in.Mutex.
  99. warnCount int
  100. // activeCall is an atomic int32; the low bit is whether Close has
  101. // been called. the rest of the bits are the number of goroutines
  102. // in Conn.Write.
  103. activeCall int32
  104. // TLS 1.3 needs the server state until it reaches the Client Finished
  105. hs *serverHandshakeState
  106. // earlyDataBytes is the number of bytes of early data received so
  107. // far. Tracked to enforce max_early_data_size.
  108. // We don't keep track of rejected 0-RTT data since there's no need
  109. // to ever buffer it. in.Mutex.
  110. earlyDataBytes int64
  111. // binder is the value of the PSK binder that was validated to
  112. // accept the 0-RTT data. Exposed as ConnectionState.Unique0RTTToken.
  113. binder []byte
  114. tmp [16]byte
  115. }
  116. type handshakeStatus int
  117. const (
  118. handshakeRunning handshakeStatus = iota
  119. discardingEarlyData
  120. readingEarlyData
  121. waitingClientFinished
  122. readingClientFinished
  123. handshakeConfirmed
  124. )
  125. // Access to net.Conn methods.
  126. // Cannot just embed net.Conn because that would
  127. // export the struct field too.
  128. // LocalAddr returns the local network address.
  129. func (c *Conn) LocalAddr() net.Addr {
  130. return c.conn.LocalAddr()
  131. }
  132. // RemoteAddr returns the remote network address.
  133. func (c *Conn) RemoteAddr() net.Addr {
  134. return c.conn.RemoteAddr()
  135. }
  136. // SetDeadline sets the read and write deadlines associated with the connection.
  137. // A zero value for t means Read and Write will not time out.
  138. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  139. func (c *Conn) SetDeadline(t time.Time) error {
  140. return c.conn.SetDeadline(t)
  141. }
  142. // SetReadDeadline sets the read deadline on the underlying connection.
  143. // A zero value for t means Read will not time out.
  144. func (c *Conn) SetReadDeadline(t time.Time) error {
  145. return c.conn.SetReadDeadline(t)
  146. }
  147. // SetWriteDeadline sets the write deadline on the underlying connection.
  148. // A zero value for t means Write will not time out.
  149. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  150. func (c *Conn) SetWriteDeadline(t time.Time) error {
  151. return c.conn.SetWriteDeadline(t)
  152. }
  153. // A halfConn represents one direction of the record layer
  154. // connection, either sending or receiving.
  155. type halfConn struct {
  156. sync.Mutex
  157. err error // first permanent error
  158. version uint16 // protocol version
  159. cipher interface{} // cipher algorithm
  160. mac macFunction
  161. seq [8]byte // 64-bit sequence number
  162. bfree *block // list of free blocks
  163. additionalData [13]byte // to avoid allocs; interface method args escape
  164. nextCipher interface{} // next encryption state
  165. nextMac macFunction // next MAC algorithm
  166. // used to save allocating a new buffer for each MAC.
  167. inDigestBuf, outDigestBuf []byte
  168. setKeyCallback func(suite *CipherSuite, trafficSecret []byte)
  169. traceErr func(error)
  170. }
  171. func (hc *halfConn) setErrorLocked(err error) error {
  172. hc.err = err
  173. if hc.traceErr != nil {
  174. hc.traceErr(err)
  175. }
  176. return err
  177. }
  178. // prepareCipherSpec sets the encryption and MAC states
  179. // that a subsequent changeCipherSpec will use.
  180. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  181. hc.version = version
  182. hc.nextCipher = cipher
  183. hc.nextMac = mac
  184. }
  185. // changeCipherSpec changes the encryption and MAC states
  186. // to the ones previously passed to prepareCipherSpec.
  187. func (hc *halfConn) changeCipherSpec() error {
  188. if hc.nextCipher == nil {
  189. return alertInternalError
  190. }
  191. hc.cipher = hc.nextCipher
  192. hc.mac = hc.nextMac
  193. hc.nextCipher = nil
  194. hc.nextMac = nil
  195. for i := range hc.seq {
  196. hc.seq[i] = 0
  197. }
  198. return nil
  199. }
  200. func (hc *halfConn) exportKey(suite *cipherSuite, trafficSecret []byte) {
  201. if hc.setKeyCallback != nil {
  202. hc.setKeyCallback(&CipherSuite{*suite}, trafficSecret)
  203. }
  204. }
  205. func (hc *halfConn) setKey(version uint16, suite *cipherSuite, trafficSecret []byte) {
  206. if hc.setKeyCallback != nil {
  207. return
  208. }
  209. hc.version = version
  210. hash := hashForSuite(suite)
  211. key := hkdfExpandLabel(hash, trafficSecret, nil, "key", suite.keyLen)
  212. iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", suite.ivLen)
  213. hc.cipher = suite.aead(key, iv)
  214. for i := range hc.seq {
  215. hc.seq[i] = 0
  216. }
  217. }
  218. // incSeq increments the sequence number.
  219. func (hc *halfConn) incSeq() {
  220. for i := 7; i >= 0; i-- {
  221. hc.seq[i]++
  222. if hc.seq[i] != 0 {
  223. return
  224. }
  225. }
  226. // Not allowed to let sequence number wrap.
  227. // Instead, must renegotiate before it does.
  228. // Not likely enough to bother.
  229. panic("TLS: sequence number wraparound")
  230. }
  231. // extractPadding returns, in constant time, the length of the padding to remove
  232. // from the end of payload. It also returns a byte which is equal to 255 if the
  233. // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  234. func extractPadding(payload []byte) (toRemove int, good byte) {
  235. if len(payload) < 1 {
  236. return 0, 0
  237. }
  238. paddingLen := payload[len(payload)-1]
  239. t := uint(len(payload)-1) - uint(paddingLen)
  240. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  241. good = byte(int32(^t) >> 31)
  242. // The maximum possible padding length plus the actual length field
  243. toCheck := 256
  244. // The length of the padded data is public, so we can use an if here
  245. if toCheck > len(payload) {
  246. toCheck = len(payload)
  247. }
  248. for i := 0; i < toCheck; i++ {
  249. t := uint(paddingLen) - uint(i)
  250. // if i <= paddingLen then the MSB of t is zero
  251. mask := byte(int32(^t) >> 31)
  252. b := payload[len(payload)-1-i]
  253. good &^= mask&paddingLen ^ mask&b
  254. }
  255. // We AND together the bits of good and replicate the result across
  256. // all the bits.
  257. good &= good << 4
  258. good &= good << 2
  259. good &= good << 1
  260. good = uint8(int8(good) >> 7)
  261. toRemove = int(paddingLen) + 1
  262. return
  263. }
  264. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  265. // protocol version is SSLv3. In this version, the contents of the padding
  266. // are random and cannot be checked.
  267. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  268. if len(payload) < 1 {
  269. return 0, 0
  270. }
  271. paddingLen := int(payload[len(payload)-1]) + 1
  272. if paddingLen > len(payload) {
  273. return 0, 0
  274. }
  275. return paddingLen, 255
  276. }
  277. func roundUp(a, b int) int {
  278. return a + (b-a%b)%b
  279. }
  280. // cbcMode is an interface for block ciphers using cipher block chaining.
  281. type cbcMode interface {
  282. cipher.BlockMode
  283. SetIV([]byte)
  284. }
  285. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  286. // success boolean, the number of bytes to skip from the start of the record in
  287. // order to get the application payload, and an optional alert value.
  288. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  289. // pull out payload
  290. payload := b.data[recordHeaderLen:]
  291. macSize := 0
  292. if hc.mac != nil {
  293. macSize = hc.mac.Size()
  294. }
  295. paddingGood := byte(255)
  296. paddingLen := 0
  297. explicitIVLen := 0
  298. // decrypt
  299. if hc.cipher != nil {
  300. switch c := hc.cipher.(type) {
  301. case cipher.Stream:
  302. c.XORKeyStream(payload, payload)
  303. case aead:
  304. explicitIVLen = c.explicitNonceLen()
  305. if len(payload) < explicitIVLen {
  306. return false, 0, alertBadRecordMAC
  307. }
  308. nonce := payload[:explicitIVLen]
  309. payload = payload[explicitIVLen:]
  310. if len(nonce) == 0 {
  311. nonce = hc.seq[:]
  312. }
  313. var additionalData []byte
  314. if hc.version < VersionTLS13 {
  315. copy(hc.additionalData[:], hc.seq[:])
  316. copy(hc.additionalData[8:], b.data[:3])
  317. n := len(payload) - c.Overhead()
  318. hc.additionalData[11] = byte(n >> 8)
  319. hc.additionalData[12] = byte(n)
  320. additionalData = hc.additionalData[:]
  321. } else {
  322. if len(payload) > int((1<<14)+256) {
  323. return false, 0, alertRecordOverflow
  324. }
  325. // Check AD header, see 5.2 of RFC8446
  326. additionalData = make([]byte, 5)
  327. additionalData[0] = byte(recordTypeApplicationData)
  328. binary.BigEndian.PutUint16(additionalData[1:], VersionTLS12)
  329. binary.BigEndian.PutUint16(additionalData[3:], uint16(len(payload)))
  330. }
  331. var err error
  332. payload, err = c.Open(payload[:0], nonce, payload, additionalData)
  333. if err != nil {
  334. return false, 0, alertBadRecordMAC
  335. }
  336. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  337. case cbcMode:
  338. blockSize := c.BlockSize()
  339. if hc.version >= VersionTLS11 {
  340. explicitIVLen = blockSize
  341. }
  342. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  343. return false, 0, alertBadRecordMAC
  344. }
  345. if explicitIVLen > 0 {
  346. c.SetIV(payload[:explicitIVLen])
  347. payload = payload[explicitIVLen:]
  348. }
  349. c.CryptBlocks(payload, payload)
  350. if hc.version == VersionSSL30 {
  351. paddingLen, paddingGood = extractPaddingSSL30(payload)
  352. } else {
  353. paddingLen, paddingGood = extractPadding(payload)
  354. // To protect against CBC padding oracles like Lucky13, the data
  355. // past paddingLen (which is secret) is passed to the MAC
  356. // function as extra data, to be fed into the HMAC after
  357. // computing the digest. This makes the MAC constant time as
  358. // long as the digest computation is constant time and does not
  359. // affect the subsequent write.
  360. }
  361. default:
  362. panic("unknown cipher type")
  363. }
  364. }
  365. // check, strip mac
  366. if hc.mac != nil {
  367. if len(payload) < macSize {
  368. return false, 0, alertBadRecordMAC
  369. }
  370. // strip mac off payload, b.data
  371. n := len(payload) - macSize - paddingLen
  372. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  373. b.data[3] = byte(n >> 8)
  374. b.data[4] = byte(n)
  375. remoteMAC := payload[n : n+macSize]
  376. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
  377. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  378. return false, 0, alertBadRecordMAC
  379. }
  380. hc.inDigestBuf = localMAC
  381. b.resize(recordHeaderLen + explicitIVLen + n)
  382. }
  383. hc.incSeq()
  384. return true, recordHeaderLen + explicitIVLen, 0
  385. }
  386. // padToBlockSize calculates the needed padding block, if any, for a payload.
  387. // On exit, prefix aliases payload and extends to the end of the last full
  388. // block of payload. finalBlock is a fresh slice which contains the contents of
  389. // any suffix of payload as well as the needed padding to make finalBlock a
  390. // full block.
  391. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  392. overrun := len(payload) % blockSize
  393. paddingLen := blockSize - overrun
  394. prefix = payload[:len(payload)-overrun]
  395. finalBlock = make([]byte, blockSize)
  396. copy(finalBlock, payload[len(payload)-overrun:])
  397. for i := overrun; i < blockSize; i++ {
  398. finalBlock[i] = byte(paddingLen - 1)
  399. }
  400. return
  401. }
  402. // encrypt encrypts and macs the data in b.
  403. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  404. // mac
  405. if hc.mac != nil {
  406. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
  407. n := len(b.data)
  408. b.resize(n + len(mac))
  409. copy(b.data[n:], mac)
  410. hc.outDigestBuf = mac
  411. }
  412. payload := b.data[recordHeaderLen:]
  413. // encrypt
  414. if hc.cipher != nil {
  415. switch c := hc.cipher.(type) {
  416. case cipher.Stream:
  417. c.XORKeyStream(payload, payload)
  418. case aead:
  419. // explicitIVLen is always 0 for TLS1.3
  420. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  421. payloadOffset := recordHeaderLen + explicitIVLen
  422. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  423. if len(nonce) == 0 {
  424. nonce = hc.seq[:]
  425. }
  426. var additionalData []byte
  427. if hc.version < VersionTLS13 {
  428. // make room in a buffer for payload + MAC
  429. b.resize(len(b.data) + c.Overhead())
  430. payload = b.data[payloadOffset : payloadOffset+payloadLen]
  431. copy(hc.additionalData[:], hc.seq[:])
  432. copy(hc.additionalData[8:], b.data[:3])
  433. binary.BigEndian.PutUint16(hc.additionalData[11:], uint16(payloadLen))
  434. additionalData = hc.additionalData[:]
  435. } else {
  436. // make room in a buffer for TLSCiphertext.encrypted_record:
  437. // payload + MAC + extra data if needed
  438. b.resize(len(b.data) + c.Overhead() + 1)
  439. payload = b.data[payloadOffset : payloadOffset+payloadLen+1]
  440. // 1 byte of content type is appended to payload and encrypted
  441. payload[len(payload)-1] = b.data[0]
  442. // opaque_type
  443. b.data[0] = byte(recordTypeApplicationData)
  444. // Add AD header, see 5.2 of RFC8446
  445. additionalData = make([]byte, 5)
  446. additionalData[0] = b.data[0]
  447. binary.BigEndian.PutUint16(additionalData[1:], VersionTLS12)
  448. binary.BigEndian.PutUint16(additionalData[3:], uint16(len(payload)+c.Overhead()))
  449. }
  450. c.Seal(payload[:0], nonce, payload, additionalData)
  451. case cbcMode:
  452. blockSize := c.BlockSize()
  453. if explicitIVLen > 0 {
  454. c.SetIV(payload[:explicitIVLen])
  455. payload = payload[explicitIVLen:]
  456. }
  457. prefix, finalBlock := padToBlockSize(payload, blockSize)
  458. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  459. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  460. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  461. default:
  462. panic("unknown cipher type")
  463. }
  464. }
  465. // update length to include MAC and any block padding needed.
  466. n := len(b.data) - recordHeaderLen
  467. b.data[3] = byte(n >> 8)
  468. b.data[4] = byte(n)
  469. hc.incSeq()
  470. return true, 0
  471. }
  472. // A block is a simple data buffer.
  473. type block struct {
  474. data []byte
  475. off int // index for Read
  476. link *block
  477. }
  478. // resize resizes block to be n bytes, growing if necessary.
  479. func (b *block) resize(n int) {
  480. if n > cap(b.data) {
  481. b.reserve(n)
  482. }
  483. b.data = b.data[0:n]
  484. }
  485. // reserve makes sure that block contains a capacity of at least n bytes.
  486. func (b *block) reserve(n int) {
  487. if cap(b.data) >= n {
  488. return
  489. }
  490. m := cap(b.data)
  491. if m == 0 {
  492. m = 1024
  493. }
  494. for m < n {
  495. m *= 2
  496. }
  497. data := make([]byte, len(b.data), m)
  498. copy(data, b.data)
  499. b.data = data
  500. }
  501. // readFromUntil reads from r into b until b contains at least n bytes
  502. // or else returns an error.
  503. func (b *block) readFromUntil(r io.Reader, n int) error {
  504. // quick case
  505. if len(b.data) >= n {
  506. return nil
  507. }
  508. // read until have enough.
  509. b.reserve(n)
  510. for {
  511. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  512. b.data = b.data[0 : len(b.data)+m]
  513. if len(b.data) >= n {
  514. // TODO(bradfitz,agl): slightly suspicious
  515. // that we're throwing away r.Read's err here.
  516. break
  517. }
  518. if err != nil {
  519. return err
  520. }
  521. }
  522. return nil
  523. }
  524. func (b *block) Read(p []byte) (n int, err error) {
  525. n = copy(p, b.data[b.off:])
  526. b.off += n
  527. if b.off >= len(b.data) {
  528. err = io.EOF
  529. }
  530. return
  531. }
  532. // newBlock allocates a new block, from hc's free list if possible.
  533. func (hc *halfConn) newBlock() *block {
  534. b := hc.bfree
  535. if b == nil {
  536. return new(block)
  537. }
  538. hc.bfree = b.link
  539. b.link = nil
  540. b.resize(0)
  541. return b
  542. }
  543. // freeBlock returns a block to hc's free list.
  544. // The protocol is such that each side only has a block or two on
  545. // its free list at a time, so there's no need to worry about
  546. // trimming the list, etc.
  547. func (hc *halfConn) freeBlock(b *block) {
  548. b.link = hc.bfree
  549. hc.bfree = b
  550. }
  551. // splitBlock splits a block after the first n bytes,
  552. // returning a block with those n bytes and a
  553. // block with the remainder. the latter may be nil.
  554. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  555. if len(b.data) <= n {
  556. return b, nil
  557. }
  558. bb := hc.newBlock()
  559. bb.resize(len(b.data) - n)
  560. copy(bb.data, b.data[n:])
  561. b.data = b.data[0:n]
  562. return b, bb
  563. }
  564. // RecordHeaderError results when a TLS record header is invalid.
  565. type RecordHeaderError struct {
  566. // Msg contains a human readable string that describes the error.
  567. Msg string
  568. // RecordHeader contains the five bytes of TLS record header that
  569. // triggered the error.
  570. RecordHeader [5]byte
  571. }
  572. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  573. func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
  574. err.Msg = msg
  575. copy(err.RecordHeader[:], c.rawInput.data)
  576. return err
  577. }
  578. // readRecord reads the next TLS record from the connection
  579. // and updates the record layer state.
  580. // c.in.Mutex <= L; c.input == nil.
  581. // c.input can still be nil after a call, retry if so.
  582. func (c *Conn) readRecord(want recordType) error {
  583. // Caller must be in sync with connection:
  584. // handshake data if handshake not yet completed,
  585. // else application data.
  586. switch want {
  587. default:
  588. c.sendAlert(alertInternalError)
  589. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  590. case recordTypeHandshake, recordTypeChangeCipherSpec:
  591. if c.phase != handshakeRunning && c.phase != readingClientFinished {
  592. c.sendAlert(alertInternalError)
  593. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
  594. }
  595. case recordTypeApplicationData:
  596. if c.phase == handshakeRunning || c.phase == readingClientFinished {
  597. c.sendAlert(alertInternalError)
  598. return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
  599. }
  600. }
  601. Again:
  602. if c.rawInput == nil {
  603. c.rawInput = c.in.newBlock()
  604. }
  605. b := c.rawInput
  606. // Read header, payload.
  607. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  608. // RFC suggests that EOF without an alertCloseNotify is
  609. // an error, but popular web sites seem to do this,
  610. // so we can't make it an error.
  611. // if err == io.EOF {
  612. // err = io.ErrUnexpectedEOF
  613. // }
  614. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  615. c.in.setErrorLocked(err)
  616. }
  617. return err
  618. }
  619. typ := recordType(b.data[0])
  620. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  621. // start with a uint16 length where the MSB is set and the first record
  622. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  623. // an SSLv2 client.
  624. if want == recordTypeHandshake && typ == 0x80 {
  625. c.sendAlert(alertProtocolVersion)
  626. return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
  627. }
  628. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  629. n := int(b.data[3])<<8 | int(b.data[4])
  630. if n > maxCiphertext {
  631. c.sendAlert(alertRecordOverflow)
  632. msg := fmt.Sprintf("oversized record received with length %d", n)
  633. return c.in.setErrorLocked(c.newRecordHeaderError(msg))
  634. }
  635. if !c.haveVers {
  636. // First message, be extra suspicious: this might not be a TLS
  637. // client. Bail out before reading a full 'body', if possible.
  638. // The current max version is 3.3 so if the version is >= 16.0,
  639. // it's probably not real.
  640. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  641. c.sendAlert(alertUnexpectedMessage)
  642. return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
  643. }
  644. }
  645. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  646. if err == io.EOF {
  647. err = io.ErrUnexpectedEOF
  648. }
  649. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  650. c.in.setErrorLocked(err)
  651. }
  652. return err
  653. }
  654. // Process message.
  655. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  656. // TLS 1.3 middlebox compatibility: skip over unencrypted CCS.
  657. if c.vers >= VersionTLS13 && typ == recordTypeChangeCipherSpec && c.phase != handshakeConfirmed {
  658. if len(b.data) != 6 || b.data[5] != 1 {
  659. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  660. }
  661. c.in.freeBlock(b)
  662. return c.in.err
  663. }
  664. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  665. ok, off, alertValue := c.in.decrypt(b)
  666. switch {
  667. case !ok && c.phase == discardingEarlyData:
  668. // If the client said that it's sending early data and we did not
  669. // accept it, we are expected to fail decryption.
  670. c.in.freeBlock(b)
  671. return nil
  672. case ok && c.phase == discardingEarlyData:
  673. c.phase = waitingClientFinished
  674. case !ok:
  675. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  676. c.in.freeBlock(b)
  677. err := c.sendAlert(alertValue)
  678. // If decryption failed because the message is an unencrypted
  679. // alert, return a more meaningful error message
  680. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  681. err = peekedAlert
  682. }
  683. return c.in.setErrorLocked(err)
  684. }
  685. b.off = off
  686. data := b.data[b.off:]
  687. if (c.vers < VersionTLS13 && len(data) > maxPlaintext) || len(data) > maxPlaintext+1 {
  688. c.in.freeBlock(b)
  689. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  690. }
  691. // After checking the plaintext length, remove 1.3 padding and
  692. // extract the real content type.
  693. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  694. if c.vers >= VersionTLS13 {
  695. i := len(data) - 1
  696. for i >= 0 {
  697. if data[i] != 0 {
  698. break
  699. }
  700. i--
  701. }
  702. if i < 0 {
  703. c.in.freeBlock(b)
  704. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  705. }
  706. typ = recordType(data[i])
  707. data = data[:i]
  708. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  709. }
  710. if typ != recordTypeAlert && len(data) > 0 {
  711. // this is a valid non-alert message: reset the count of alerts
  712. c.warnCount = 0
  713. }
  714. switch typ {
  715. default:
  716. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  717. case recordTypeAlert:
  718. if len(data) != 2 {
  719. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  720. break
  721. }
  722. if alert(data[1]) == alertCloseNotify {
  723. c.in.setErrorLocked(io.EOF)
  724. break
  725. }
  726. switch data[0] {
  727. case alertLevelWarning:
  728. // drop on the floor
  729. c.in.freeBlock(b)
  730. c.warnCount++
  731. if c.warnCount > maxWarnAlertCount {
  732. c.sendAlert(alertUnexpectedMessage)
  733. return c.in.setErrorLocked(errors.New("tls: too many warn alerts"))
  734. }
  735. goto Again
  736. case alertLevelError:
  737. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  738. default:
  739. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  740. }
  741. case recordTypeChangeCipherSpec:
  742. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  743. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  744. break
  745. }
  746. // Handshake messages are not allowed to fragment across the CCS
  747. if c.hand.Len() > 0 {
  748. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  749. break
  750. }
  751. // Handshake messages are not allowed to fragment across the CCS
  752. if c.hand.Len() > 0 {
  753. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  754. break
  755. }
  756. err := c.in.changeCipherSpec()
  757. if err != nil {
  758. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  759. }
  760. case recordTypeApplicationData:
  761. if typ != want || c.phase == waitingClientFinished {
  762. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  763. break
  764. }
  765. if c.phase == readingEarlyData {
  766. c.earlyDataBytes += int64(len(b.data) - b.off)
  767. if c.earlyDataBytes > c.ticketMaxEarlyData {
  768. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  769. }
  770. }
  771. c.input = b
  772. b = nil
  773. case recordTypeHandshake:
  774. // TODO(rsc): Should at least pick off connection close.
  775. // If early data was being read, a Finished message is expected
  776. // instead of (early) application data. Other post-handshake
  777. // messages include HelloRequest and NewSessionTicket.
  778. if typ != want && want != recordTypeApplicationData {
  779. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  780. }
  781. c.hand.Write(data)
  782. }
  783. if b != nil {
  784. c.in.freeBlock(b)
  785. }
  786. return c.in.err
  787. }
  788. // peekAlert looks at a message to spot an unencrypted alert. It must be
  789. // called before decryption to avoid a side channel, and its result must
  790. // only be used if decryption fails, to avoid false positives.
  791. func peekAlert(b *block) error {
  792. if len(b.data) < 7 {
  793. return nil
  794. }
  795. if recordType(b.data[0]) != recordTypeAlert {
  796. return nil
  797. }
  798. return &net.OpError{Op: "remote error", Err: alert(b.data[6])}
  799. }
  800. // sendAlert sends a TLS alert message.
  801. // c.out.Mutex <= L.
  802. func (c *Conn) sendAlertLocked(err alert) error {
  803. switch err {
  804. case alertNoRenegotiation, alertCloseNotify:
  805. c.tmp[0] = alertLevelWarning
  806. default:
  807. c.tmp[0] = alertLevelError
  808. }
  809. c.tmp[1] = byte(err)
  810. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  811. if err == alertCloseNotify {
  812. // closeNotify is a special case in that it isn't an error.
  813. return writeErr
  814. }
  815. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  816. }
  817. // sendAlert sends a TLS alert message.
  818. // L < c.out.Mutex.
  819. func (c *Conn) sendAlert(err alert) error {
  820. if c.config.AlternativeRecordLayer != nil {
  821. return nil
  822. }
  823. c.out.Lock()
  824. defer c.out.Unlock()
  825. return c.sendAlertLocked(err)
  826. }
  827. const (
  828. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  829. // size (MSS). A constant is used, rather than querying the kernel for
  830. // the actual MSS, to avoid complexity. The value here is the IPv6
  831. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  832. // bytes) and a TCP header with timestamps (32 bytes).
  833. tcpMSSEstimate = 1208
  834. // recordSizeBoostThreshold is the number of bytes of application data
  835. // sent after which the TLS record size will be increased to the
  836. // maximum.
  837. recordSizeBoostThreshold = 128 * 1024
  838. )
  839. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  840. // next application data record. There is the following trade-off:
  841. //
  842. // - For latency-sensitive applications, such as web browsing, each TLS
  843. // record should fit in one TCP segment.
  844. // - For throughput-sensitive applications, such as large file transfers,
  845. // larger TLS records better amortize framing and encryption overheads.
  846. //
  847. // A simple heuristic that works well in practice is to use small records for
  848. // the first 1MB of data, then use larger records for subsequent data, and
  849. // reset back to smaller records after the connection becomes idle. See "High
  850. // Performance Web Networking", Chapter 4, or:
  851. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  852. //
  853. // In the interests of simplicity and determinism, this code does not attempt
  854. // to reset the record size once the connection is idle, however.
  855. //
  856. // c.out.Mutex <= L.
  857. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  858. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  859. return maxPlaintext
  860. }
  861. if c.bytesSent >= recordSizeBoostThreshold {
  862. return maxPlaintext
  863. }
  864. // Subtract TLS overheads to get the maximum payload size.
  865. macSize := 0
  866. if c.out.mac != nil {
  867. macSize = c.out.mac.Size()
  868. }
  869. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  870. if c.out.cipher != nil {
  871. switch ciph := c.out.cipher.(type) {
  872. case cipher.Stream:
  873. payloadBytes -= macSize
  874. case cipher.AEAD:
  875. payloadBytes -= ciph.Overhead()
  876. if c.vers >= VersionTLS13 {
  877. payloadBytes -= 1 // ContentType
  878. }
  879. case cbcMode:
  880. blockSize := ciph.BlockSize()
  881. // The payload must fit in a multiple of blockSize, with
  882. // room for at least one padding byte.
  883. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  884. // The MAC is appended before padding so affects the
  885. // payload size directly.
  886. payloadBytes -= macSize
  887. default:
  888. panic("unknown cipher type")
  889. }
  890. }
  891. // Allow packet growth in arithmetic progression up to max.
  892. pkt := c.packetsSent
  893. c.packetsSent++
  894. if pkt > 1000 {
  895. return maxPlaintext // avoid overflow in multiply below
  896. }
  897. n := payloadBytes * int(pkt+1)
  898. if n > maxPlaintext {
  899. n = maxPlaintext
  900. }
  901. return n
  902. }
  903. // c.out.Mutex <= L.
  904. func (c *Conn) write(data []byte) (int, error) {
  905. if c.buffering {
  906. c.sendBuf = append(c.sendBuf, data...)
  907. return len(data), nil
  908. }
  909. n, err := c.conn.Write(data)
  910. c.bytesSent += int64(n)
  911. return n, err
  912. }
  913. func (c *Conn) flush() (int, error) {
  914. if len(c.sendBuf) == 0 {
  915. return 0, nil
  916. }
  917. n, err := c.conn.Write(c.sendBuf)
  918. c.bytesSent += int64(n)
  919. c.sendBuf = nil
  920. c.buffering = false
  921. return n, err
  922. }
  923. // writeRecordLocked writes a TLS record with the given type and payload to the
  924. // connection and updates the record layer state.
  925. // c.out.Mutex <= L.
  926. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  927. b := c.out.newBlock()
  928. defer c.out.freeBlock(b)
  929. var n int
  930. for len(data) > 0 {
  931. explicitIVLen := 0
  932. explicitIVIsSeq := false
  933. var cbc cbcMode
  934. if c.out.version >= VersionTLS11 {
  935. var ok bool
  936. if cbc, ok = c.out.cipher.(cbcMode); ok {
  937. explicitIVLen = cbc.BlockSize()
  938. }
  939. }
  940. if explicitIVLen == 0 {
  941. if c, ok := c.out.cipher.(aead); ok {
  942. explicitIVLen = c.explicitNonceLen()
  943. // The AES-GCM construction in TLS has an
  944. // explicit nonce so that the nonce can be
  945. // random. However, the nonce is only 8 bytes
  946. // which is too small for a secure, random
  947. // nonce. Therefore we use the sequence number
  948. // as the nonce.
  949. explicitIVIsSeq = explicitIVLen > 0
  950. }
  951. }
  952. m := len(data)
  953. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  954. m = maxPayload
  955. }
  956. b.resize(recordHeaderLen + explicitIVLen + m)
  957. b.data[0] = byte(typ)
  958. vers := c.vers
  959. if vers == 0 {
  960. // Some TLS servers fail if the record version is
  961. // greater than TLS 1.0 for the initial ClientHello.
  962. vers = VersionTLS10
  963. }
  964. if c.vers >= VersionTLS13 {
  965. // TLS 1.3 froze the record layer version at { 3, 1 }.
  966. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.1.
  967. // But for draft 22, this was changed to { 3, 3 }.
  968. vers = VersionTLS12
  969. }
  970. b.data[1] = byte(vers >> 8)
  971. b.data[2] = byte(vers)
  972. b.data[3] = byte(m >> 8)
  973. b.data[4] = byte(m)
  974. if explicitIVLen > 0 {
  975. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  976. if explicitIVIsSeq {
  977. copy(explicitIV, c.out.seq[:])
  978. } else {
  979. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  980. return n, err
  981. }
  982. }
  983. }
  984. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  985. c.out.encrypt(b, explicitIVLen)
  986. if _, err := c.write(b.data); err != nil {
  987. return n, err
  988. }
  989. n += m
  990. data = data[m:]
  991. }
  992. if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
  993. if err := c.out.changeCipherSpec(); err != nil {
  994. return n, c.sendAlertLocked(err.(alert))
  995. }
  996. }
  997. return n, nil
  998. }
  999. // writeRecord writes a TLS record with the given type and payload to the
  1000. // connection and updates the record layer state.
  1001. // L < c.out.Mutex.
  1002. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  1003. if c.config.AlternativeRecordLayer != nil {
  1004. if typ == recordTypeChangeCipherSpec {
  1005. return len(data), nil
  1006. }
  1007. return c.config.AlternativeRecordLayer.WriteRecord(data)
  1008. }
  1009. c.out.Lock()
  1010. defer c.out.Unlock()
  1011. return c.writeRecordLocked(typ, data)
  1012. }
  1013. // readHandshake reads the next handshake message from
  1014. // the record layer.
  1015. // c.in.Mutex < L; c.out.Mutex < L.
  1016. func (c *Conn) readHandshake() (interface{}, error) {
  1017. var data []byte
  1018. if c.config.AlternativeRecordLayer != nil {
  1019. var err error
  1020. data, err = c.config.AlternativeRecordLayer.ReadHandshakeMessage()
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. } else {
  1025. for c.hand.Len() < 4 {
  1026. if err := c.in.err; err != nil {
  1027. return nil, err
  1028. }
  1029. if err := c.readRecord(recordTypeHandshake); err != nil {
  1030. return nil, err
  1031. }
  1032. }
  1033. data = c.hand.Bytes()
  1034. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1035. if n > maxHandshake {
  1036. c.sendAlertLocked(alertInternalError)
  1037. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  1038. }
  1039. for c.hand.Len() < 4+n {
  1040. if err := c.in.err; err != nil {
  1041. return nil, err
  1042. }
  1043. if err := c.readRecord(recordTypeHandshake); err != nil {
  1044. return nil, err
  1045. }
  1046. }
  1047. data = c.hand.Next(4 + n)
  1048. }
  1049. var m handshakeMessage
  1050. switch data[0] {
  1051. case typeHelloRequest:
  1052. m = new(helloRequestMsg)
  1053. case typeClientHello:
  1054. m = new(clientHelloMsg)
  1055. case typeServerHello:
  1056. m = new(serverHelloMsg)
  1057. case typeEncryptedExtensions:
  1058. m = new(encryptedExtensionsMsg)
  1059. case typeNewSessionTicket:
  1060. if c.vers >= VersionTLS13 {
  1061. m = new(newSessionTicketMsg13)
  1062. } else {
  1063. m = new(newSessionTicketMsg)
  1064. }
  1065. case typeEndOfEarlyData:
  1066. m = new(endOfEarlyDataMsg)
  1067. case typeCertificate:
  1068. if c.vers >= VersionTLS13 {
  1069. m = new(certificateMsg13)
  1070. } else {
  1071. m = new(certificateMsg)
  1072. }
  1073. case typeCertificateRequest:
  1074. if c.vers >= VersionTLS13 {
  1075. m = new(certificateRequestMsg13)
  1076. } else {
  1077. m = &certificateRequestMsg{
  1078. hasSignatureAndHash: c.vers >= VersionTLS12,
  1079. }
  1080. }
  1081. case typeCertificateStatus:
  1082. m = new(certificateStatusMsg)
  1083. case typeServerKeyExchange:
  1084. m = new(serverKeyExchangeMsg)
  1085. case typeServerHelloDone:
  1086. m = new(serverHelloDoneMsg)
  1087. case typeClientKeyExchange:
  1088. m = new(clientKeyExchangeMsg)
  1089. case typeCertificateVerify:
  1090. m = &certificateVerifyMsg{
  1091. hasSignatureAndHash: c.vers >= VersionTLS12,
  1092. }
  1093. case typeNextProtocol:
  1094. m = new(nextProtoMsg)
  1095. case typeFinished:
  1096. m = new(finishedMsg)
  1097. default:
  1098. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1099. }
  1100. // The handshake message unmarshalers
  1101. // expect to be able to keep references to data,
  1102. // so pass in a fresh copy that won't be overwritten.
  1103. data = append([]byte(nil), data...)
  1104. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1105. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1106. }
  1107. return m, nil
  1108. }
  1109. var (
  1110. errClosed = errors.New("tls: use of closed connection")
  1111. errShutdown = errors.New("tls: protocol is shutdown")
  1112. )
  1113. // Write writes data to the connection.
  1114. func (c *Conn) Write(b []byte) (int, error) {
  1115. // interlock with Close below
  1116. for {
  1117. x := atomic.LoadInt32(&c.activeCall)
  1118. if x&1 != 0 {
  1119. return 0, errClosed
  1120. }
  1121. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1122. defer atomic.AddInt32(&c.activeCall, -2)
  1123. break
  1124. }
  1125. }
  1126. if err := c.Handshake(); err != nil {
  1127. return 0, err
  1128. }
  1129. c.out.Lock()
  1130. defer c.out.Unlock()
  1131. if err := c.out.err; err != nil {
  1132. return 0, err
  1133. }
  1134. if !c.handshakeComplete {
  1135. return 0, alertInternalError
  1136. }
  1137. if c.closeNotifySent {
  1138. return 0, errShutdown
  1139. }
  1140. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1141. // attack when using block mode ciphers due to predictable IVs.
  1142. // This can be prevented by splitting each Application Data
  1143. // record into two records, effectively randomizing the IV.
  1144. //
  1145. // http://www.openssl.org/~bodo/tls-cbc.txt
  1146. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1147. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1148. var m int
  1149. if len(b) > 1 && c.vers <= VersionTLS10 {
  1150. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1151. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1152. if err != nil {
  1153. return n, c.out.setErrorLocked(err)
  1154. }
  1155. m, b = 1, b[1:]
  1156. }
  1157. }
  1158. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1159. return n + m, c.out.setErrorLocked(err)
  1160. }
  1161. // Process Handshake messages after the handshake has completed.
  1162. // c.in.Mutex <= L
  1163. func (c *Conn) handlePostHandshake() error {
  1164. msg, err := c.readHandshake()
  1165. if err != nil {
  1166. return err
  1167. }
  1168. switch hm := msg.(type) {
  1169. case *helloRequestMsg:
  1170. return c.handleRenegotiation(hm)
  1171. case *newSessionTicketMsg13:
  1172. if !c.isClient {
  1173. c.sendAlert(alertUnexpectedMessage)
  1174. return alertUnexpectedMessage
  1175. }
  1176. return nil // TODO implement session tickets
  1177. default:
  1178. c.sendAlert(alertUnexpectedMessage)
  1179. return alertUnexpectedMessage
  1180. }
  1181. }
  1182. // handleRenegotiation processes a HelloRequest handshake message.
  1183. // c.in.Mutex <= L
  1184. func (c *Conn) handleRenegotiation(*helloRequestMsg) error {
  1185. if !c.isClient {
  1186. return c.sendAlert(alertNoRenegotiation)
  1187. }
  1188. if c.vers >= VersionTLS13 {
  1189. return c.sendAlert(alertNoRenegotiation)
  1190. }
  1191. switch c.config.Renegotiation {
  1192. case RenegotiateNever:
  1193. return c.sendAlert(alertNoRenegotiation)
  1194. case RenegotiateOnceAsClient:
  1195. if c.handshakes > 1 {
  1196. return c.sendAlert(alertNoRenegotiation)
  1197. }
  1198. case RenegotiateFreelyAsClient:
  1199. // Ok.
  1200. default:
  1201. c.sendAlert(alertInternalError)
  1202. return errors.New("tls: unknown Renegotiation value")
  1203. }
  1204. c.handshakeMutex.Lock()
  1205. defer c.handshakeMutex.Unlock()
  1206. c.phase = handshakeRunning
  1207. c.handshakeComplete = false
  1208. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1209. c.handshakes++
  1210. }
  1211. return c.handshakeErr
  1212. }
  1213. func (c *Conn) setAlternativeRecordLayer() {
  1214. if c.config.AlternativeRecordLayer != nil {
  1215. c.in.setKeyCallback = c.config.AlternativeRecordLayer.SetReadKey
  1216. c.out.setKeyCallback = c.config.AlternativeRecordLayer.SetWriteKey
  1217. }
  1218. }
  1219. // ConfirmHandshake waits for the handshake to reach a point at which
  1220. // the connection is certainly not replayed. That is, after receiving
  1221. // the Client Finished.
  1222. //
  1223. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1224. // returns, the 0-RTT data should not be trusted not to be replayed.
  1225. //
  1226. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1227. // client sent valid 0-RTT data. In any other case it's equivalent to
  1228. // calling Handshake.
  1229. func (c *Conn) ConfirmHandshake() error {
  1230. if c.isClient {
  1231. panic("ConfirmHandshake should only be called for servers")
  1232. }
  1233. if err := c.Handshake(); err != nil {
  1234. return err
  1235. }
  1236. if c.vers < VersionTLS13 {
  1237. return nil
  1238. }
  1239. c.confirmMutex.Lock()
  1240. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1241. c.confirmMutex.Unlock()
  1242. return nil
  1243. } else {
  1244. defer func() {
  1245. // If we transitioned to handshakeConfirmed we already released the lock,
  1246. // otherwise do it here.
  1247. if c.phase != handshakeConfirmed {
  1248. c.confirmMutex.Unlock()
  1249. }
  1250. }()
  1251. }
  1252. c.in.Lock()
  1253. defer c.in.Unlock()
  1254. var input *block
  1255. // Try to read all data (if phase==readingEarlyData) or extract the
  1256. // remaining data from the previous read that could not fit in the read
  1257. // buffer (if c.input != nil).
  1258. if c.phase == readingEarlyData || c.input != nil {
  1259. buf := &bytes.Buffer{}
  1260. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1261. c.in.setErrorLocked(err)
  1262. return err
  1263. }
  1264. input = &block{data: buf.Bytes()}
  1265. }
  1266. // At this point, earlyDataReader has read all early data and received
  1267. // the end_of_early_data signal. Expect a Finished message.
  1268. // Locks held so far: c.confirmMutex, c.in
  1269. // not confirmed implies c.phase == discardingEarlyData || c.phase == waitingClientFinished
  1270. for c.phase != handshakeConfirmed {
  1271. if err := c.hs.readClientFinished13(true); err != nil {
  1272. c.in.setErrorLocked(err)
  1273. return err
  1274. }
  1275. }
  1276. if c.phase != handshakeConfirmed {
  1277. panic("should have reached handshakeConfirmed state")
  1278. }
  1279. if c.input != nil {
  1280. panic("should not have read past the Client Finished")
  1281. }
  1282. c.input = input
  1283. return nil
  1284. }
  1285. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1286. // and still on the wire.
  1287. type earlyDataReader struct {
  1288. c *Conn
  1289. }
  1290. // c.in.Mutex <= L
  1291. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1292. c := r.c
  1293. if c.phase == handshakeConfirmed {
  1294. // c.input might not be early data
  1295. panic("earlyDataReader called at handshakeConfirmed")
  1296. }
  1297. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1298. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1299. return 0, err
  1300. }
  1301. if c.hand.Len() > 0 {
  1302. if err := c.handleEndOfEarlyData(); err != nil {
  1303. return 0, err
  1304. }
  1305. }
  1306. }
  1307. if err := c.in.err; err != nil {
  1308. return 0, err
  1309. }
  1310. if c.input != nil {
  1311. n, err = c.input.Read(b)
  1312. if err == io.EOF {
  1313. err = nil
  1314. c.in.freeBlock(c.input)
  1315. c.input = nil
  1316. }
  1317. }
  1318. // Following early application data, an end_of_early_data is expected.
  1319. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1320. err = io.EOF
  1321. }
  1322. return
  1323. }
  1324. // Read can be made to time out and return a net.Error with Timeout() == true
  1325. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1326. func (c *Conn) Read(b []byte) (n int, err error) {
  1327. if err = c.Handshake(); err != nil {
  1328. return
  1329. }
  1330. if len(b) == 0 {
  1331. // Put this after Handshake, in case people were calling
  1332. // Read(nil) for the side effect of the Handshake.
  1333. return
  1334. }
  1335. c.confirmMutex.Lock()
  1336. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1337. c.confirmMutex.Unlock()
  1338. } else {
  1339. defer func() {
  1340. // If we transitioned to handshakeConfirmed we already released the lock,
  1341. // otherwise do it here.
  1342. if c.phase != handshakeConfirmed {
  1343. c.confirmMutex.Unlock()
  1344. }
  1345. }()
  1346. }
  1347. c.in.Lock()
  1348. defer c.in.Unlock()
  1349. // Some OpenSSL servers send empty records in order to randomize the
  1350. // CBC IV. So this loop ignores a limited number of empty records.
  1351. const maxConsecutiveEmptyRecords = 100
  1352. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1353. for c.input == nil && c.in.err == nil {
  1354. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1355. // Soft error, like EAGAIN
  1356. return 0, err
  1357. }
  1358. if c.hand.Len() > 0 {
  1359. if c.phase == readingEarlyData || c.phase == waitingClientFinished {
  1360. if c.phase == readingEarlyData {
  1361. if err := c.handleEndOfEarlyData(); err != nil {
  1362. return 0, err
  1363. }
  1364. }
  1365. // Server has received all early data, confirm
  1366. // by reading the Client Finished message.
  1367. if err := c.hs.readClientFinished13(true); err != nil {
  1368. c.in.setErrorLocked(err)
  1369. return 0, err
  1370. }
  1371. continue
  1372. }
  1373. if err := c.handlePostHandshake(); err != nil {
  1374. return 0, err
  1375. }
  1376. }
  1377. }
  1378. if err := c.in.err; err != nil {
  1379. return 0, err
  1380. }
  1381. n, err = c.input.Read(b)
  1382. if err == io.EOF {
  1383. err = nil
  1384. c.in.freeBlock(c.input)
  1385. c.input = nil
  1386. }
  1387. // If a close-notify alert is waiting, read it so that
  1388. // we can return (n, EOF) instead of (n, nil), to signal
  1389. // to the HTTP response reading goroutine that the
  1390. // connection is now closed. This eliminates a race
  1391. // where the HTTP response reading goroutine would
  1392. // otherwise not observe the EOF until its next read,
  1393. // by which time a client goroutine might have already
  1394. // tried to reuse the HTTP connection for a new
  1395. // request.
  1396. // See https://codereview.appspot.com/76400046
  1397. // and https://golang.org/issue/3514
  1398. if ri := c.rawInput; ri != nil &&
  1399. n != 0 && err == nil &&
  1400. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1401. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1402. err = recErr // will be io.EOF on closeNotify
  1403. }
  1404. }
  1405. if n != 0 || err != nil {
  1406. return n, err
  1407. }
  1408. }
  1409. return 0, io.ErrNoProgress
  1410. }
  1411. // Close closes the connection.
  1412. func (c *Conn) Close() error {
  1413. // Interlock with Conn.Write above.
  1414. var x int32
  1415. for {
  1416. x = atomic.LoadInt32(&c.activeCall)
  1417. if x&1 != 0 {
  1418. return errClosed
  1419. }
  1420. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1421. break
  1422. }
  1423. }
  1424. if x != 0 {
  1425. // io.Writer and io.Closer should not be used concurrently.
  1426. // If Close is called while a Write is currently in-flight,
  1427. // interpret that as a sign that this Close is really just
  1428. // being used to break the Write and/or clean up resources and
  1429. // avoid sending the alertCloseNotify, which may block
  1430. // waiting on handshakeMutex or the c.out mutex.
  1431. return c.conn.Close()
  1432. }
  1433. var alertErr error
  1434. c.handshakeMutex.Lock()
  1435. if c.handshakeComplete {
  1436. alertErr = c.closeNotify()
  1437. }
  1438. c.handshakeMutex.Unlock()
  1439. if err := c.conn.Close(); err != nil {
  1440. return err
  1441. }
  1442. return alertErr
  1443. }
  1444. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1445. // CloseWrite shuts down the writing side of the connection. It should only be
  1446. // called once the handshake has completed and does not call CloseWrite on the
  1447. // underlying connection. Most callers should just use Close.
  1448. func (c *Conn) CloseWrite() error {
  1449. c.handshakeMutex.Lock()
  1450. defer c.handshakeMutex.Unlock()
  1451. if !c.handshakeComplete {
  1452. return errEarlyCloseWrite
  1453. }
  1454. return c.closeNotify()
  1455. }
  1456. func (c *Conn) closeNotify() error {
  1457. c.out.Lock()
  1458. defer c.out.Unlock()
  1459. if !c.closeNotifySent {
  1460. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1461. c.closeNotifySent = true
  1462. }
  1463. return c.closeNotifyErr
  1464. }
  1465. // Handshake runs the client or server handshake
  1466. // protocol if it has not yet been run.
  1467. // Most uses of this package need not call Handshake
  1468. // explicitly: the first Read or Write will call it automatically.
  1469. //
  1470. // In TLS 1.3 Handshake returns after the client and server first flights,
  1471. // without waiting for the Client Finished.
  1472. func (c *Conn) Handshake() error {
  1473. c.handshakeMutex.Lock()
  1474. defer c.handshakeMutex.Unlock()
  1475. if err := c.handshakeErr; err != nil {
  1476. return err
  1477. }
  1478. if c.handshakeComplete {
  1479. return nil
  1480. }
  1481. c.in.Lock()
  1482. defer c.in.Unlock()
  1483. // The handshake cannot have completed when handshakeMutex was unlocked
  1484. // because this goroutine set handshakeCond.
  1485. if c.handshakeErr != nil || c.handshakeComplete {
  1486. panic("handshake should not have been able to complete after handshakeCond was set")
  1487. }
  1488. c.connID = make([]byte, 8)
  1489. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1490. return err
  1491. }
  1492. if c.isClient {
  1493. c.handshakeErr = c.clientHandshake()
  1494. } else {
  1495. c.handshakeErr = c.serverHandshake()
  1496. }
  1497. if c.handshakeErr == nil {
  1498. c.handshakes++
  1499. } else {
  1500. // If an error occurred during the hadshake try to flush the
  1501. // alert that might be left in the buffer.
  1502. c.flush()
  1503. }
  1504. if c.handshakeErr == nil && !c.handshakeComplete {
  1505. panic("handshake should have had a result.")
  1506. }
  1507. return c.handshakeErr
  1508. }
  1509. // ConnectionState returns basic TLS details about the connection.
  1510. func (c *Conn) ConnectionState() ConnectionState {
  1511. c.handshakeMutex.Lock()
  1512. defer c.handshakeMutex.Unlock()
  1513. var state ConnectionState
  1514. state.HandshakeComplete = c.handshakeComplete
  1515. state.ServerName = c.serverName
  1516. if c.handshakeComplete {
  1517. state.ConnectionID = c.connID
  1518. state.ClientHello = c.clientHello
  1519. state.Version = c.vers
  1520. state.NegotiatedProtocol = c.clientProtocol
  1521. state.DidResume = c.didResume
  1522. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1523. state.CipherSuite = c.cipherSuite
  1524. state.PeerCertificates = c.peerCertificates
  1525. state.VerifiedChains = c.verifiedChains
  1526. state.SignedCertificateTimestamps = c.scts
  1527. state.OCSPResponse = c.ocspResponse
  1528. if c.verifiedDc != nil {
  1529. state.DelegatedCredential = c.verifiedDc.raw
  1530. }
  1531. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1532. if !state.HandshakeConfirmed {
  1533. state.Unique0RTTToken = c.binder
  1534. }
  1535. if !c.didResume {
  1536. if c.clientFinishedIsFirst {
  1537. state.TLSUnique = c.clientFinished[:]
  1538. } else {
  1539. state.TLSUnique = c.serverFinished[:]
  1540. }
  1541. }
  1542. }
  1543. return state
  1544. }
  1545. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1546. // any. (Only valid for client connections.)
  1547. func (c *Conn) OCSPResponse() []byte {
  1548. c.handshakeMutex.Lock()
  1549. defer c.handshakeMutex.Unlock()
  1550. return c.ocspResponse
  1551. }
  1552. // VerifyHostname checks that the peer certificate chain is valid for
  1553. // connecting to host. If so, it returns nil; if not, it returns an error
  1554. // describing the problem.
  1555. func (c *Conn) VerifyHostname(host string) error {
  1556. c.handshakeMutex.Lock()
  1557. defer c.handshakeMutex.Unlock()
  1558. if !c.isClient {
  1559. return errors.New("tls: VerifyHostname called on TLS server connection")
  1560. }
  1561. if !c.handshakeComplete {
  1562. return errors.New("tls: handshake has not yet been performed")
  1563. }
  1564. if len(c.verifiedChains) == 0 {
  1565. return errors.New("tls: handshake did not verify certificate chain")
  1566. }
  1567. return c.peerCertificates[0].VerifyHostname(host)
  1568. }