conn.go 49 KB

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