選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conn.go 38 KiB

Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9年前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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 main
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/ecdsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "encoding/binary"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "net"
  17. "sync"
  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. isDTLS bool
  26. isClient bool
  27. // constant after handshake; protected by handshakeMutex
  28. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  29. handshakeErr error // error resulting from handshake
  30. vers uint16 // TLS version
  31. haveVers bool // version has been negotiated
  32. config *Config // configuration passed to constructor
  33. handshakeComplete bool
  34. didResume bool // whether this connection was a session resumption
  35. extendedMasterSecret bool // whether this session used an extended master secret
  36. cipherSuite *cipherSuite
  37. ocspResponse []byte // stapled OCSP response
  38. peerCertificates []*x509.Certificate
  39. // verifiedChains contains the certificate chains that we built, as
  40. // opposed to the ones presented by the server.
  41. verifiedChains [][]*x509.Certificate
  42. // serverName contains the server name indicated by the client, if any.
  43. serverName string
  44. // firstFinished contains the first Finished hash sent during the
  45. // handshake. This is the "tls-unique" channel binding value.
  46. firstFinished [12]byte
  47. clientRandom, serverRandom [32]byte
  48. masterSecret [48]byte
  49. clientProtocol string
  50. clientProtocolFallback bool
  51. usedALPN bool
  52. // verify_data values for the renegotiation extension.
  53. clientVerify []byte
  54. serverVerify []byte
  55. channelID *ecdsa.PublicKey
  56. srtpProtectionProfile uint16
  57. clientVersion uint16
  58. // input/output
  59. in, out halfConn // in.Mutex < out.Mutex
  60. rawInput *block // raw input, right off the wire
  61. input *block // application record waiting to be read
  62. hand bytes.Buffer // handshake record waiting to be read
  63. // DTLS state
  64. sendHandshakeSeq uint16
  65. recvHandshakeSeq uint16
  66. handMsg []byte // pending assembled handshake message
  67. handMsgLen int // handshake message length, not including the header
  68. pendingFragments [][]byte // pending outgoing handshake fragments.
  69. tmp [16]byte
  70. }
  71. func (c *Conn) init() {
  72. c.in.isDTLS = c.isDTLS
  73. c.out.isDTLS = c.isDTLS
  74. c.in.config = c.config
  75. c.out.config = c.config
  76. c.out.updateOutSeq()
  77. }
  78. // Access to net.Conn methods.
  79. // Cannot just embed net.Conn because that would
  80. // export the struct field too.
  81. // LocalAddr returns the local network address.
  82. func (c *Conn) LocalAddr() net.Addr {
  83. return c.conn.LocalAddr()
  84. }
  85. // RemoteAddr returns the remote network address.
  86. func (c *Conn) RemoteAddr() net.Addr {
  87. return c.conn.RemoteAddr()
  88. }
  89. // SetDeadline sets the read and write deadlines associated with the connection.
  90. // A zero value for t means Read and Write will not time out.
  91. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  92. func (c *Conn) SetDeadline(t time.Time) error {
  93. return c.conn.SetDeadline(t)
  94. }
  95. // SetReadDeadline sets the read deadline on the underlying connection.
  96. // A zero value for t means Read will not time out.
  97. func (c *Conn) SetReadDeadline(t time.Time) error {
  98. return c.conn.SetReadDeadline(t)
  99. }
  100. // SetWriteDeadline sets the write deadline on the underlying conneciton.
  101. // A zero value for t means Write will not time out.
  102. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  103. func (c *Conn) SetWriteDeadline(t time.Time) error {
  104. return c.conn.SetWriteDeadline(t)
  105. }
  106. // A halfConn represents one direction of the record layer
  107. // connection, either sending or receiving.
  108. type halfConn struct {
  109. sync.Mutex
  110. err error // first permanent error
  111. version uint16 // protocol version
  112. isDTLS bool
  113. cipher interface{} // cipher algorithm
  114. mac macFunction
  115. seq [8]byte // 64-bit sequence number
  116. outSeq [8]byte // Mapped sequence number
  117. bfree *block // list of free blocks
  118. nextCipher interface{} // next encryption state
  119. nextMac macFunction // next MAC algorithm
  120. nextSeq [6]byte // next epoch's starting sequence number in DTLS
  121. // used to save allocating a new buffer for each MAC.
  122. inDigestBuf, outDigestBuf []byte
  123. config *Config
  124. }
  125. func (hc *halfConn) setErrorLocked(err error) error {
  126. hc.err = err
  127. return err
  128. }
  129. func (hc *halfConn) error() error {
  130. // This should be locked, but I've removed it for the renegotiation
  131. // tests since we don't concurrently read and write the same tls.Conn
  132. // in any case during testing.
  133. err := hc.err
  134. return err
  135. }
  136. // prepareCipherSpec sets the encryption and MAC states
  137. // that a subsequent changeCipherSpec will use.
  138. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  139. hc.version = version
  140. hc.nextCipher = cipher
  141. hc.nextMac = mac
  142. }
  143. // changeCipherSpec changes the encryption and MAC states
  144. // to the ones previously passed to prepareCipherSpec.
  145. func (hc *halfConn) changeCipherSpec(config *Config) error {
  146. if hc.nextCipher == nil {
  147. return alertInternalError
  148. }
  149. hc.cipher = hc.nextCipher
  150. hc.mac = hc.nextMac
  151. hc.nextCipher = nil
  152. hc.nextMac = nil
  153. hc.config = config
  154. hc.incEpoch()
  155. return nil
  156. }
  157. // incSeq increments the sequence number.
  158. func (hc *halfConn) incSeq(isOutgoing bool) {
  159. limit := 0
  160. increment := uint64(1)
  161. if hc.isDTLS {
  162. // Increment up to the epoch in DTLS.
  163. limit = 2
  164. }
  165. for i := 7; i >= limit; i-- {
  166. increment += uint64(hc.seq[i])
  167. hc.seq[i] = byte(increment)
  168. increment >>= 8
  169. }
  170. // Not allowed to let sequence number wrap.
  171. // Instead, must renegotiate before it does.
  172. // Not likely enough to bother.
  173. if increment != 0 {
  174. panic("TLS: sequence number wraparound")
  175. }
  176. hc.updateOutSeq()
  177. }
  178. // incNextSeq increments the starting sequence number for the next epoch.
  179. func (hc *halfConn) incNextSeq() {
  180. for i := len(hc.nextSeq) - 1; i >= 0; i-- {
  181. hc.nextSeq[i]++
  182. if hc.nextSeq[i] != 0 {
  183. return
  184. }
  185. }
  186. panic("TLS: sequence number wraparound")
  187. }
  188. // incEpoch resets the sequence number. In DTLS, it also increments the epoch
  189. // half of the sequence number.
  190. func (hc *halfConn) incEpoch() {
  191. if hc.isDTLS {
  192. for i := 1; i >= 0; i-- {
  193. hc.seq[i]++
  194. if hc.seq[i] != 0 {
  195. break
  196. }
  197. if i == 0 {
  198. panic("TLS: epoch number wraparound")
  199. }
  200. }
  201. copy(hc.seq[2:], hc.nextSeq[:])
  202. for i := range hc.nextSeq {
  203. hc.nextSeq[i] = 0
  204. }
  205. } else {
  206. for i := range hc.seq {
  207. hc.seq[i] = 0
  208. }
  209. }
  210. hc.updateOutSeq()
  211. }
  212. func (hc *halfConn) updateOutSeq() {
  213. if hc.config.Bugs.SequenceNumberMapping != nil {
  214. seqU64 := binary.BigEndian.Uint64(hc.seq[:])
  215. seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
  216. binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
  217. // The DTLS epoch cannot be changed.
  218. copy(hc.outSeq[:2], hc.seq[:2])
  219. return
  220. }
  221. copy(hc.outSeq[:], hc.seq[:])
  222. }
  223. func (hc *halfConn) recordHeaderLen() int {
  224. if hc.isDTLS {
  225. return dtlsRecordHeaderLen
  226. }
  227. return tlsRecordHeaderLen
  228. }
  229. // removePadding returns an unpadded slice, in constant time, which is a prefix
  230. // of the input. It also returns a byte which is equal to 255 if the padding
  231. // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  232. func removePadding(payload []byte) ([]byte, byte) {
  233. if len(payload) < 1 {
  234. return payload, 0
  235. }
  236. paddingLen := payload[len(payload)-1]
  237. t := uint(len(payload)-1) - uint(paddingLen)
  238. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  239. good := byte(int32(^t) >> 31)
  240. toCheck := 255 // the maximum possible padding length
  241. // The length of the padded data is public, so we can use an if here
  242. if toCheck+1 > len(payload) {
  243. toCheck = len(payload) - 1
  244. }
  245. for i := 0; i < toCheck; i++ {
  246. t := uint(paddingLen) - uint(i)
  247. // if i <= paddingLen then the MSB of t is zero
  248. mask := byte(int32(^t) >> 31)
  249. b := payload[len(payload)-1-i]
  250. good &^= mask&paddingLen ^ mask&b
  251. }
  252. // We AND together the bits of good and replicate the result across
  253. // all the bits.
  254. good &= good << 4
  255. good &= good << 2
  256. good &= good << 1
  257. good = uint8(int8(good) >> 7)
  258. toRemove := good&paddingLen + 1
  259. return payload[:len(payload)-int(toRemove)], good
  260. }
  261. // removePaddingSSL30 is a replacement for removePadding in the case that the
  262. // protocol version is SSLv3. In this version, the contents of the padding
  263. // are random and cannot be checked.
  264. func removePaddingSSL30(payload []byte) ([]byte, byte) {
  265. if len(payload) < 1 {
  266. return payload, 0
  267. }
  268. paddingLen := int(payload[len(payload)-1]) + 1
  269. if paddingLen > len(payload) {
  270. return payload, 0
  271. }
  272. return payload[:len(payload)-paddingLen], 255
  273. }
  274. func roundUp(a, b int) int {
  275. return a + (b-a%b)%b
  276. }
  277. // cbcMode is an interface for block ciphers using cipher block chaining.
  278. type cbcMode interface {
  279. cipher.BlockMode
  280. SetIV([]byte)
  281. }
  282. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  283. // success boolean, the number of bytes to skip from the start of the record in
  284. // order to get the application payload, and an optional alert value.
  285. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  286. recordHeaderLen := hc.recordHeaderLen()
  287. // pull out payload
  288. payload := b.data[recordHeaderLen:]
  289. macSize := 0
  290. if hc.mac != nil {
  291. macSize = hc.mac.Size()
  292. }
  293. paddingGood := byte(255)
  294. explicitIVLen := 0
  295. seq := hc.seq[:]
  296. if hc.isDTLS {
  297. // DTLS sequence numbers are explicit.
  298. seq = b.data[3:11]
  299. }
  300. // decrypt
  301. if hc.cipher != nil {
  302. switch c := hc.cipher.(type) {
  303. case cipher.Stream:
  304. c.XORKeyStream(payload, payload)
  305. case *tlsAead:
  306. nonce := seq
  307. if c.explicitNonce {
  308. explicitIVLen = 8
  309. if len(payload) < explicitIVLen {
  310. return false, 0, alertBadRecordMAC
  311. }
  312. nonce = payload[:8]
  313. payload = payload[8:]
  314. }
  315. var additionalData [13]byte
  316. copy(additionalData[:], seq)
  317. copy(additionalData[8:], b.data[:3])
  318. n := len(payload) - c.Overhead()
  319. additionalData[11] = byte(n >> 8)
  320. additionalData[12] = byte(n)
  321. var err error
  322. payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
  323. if err != nil {
  324. return false, 0, alertBadRecordMAC
  325. }
  326. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  327. case cbcMode:
  328. blockSize := c.BlockSize()
  329. if hc.version >= VersionTLS11 || hc.isDTLS {
  330. explicitIVLen = blockSize
  331. }
  332. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  333. return false, 0, alertBadRecordMAC
  334. }
  335. if explicitIVLen > 0 {
  336. c.SetIV(payload[:explicitIVLen])
  337. payload = payload[explicitIVLen:]
  338. }
  339. c.CryptBlocks(payload, payload)
  340. if hc.version == VersionSSL30 {
  341. payload, paddingGood = removePaddingSSL30(payload)
  342. } else {
  343. payload, paddingGood = removePadding(payload)
  344. }
  345. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  346. // note that we still have a timing side-channel in the
  347. // MAC check, below. An attacker can align the record
  348. // so that a correct padding will cause one less hash
  349. // block to be calculated. Then they can iteratively
  350. // decrypt a record by breaking each byte. See
  351. // "Password Interception in a SSL/TLS Channel", Brice
  352. // Canvel et al.
  353. //
  354. // However, our behavior matches OpenSSL, so we leak
  355. // only as much as they do.
  356. default:
  357. panic("unknown cipher type")
  358. }
  359. }
  360. // check, strip mac
  361. if hc.mac != nil {
  362. if len(payload) < macSize {
  363. return false, 0, alertBadRecordMAC
  364. }
  365. // strip mac off payload, b.data
  366. n := len(payload) - macSize
  367. b.data[recordHeaderLen-2] = byte(n >> 8)
  368. b.data[recordHeaderLen-1] = byte(n)
  369. b.resize(recordHeaderLen + explicitIVLen + n)
  370. remoteMAC := payload[n:]
  371. localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
  372. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  373. return false, 0, alertBadRecordMAC
  374. }
  375. hc.inDigestBuf = localMAC
  376. }
  377. hc.incSeq(false)
  378. return true, recordHeaderLen + explicitIVLen, 0
  379. }
  380. // padToBlockSize calculates the needed padding block, if any, for a payload.
  381. // On exit, prefix aliases payload and extends to the end of the last full
  382. // block of payload. finalBlock is a fresh slice which contains the contents of
  383. // any suffix of payload as well as the needed padding to make finalBlock a
  384. // full block.
  385. func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
  386. overrun := len(payload) % blockSize
  387. prefix = payload[:len(payload)-overrun]
  388. paddingLen := blockSize - overrun
  389. finalSize := blockSize
  390. if config.Bugs.MaxPadding {
  391. for paddingLen+blockSize <= 256 {
  392. paddingLen += blockSize
  393. }
  394. finalSize = 256
  395. }
  396. finalBlock = make([]byte, finalSize)
  397. for i := range finalBlock {
  398. finalBlock[i] = byte(paddingLen - 1)
  399. }
  400. if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
  401. finalBlock[overrun] ^= 0xff
  402. }
  403. copy(finalBlock, payload[len(payload)-overrun:])
  404. return
  405. }
  406. // encrypt encrypts and macs the data in b.
  407. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  408. recordHeaderLen := hc.recordHeaderLen()
  409. // mac
  410. if hc.mac != nil {
  411. mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
  412. n := len(b.data)
  413. b.resize(n + len(mac))
  414. copy(b.data[n:], mac)
  415. hc.outDigestBuf = mac
  416. }
  417. payload := b.data[recordHeaderLen:]
  418. // encrypt
  419. if hc.cipher != nil {
  420. switch c := hc.cipher.(type) {
  421. case cipher.Stream:
  422. c.XORKeyStream(payload, payload)
  423. case *tlsAead:
  424. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  425. b.resize(len(b.data) + c.Overhead())
  426. nonce := hc.outSeq[:]
  427. if c.explicitNonce {
  428. nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  429. }
  430. payload := b.data[recordHeaderLen+explicitIVLen:]
  431. payload = payload[:payloadLen]
  432. var additionalData [13]byte
  433. copy(additionalData[:], hc.outSeq[:])
  434. copy(additionalData[8:], b.data[:3])
  435. additionalData[11] = byte(payloadLen >> 8)
  436. additionalData[12] = byte(payloadLen)
  437. c.Seal(payload[:0], nonce, payload, additionalData[:])
  438. case cbcMode:
  439. blockSize := c.BlockSize()
  440. if explicitIVLen > 0 {
  441. c.SetIV(payload[:explicitIVLen])
  442. payload = payload[explicitIVLen:]
  443. }
  444. prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
  445. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  446. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  447. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  448. default:
  449. panic("unknown cipher type")
  450. }
  451. }
  452. // update length to include MAC and any block padding needed.
  453. n := len(b.data) - recordHeaderLen
  454. b.data[recordHeaderLen-2] = byte(n >> 8)
  455. b.data[recordHeaderLen-1] = byte(n)
  456. hc.incSeq(true)
  457. return true, 0
  458. }
  459. // A block is a simple data buffer.
  460. type block struct {
  461. data []byte
  462. off int // index for Read
  463. link *block
  464. }
  465. // resize resizes block to be n bytes, growing if necessary.
  466. func (b *block) resize(n int) {
  467. if n > cap(b.data) {
  468. b.reserve(n)
  469. }
  470. b.data = b.data[0:n]
  471. }
  472. // reserve makes sure that block contains a capacity of at least n bytes.
  473. func (b *block) reserve(n int) {
  474. if cap(b.data) >= n {
  475. return
  476. }
  477. m := cap(b.data)
  478. if m == 0 {
  479. m = 1024
  480. }
  481. for m < n {
  482. m *= 2
  483. }
  484. data := make([]byte, len(b.data), m)
  485. copy(data, b.data)
  486. b.data = data
  487. }
  488. // readFromUntil reads from r into b until b contains at least n bytes
  489. // or else returns an error.
  490. func (b *block) readFromUntil(r io.Reader, n int) error {
  491. // quick case
  492. if len(b.data) >= n {
  493. return nil
  494. }
  495. // read until have enough.
  496. b.reserve(n)
  497. for {
  498. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  499. b.data = b.data[0 : len(b.data)+m]
  500. if len(b.data) >= n {
  501. // TODO(bradfitz,agl): slightly suspicious
  502. // that we're throwing away r.Read's err here.
  503. break
  504. }
  505. if err != nil {
  506. return err
  507. }
  508. }
  509. return nil
  510. }
  511. func (b *block) Read(p []byte) (n int, err error) {
  512. n = copy(p, b.data[b.off:])
  513. b.off += n
  514. return
  515. }
  516. // newBlock allocates a new block, from hc's free list if possible.
  517. func (hc *halfConn) newBlock() *block {
  518. b := hc.bfree
  519. if b == nil {
  520. return new(block)
  521. }
  522. hc.bfree = b.link
  523. b.link = nil
  524. b.resize(0)
  525. return b
  526. }
  527. // freeBlock returns a block to hc's free list.
  528. // The protocol is such that each side only has a block or two on
  529. // its free list at a time, so there's no need to worry about
  530. // trimming the list, etc.
  531. func (hc *halfConn) freeBlock(b *block) {
  532. b.link = hc.bfree
  533. hc.bfree = b
  534. }
  535. // splitBlock splits a block after the first n bytes,
  536. // returning a block with those n bytes and a
  537. // block with the remainder. the latter may be nil.
  538. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  539. if len(b.data) <= n {
  540. return b, nil
  541. }
  542. bb := hc.newBlock()
  543. bb.resize(len(b.data) - n)
  544. copy(bb.data, b.data[n:])
  545. b.data = b.data[0:n]
  546. return b, bb
  547. }
  548. func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
  549. if c.isDTLS {
  550. return c.dtlsDoReadRecord(want)
  551. }
  552. recordHeaderLen := tlsRecordHeaderLen
  553. if c.rawInput == nil {
  554. c.rawInput = c.in.newBlock()
  555. }
  556. b := c.rawInput
  557. // Read header, payload.
  558. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  559. // RFC suggests that EOF without an alertCloseNotify is
  560. // an error, but popular web sites seem to do this,
  561. // so we can't make it an error.
  562. // if err == io.EOF {
  563. // err = io.ErrUnexpectedEOF
  564. // }
  565. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  566. c.in.setErrorLocked(err)
  567. }
  568. return 0, nil, err
  569. }
  570. typ := recordType(b.data[0])
  571. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  572. // start with a uint16 length where the MSB is set and the first record
  573. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  574. // an SSLv2 client.
  575. if want == recordTypeHandshake && typ == 0x80 {
  576. c.sendAlert(alertProtocolVersion)
  577. return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
  578. }
  579. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  580. n := int(b.data[3])<<8 | int(b.data[4])
  581. if c.haveVers {
  582. if vers != c.vers {
  583. c.sendAlert(alertProtocolVersion)
  584. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
  585. }
  586. } else {
  587. if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
  588. c.sendAlert(alertProtocolVersion)
  589. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
  590. }
  591. }
  592. if n > maxCiphertext {
  593. c.sendAlert(alertRecordOverflow)
  594. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
  595. }
  596. if !c.haveVers {
  597. // First message, be extra suspicious:
  598. // this might not be a TLS client.
  599. // Bail out before reading a full 'body', if possible.
  600. // The current max version is 3.1.
  601. // If the version is >= 16.0, it's probably not real.
  602. // Similarly, a clientHello message encodes in
  603. // well under a kilobyte. If the length is >= 12 kB,
  604. // it's probably not real.
  605. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
  606. c.sendAlert(alertUnexpectedMessage)
  607. return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
  608. }
  609. }
  610. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  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 0, nil, err
  618. }
  619. // Process message.
  620. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  621. ok, off, err := c.in.decrypt(b)
  622. if !ok {
  623. c.in.setErrorLocked(c.sendAlert(err))
  624. }
  625. b.off = off
  626. return typ, b, nil
  627. }
  628. // readRecord reads the next TLS record from the connection
  629. // and updates the record layer state.
  630. // c.in.Mutex <= L; c.input == nil.
  631. func (c *Conn) readRecord(want recordType) error {
  632. // Caller must be in sync with connection:
  633. // handshake data if handshake not yet completed,
  634. // else application data.
  635. switch want {
  636. default:
  637. c.sendAlert(alertInternalError)
  638. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  639. case recordTypeHandshake, recordTypeChangeCipherSpec:
  640. if c.handshakeComplete {
  641. c.sendAlert(alertInternalError)
  642. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
  643. }
  644. case recordTypeApplicationData:
  645. if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
  646. c.sendAlert(alertInternalError)
  647. return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
  648. }
  649. }
  650. Again:
  651. typ, b, err := c.doReadRecord(want)
  652. if err != nil {
  653. return err
  654. }
  655. data := b.data[b.off:]
  656. if len(data) > maxPlaintext {
  657. err := c.sendAlert(alertRecordOverflow)
  658. c.in.freeBlock(b)
  659. return c.in.setErrorLocked(err)
  660. }
  661. switch typ {
  662. default:
  663. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  664. case recordTypeAlert:
  665. if len(data) != 2 {
  666. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  667. break
  668. }
  669. if alert(data[1]) == alertCloseNotify {
  670. c.in.setErrorLocked(io.EOF)
  671. break
  672. }
  673. switch data[0] {
  674. case alertLevelWarning:
  675. // drop on the floor
  676. c.in.freeBlock(b)
  677. goto Again
  678. case alertLevelError:
  679. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  680. default:
  681. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  682. }
  683. case recordTypeChangeCipherSpec:
  684. if typ != want || len(data) != 1 || data[0] != 1 {
  685. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  686. break
  687. }
  688. err := c.in.changeCipherSpec(c.config)
  689. if err != nil {
  690. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  691. }
  692. case recordTypeApplicationData:
  693. if typ != want {
  694. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  695. break
  696. }
  697. c.input = b
  698. b = nil
  699. case recordTypeHandshake:
  700. // TODO(rsc): Should at least pick off connection close.
  701. if typ != want {
  702. // A client might need to process a HelloRequest from
  703. // the server, thus receiving a handshake message when
  704. // application data is expected is ok.
  705. if !c.isClient {
  706. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  707. }
  708. }
  709. c.hand.Write(data)
  710. }
  711. if b != nil {
  712. c.in.freeBlock(b)
  713. }
  714. return c.in.err
  715. }
  716. // sendAlert sends a TLS alert message.
  717. // c.out.Mutex <= L.
  718. func (c *Conn) sendAlertLocked(level byte, err alert) error {
  719. c.tmp[0] = level
  720. c.tmp[1] = byte(err)
  721. if c.config.Bugs.FragmentAlert {
  722. c.writeRecord(recordTypeAlert, c.tmp[0:1])
  723. c.writeRecord(recordTypeAlert, c.tmp[1:2])
  724. } else {
  725. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  726. }
  727. // Error alerts are fatal to the connection.
  728. if level == alertLevelError {
  729. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  730. }
  731. return nil
  732. }
  733. // sendAlert sends a TLS alert message.
  734. // L < c.out.Mutex.
  735. func (c *Conn) sendAlert(err alert) error {
  736. level := byte(alertLevelError)
  737. if err == alertNoRenegotiation || err == alertCloseNotify {
  738. level = alertLevelWarning
  739. }
  740. return c.SendAlert(level, err)
  741. }
  742. func (c *Conn) SendAlert(level byte, err alert) error {
  743. c.out.Lock()
  744. defer c.out.Unlock()
  745. return c.sendAlertLocked(level, err)
  746. }
  747. // writeV2Record writes a record for a V2ClientHello.
  748. func (c *Conn) writeV2Record(data []byte) (n int, err error) {
  749. record := make([]byte, 2+len(data))
  750. record[0] = uint8(len(data)>>8) | 0x80
  751. record[1] = uint8(len(data))
  752. copy(record[2:], data)
  753. return c.conn.Write(record)
  754. }
  755. // writeRecord writes a TLS record with the given type and payload
  756. // to the connection and updates the record layer state.
  757. // c.out.Mutex <= L.
  758. func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
  759. if c.isDTLS {
  760. return c.dtlsWriteRecord(typ, data)
  761. }
  762. recordHeaderLen := tlsRecordHeaderLen
  763. b := c.out.newBlock()
  764. first := true
  765. isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
  766. for len(data) > 0 || first {
  767. m := len(data)
  768. if m > maxPlaintext {
  769. m = maxPlaintext
  770. }
  771. if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
  772. m = c.config.Bugs.MaxHandshakeRecordLength
  773. // By default, do not fragment the client_version or
  774. // server_version, which are located in the first 6
  775. // bytes.
  776. if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
  777. m = 6
  778. }
  779. }
  780. explicitIVLen := 0
  781. explicitIVIsSeq := false
  782. first = false
  783. var cbc cbcMode
  784. if c.out.version >= VersionTLS11 {
  785. var ok bool
  786. if cbc, ok = c.out.cipher.(cbcMode); ok {
  787. explicitIVLen = cbc.BlockSize()
  788. }
  789. }
  790. if explicitIVLen == 0 {
  791. if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
  792. explicitIVLen = 8
  793. // The AES-GCM construction in TLS has an
  794. // explicit nonce so that the nonce can be
  795. // random. However, the nonce is only 8 bytes
  796. // which is too small for a secure, random
  797. // nonce. Therefore we use the sequence number
  798. // as the nonce.
  799. explicitIVIsSeq = true
  800. }
  801. }
  802. b.resize(recordHeaderLen + explicitIVLen + m)
  803. b.data[0] = byte(typ)
  804. vers := c.vers
  805. if vers == 0 {
  806. // Some TLS servers fail if the record version is
  807. // greater than TLS 1.0 for the initial ClientHello.
  808. vers = VersionTLS10
  809. }
  810. b.data[1] = byte(vers >> 8)
  811. b.data[2] = byte(vers)
  812. b.data[3] = byte(m >> 8)
  813. b.data[4] = byte(m)
  814. if explicitIVLen > 0 {
  815. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  816. if explicitIVIsSeq {
  817. copy(explicitIV, c.out.seq[:])
  818. } else {
  819. if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
  820. break
  821. }
  822. }
  823. }
  824. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  825. c.out.encrypt(b, explicitIVLen)
  826. _, err = c.conn.Write(b.data)
  827. if err != nil {
  828. break
  829. }
  830. n += m
  831. data = data[m:]
  832. }
  833. c.out.freeBlock(b)
  834. if typ == recordTypeChangeCipherSpec {
  835. err = c.out.changeCipherSpec(c.config)
  836. if err != nil {
  837. // Cannot call sendAlert directly,
  838. // because we already hold c.out.Mutex.
  839. c.tmp[0] = alertLevelError
  840. c.tmp[1] = byte(err.(alert))
  841. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  842. return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  843. }
  844. }
  845. return
  846. }
  847. func (c *Conn) doReadHandshake() ([]byte, error) {
  848. if c.isDTLS {
  849. return c.dtlsDoReadHandshake()
  850. }
  851. for c.hand.Len() < 4 {
  852. if err := c.in.err; err != nil {
  853. return nil, err
  854. }
  855. if err := c.readRecord(recordTypeHandshake); err != nil {
  856. return nil, err
  857. }
  858. }
  859. data := c.hand.Bytes()
  860. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  861. if n > maxHandshake {
  862. return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
  863. }
  864. for c.hand.Len() < 4+n {
  865. if err := c.in.err; err != nil {
  866. return nil, err
  867. }
  868. if err := c.readRecord(recordTypeHandshake); err != nil {
  869. return nil, err
  870. }
  871. }
  872. return c.hand.Next(4 + n), nil
  873. }
  874. // readHandshake reads the next handshake message from
  875. // the record layer.
  876. // c.in.Mutex < L; c.out.Mutex < L.
  877. func (c *Conn) readHandshake() (interface{}, error) {
  878. data, err := c.doReadHandshake()
  879. if err != nil {
  880. return nil, err
  881. }
  882. var m handshakeMessage
  883. switch data[0] {
  884. case typeHelloRequest:
  885. m = new(helloRequestMsg)
  886. case typeClientHello:
  887. m = &clientHelloMsg{
  888. isDTLS: c.isDTLS,
  889. }
  890. case typeServerHello:
  891. m = &serverHelloMsg{
  892. isDTLS: c.isDTLS,
  893. }
  894. case typeNewSessionTicket:
  895. m = new(newSessionTicketMsg)
  896. case typeCertificate:
  897. m = new(certificateMsg)
  898. case typeCertificateRequest:
  899. m = &certificateRequestMsg{
  900. hasSignatureAndHash: c.vers >= VersionTLS12,
  901. }
  902. case typeCertificateStatus:
  903. m = new(certificateStatusMsg)
  904. case typeServerKeyExchange:
  905. m = new(serverKeyExchangeMsg)
  906. case typeServerHelloDone:
  907. m = new(serverHelloDoneMsg)
  908. case typeClientKeyExchange:
  909. m = new(clientKeyExchangeMsg)
  910. case typeCertificateVerify:
  911. m = &certificateVerifyMsg{
  912. hasSignatureAndHash: c.vers >= VersionTLS12,
  913. }
  914. case typeNextProtocol:
  915. m = new(nextProtoMsg)
  916. case typeFinished:
  917. m = new(finishedMsg)
  918. case typeHelloVerifyRequest:
  919. m = new(helloVerifyRequestMsg)
  920. case typeEncryptedExtensions:
  921. m = new(encryptedExtensionsMsg)
  922. default:
  923. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  924. }
  925. // The handshake message unmarshallers
  926. // expect to be able to keep references to data,
  927. // so pass in a fresh copy that won't be overwritten.
  928. data = append([]byte(nil), data...)
  929. if !m.unmarshal(data) {
  930. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  931. }
  932. return m, nil
  933. }
  934. // skipPacket processes all the DTLS records in packet. It updates
  935. // sequence number expectations but otherwise ignores them.
  936. func (c *Conn) skipPacket(packet []byte) error {
  937. for len(packet) > 0 {
  938. // Dropped packets are completely ignored save to update
  939. // expected sequence numbers for this and the next epoch. (We
  940. // don't assert on the contents of the packets both for
  941. // simplicity and because a previous test with one shorter
  942. // timeout schedule would have done so.)
  943. epoch := packet[3:5]
  944. seq := packet[5:11]
  945. length := uint16(packet[11])<<8 | uint16(packet[12])
  946. if bytes.Equal(c.in.seq[:2], epoch) {
  947. if !bytes.Equal(c.in.seq[2:], seq) {
  948. return errors.New("tls: sequence mismatch")
  949. }
  950. c.in.incSeq(false)
  951. } else {
  952. if !bytes.Equal(c.in.nextSeq[:], seq) {
  953. return errors.New("tls: sequence mismatch")
  954. }
  955. c.in.incNextSeq()
  956. }
  957. packet = packet[13+length:]
  958. }
  959. return nil
  960. }
  961. // simulatePacketLoss simulates the loss of a handshake leg from the
  962. // peer based on the schedule in c.config.Bugs. If resendFunc is
  963. // non-nil, it is called after each simulated timeout to retransmit
  964. // handshake messages from the local end. This is used in cases where
  965. // the peer retransmits on a stale Finished rather than a timeout.
  966. func (c *Conn) simulatePacketLoss(resendFunc func()) error {
  967. if len(c.config.Bugs.TimeoutSchedule) == 0 {
  968. return nil
  969. }
  970. if !c.isDTLS {
  971. return errors.New("tls: TimeoutSchedule may only be set in DTLS")
  972. }
  973. if c.config.Bugs.PacketAdaptor == nil {
  974. return errors.New("tls: TimeoutSchedule set without PacketAdapter")
  975. }
  976. for _, timeout := range c.config.Bugs.TimeoutSchedule {
  977. // Simulate a timeout.
  978. packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
  979. if err != nil {
  980. return err
  981. }
  982. for _, packet := range packets {
  983. if err := c.skipPacket(packet); err != nil {
  984. return err
  985. }
  986. }
  987. if resendFunc != nil {
  988. resendFunc()
  989. }
  990. }
  991. return nil
  992. }
  993. // Write writes data to the connection.
  994. func (c *Conn) Write(b []byte) (int, error) {
  995. if err := c.Handshake(); err != nil {
  996. return 0, err
  997. }
  998. c.out.Lock()
  999. defer c.out.Unlock()
  1000. if err := c.out.err; err != nil {
  1001. return 0, err
  1002. }
  1003. if !c.handshakeComplete {
  1004. return 0, alertInternalError
  1005. }
  1006. if c.config.Bugs.SendSpuriousAlert != 0 {
  1007. c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
  1008. }
  1009. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1010. // attack when using block mode ciphers due to predictable IVs.
  1011. // This can be prevented by splitting each Application Data
  1012. // record into two records, effectively randomizing the IV.
  1013. //
  1014. // http://www.openssl.org/~bodo/tls-cbc.txt
  1015. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1016. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1017. var m int
  1018. if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
  1019. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1020. n, err := c.writeRecord(recordTypeApplicationData, b[:1])
  1021. if err != nil {
  1022. return n, c.out.setErrorLocked(err)
  1023. }
  1024. m, b = 1, b[1:]
  1025. }
  1026. }
  1027. n, err := c.writeRecord(recordTypeApplicationData, b)
  1028. return n + m, c.out.setErrorLocked(err)
  1029. }
  1030. func (c *Conn) handleRenegotiation() error {
  1031. c.handshakeComplete = false
  1032. if !c.isClient {
  1033. panic("renegotiation should only happen for a client")
  1034. }
  1035. msg, err := c.readHandshake()
  1036. if err != nil {
  1037. return err
  1038. }
  1039. _, ok := msg.(*helloRequestMsg)
  1040. if !ok {
  1041. c.sendAlert(alertUnexpectedMessage)
  1042. return alertUnexpectedMessage
  1043. }
  1044. return c.Handshake()
  1045. }
  1046. func (c *Conn) Renegotiate() error {
  1047. if !c.isClient {
  1048. helloReq := new(helloRequestMsg)
  1049. c.writeRecord(recordTypeHandshake, helloReq.marshal())
  1050. }
  1051. c.handshakeComplete = false
  1052. return c.Handshake()
  1053. }
  1054. // Read can be made to time out and return a net.Error with Timeout() == true
  1055. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1056. func (c *Conn) Read(b []byte) (n int, err error) {
  1057. if err = c.Handshake(); err != nil {
  1058. return
  1059. }
  1060. c.in.Lock()
  1061. defer c.in.Unlock()
  1062. // Some OpenSSL servers send empty records in order to randomize the
  1063. // CBC IV. So this loop ignores a limited number of empty records.
  1064. const maxConsecutiveEmptyRecords = 100
  1065. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1066. for c.input == nil && c.in.err == nil {
  1067. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1068. // Soft error, like EAGAIN
  1069. return 0, err
  1070. }
  1071. if c.hand.Len() > 0 {
  1072. // We received handshake bytes, indicating the
  1073. // start of a renegotiation.
  1074. if err := c.handleRenegotiation(); err != nil {
  1075. return 0, err
  1076. }
  1077. continue
  1078. }
  1079. }
  1080. if err := c.in.err; err != nil {
  1081. return 0, err
  1082. }
  1083. n, err = c.input.Read(b)
  1084. if c.input.off >= len(c.input.data) || c.isDTLS {
  1085. c.in.freeBlock(c.input)
  1086. c.input = nil
  1087. }
  1088. // If a close-notify alert is waiting, read it so that
  1089. // we can return (n, EOF) instead of (n, nil), to signal
  1090. // to the HTTP response reading goroutine that the
  1091. // connection is now closed. This eliminates a race
  1092. // where the HTTP response reading goroutine would
  1093. // otherwise not observe the EOF until its next read,
  1094. // by which time a client goroutine might have already
  1095. // tried to reuse the HTTP connection for a new
  1096. // request.
  1097. // See https://codereview.appspot.com/76400046
  1098. // and http://golang.org/issue/3514
  1099. if ri := c.rawInput; ri != nil &&
  1100. n != 0 && err == nil &&
  1101. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1102. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1103. err = recErr // will be io.EOF on closeNotify
  1104. }
  1105. }
  1106. if n != 0 || err != nil {
  1107. return n, err
  1108. }
  1109. }
  1110. return 0, io.ErrNoProgress
  1111. }
  1112. // Close closes the connection.
  1113. func (c *Conn) Close() error {
  1114. var alertErr error
  1115. c.handshakeMutex.Lock()
  1116. defer c.handshakeMutex.Unlock()
  1117. if c.handshakeComplete {
  1118. alertErr = c.sendAlert(alertCloseNotify)
  1119. }
  1120. if err := c.conn.Close(); err != nil {
  1121. return err
  1122. }
  1123. return alertErr
  1124. }
  1125. // Handshake runs the client or server handshake
  1126. // protocol if it has not yet been run.
  1127. // Most uses of this package need not call Handshake
  1128. // explicitly: the first Read or Write will call it automatically.
  1129. func (c *Conn) Handshake() error {
  1130. c.handshakeMutex.Lock()
  1131. defer c.handshakeMutex.Unlock()
  1132. if err := c.handshakeErr; err != nil {
  1133. return err
  1134. }
  1135. if c.handshakeComplete {
  1136. return nil
  1137. }
  1138. if c.isDTLS && c.config.Bugs.SendSplitAlert {
  1139. c.conn.Write([]byte{
  1140. byte(recordTypeAlert), // type
  1141. 0xfe, 0xff, // version
  1142. 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
  1143. 0x0, 0x2, // length
  1144. })
  1145. c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
  1146. }
  1147. if c.isClient {
  1148. c.handshakeErr = c.clientHandshake()
  1149. } else {
  1150. c.handshakeErr = c.serverHandshake()
  1151. }
  1152. if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
  1153. c.writeRecord(recordType(42), []byte("invalid record"))
  1154. }
  1155. return c.handshakeErr
  1156. }
  1157. // ConnectionState returns basic TLS details about the connection.
  1158. func (c *Conn) ConnectionState() ConnectionState {
  1159. c.handshakeMutex.Lock()
  1160. defer c.handshakeMutex.Unlock()
  1161. var state ConnectionState
  1162. state.HandshakeComplete = c.handshakeComplete
  1163. if c.handshakeComplete {
  1164. state.Version = c.vers
  1165. state.NegotiatedProtocol = c.clientProtocol
  1166. state.DidResume = c.didResume
  1167. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1168. state.NegotiatedProtocolFromALPN = c.usedALPN
  1169. state.CipherSuite = c.cipherSuite.id
  1170. state.PeerCertificates = c.peerCertificates
  1171. state.VerifiedChains = c.verifiedChains
  1172. state.ServerName = c.serverName
  1173. state.ChannelID = c.channelID
  1174. state.SRTPProtectionProfile = c.srtpProtectionProfile
  1175. state.TLSUnique = c.firstFinished[:]
  1176. }
  1177. return state
  1178. }
  1179. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1180. // any. (Only valid for client connections.)
  1181. func (c *Conn) OCSPResponse() []byte {
  1182. c.handshakeMutex.Lock()
  1183. defer c.handshakeMutex.Unlock()
  1184. return c.ocspResponse
  1185. }
  1186. // VerifyHostname checks that the peer certificate chain is valid for
  1187. // connecting to host. If so, it returns nil; if not, it returns an error
  1188. // describing the problem.
  1189. func (c *Conn) VerifyHostname(host string) error {
  1190. c.handshakeMutex.Lock()
  1191. defer c.handshakeMutex.Unlock()
  1192. if !c.isClient {
  1193. return errors.New("tls: VerifyHostname called on TLS server connection")
  1194. }
  1195. if !c.handshakeComplete {
  1196. return errors.New("tls: handshake has not yet been performed")
  1197. }
  1198. return c.peerCertificates[0].VerifyHostname(host)
  1199. }
  1200. // ExportKeyingMaterial exports keying material from the current connection
  1201. // state, as per RFC 5705.
  1202. func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
  1203. c.handshakeMutex.Lock()
  1204. defer c.handshakeMutex.Unlock()
  1205. if !c.handshakeComplete {
  1206. return nil, errors.New("tls: handshake has not yet been performed")
  1207. }
  1208. seedLen := len(c.clientRandom) + len(c.serverRandom)
  1209. if useContext {
  1210. seedLen += 2 + len(context)
  1211. }
  1212. seed := make([]byte, 0, seedLen)
  1213. seed = append(seed, c.clientRandom[:]...)
  1214. seed = append(seed, c.serverRandom[:]...)
  1215. if useContext {
  1216. seed = append(seed, byte(len(context)>>8), byte(len(context)))
  1217. seed = append(seed, context...)
  1218. }
  1219. result := make([]byte, length)
  1220. prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
  1221. return result, nil
  1222. }