Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

handshake_server.go 31 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>
pirms 9 gadiem
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>
pirms 9 gadiem
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>
pirms 9 gadiem
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>
pirms 9 gadiem
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>
pirms 9 gadiem
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>
pirms 9 gadiem
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>
pirms 9 gadiem
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. // Copyright 2009 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. package main
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rsa"
  11. "crypto/subtle"
  12. "crypto/x509"
  13. "encoding/asn1"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "math/big"
  18. )
  19. // serverHandshakeState contains details of a server handshake in progress.
  20. // It's discarded once the handshake has completed.
  21. type serverHandshakeState struct {
  22. c *Conn
  23. clientHello *clientHelloMsg
  24. hello *serverHelloMsg
  25. suite *cipherSuite
  26. ellipticOk bool
  27. ecdsaOk bool
  28. sessionState *sessionState
  29. finishedHash finishedHash
  30. masterSecret []byte
  31. certsFromClient [][]byte
  32. cert *Certificate
  33. finishedBytes []byte
  34. }
  35. // serverHandshake performs a TLS handshake as a server.
  36. func (c *Conn) serverHandshake() error {
  37. config := c.config
  38. // If this is the first server handshake, we generate a random key to
  39. // encrypt the tickets with.
  40. config.serverInitOnce.Do(config.serverInit)
  41. c.sendHandshakeSeq = 0
  42. c.recvHandshakeSeq = 0
  43. hs := serverHandshakeState{
  44. c: c,
  45. }
  46. isResume, err := hs.readClientHello()
  47. if err != nil {
  48. return err
  49. }
  50. // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
  51. if isResume {
  52. // The client has included a session ticket and so we do an abbreviated handshake.
  53. if err := hs.doResumeHandshake(); err != nil {
  54. return err
  55. }
  56. if err := hs.establishKeys(); err != nil {
  57. return err
  58. }
  59. if c.config.Bugs.RenewTicketOnResume {
  60. if err := hs.sendSessionTicket(); err != nil {
  61. return err
  62. }
  63. }
  64. if err := hs.sendFinished(c.firstFinished[:]); err != nil {
  65. return err
  66. }
  67. // Most retransmits are triggered by a timeout, but the final
  68. // leg of the handshake is retransmited upon re-receiving a
  69. // Finished.
  70. if err := c.simulatePacketLoss(func() {
  71. c.writeRecord(recordTypeHandshake, hs.finishedBytes)
  72. c.dtlsFlushHandshake()
  73. }); err != nil {
  74. return err
  75. }
  76. if err := hs.readFinished(nil, isResume); err != nil {
  77. return err
  78. }
  79. c.didResume = true
  80. } else {
  81. // The client didn't include a session ticket, or it wasn't
  82. // valid so we do a full handshake.
  83. if err := hs.doFullHandshake(); err != nil {
  84. return err
  85. }
  86. if err := hs.establishKeys(); err != nil {
  87. return err
  88. }
  89. if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
  90. return err
  91. }
  92. if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
  93. c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
  94. }
  95. if c.config.Bugs.ExpectFalseStart {
  96. if err := c.readRecord(recordTypeApplicationData); err != nil {
  97. return fmt.Errorf("tls: peer did not false start: %s", err)
  98. }
  99. }
  100. if err := hs.sendSessionTicket(); err != nil {
  101. return err
  102. }
  103. if err := hs.sendFinished(nil); err != nil {
  104. return err
  105. }
  106. }
  107. c.handshakeComplete = true
  108. copy(c.clientRandom[:], hs.clientHello.random)
  109. copy(c.serverRandom[:], hs.hello.random)
  110. copy(c.masterSecret[:], hs.masterSecret)
  111. return nil
  112. }
  113. // readClientHello reads a ClientHello message from the client and decides
  114. // whether we will perform session resumption.
  115. func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
  116. config := hs.c.config
  117. c := hs.c
  118. if err := c.simulatePacketLoss(nil); err != nil {
  119. return false, err
  120. }
  121. msg, err := c.readHandshake()
  122. if err != nil {
  123. return false, err
  124. }
  125. var ok bool
  126. hs.clientHello, ok = msg.(*clientHelloMsg)
  127. if !ok {
  128. c.sendAlert(alertUnexpectedMessage)
  129. return false, unexpectedMessageError(hs.clientHello, msg)
  130. }
  131. if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
  132. return false, fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
  133. }
  134. if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
  135. // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
  136. // be always DTLS 1.0
  137. helloVerifyRequest := &helloVerifyRequestMsg{
  138. vers: VersionTLS10,
  139. cookie: make([]byte, 32),
  140. }
  141. if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
  142. c.sendAlert(alertInternalError)
  143. return false, errors.New("dtls: short read from Rand: " + err.Error())
  144. }
  145. c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
  146. c.dtlsFlushHandshake()
  147. if err := c.simulatePacketLoss(nil); err != nil {
  148. return false, err
  149. }
  150. msg, err := c.readHandshake()
  151. if err != nil {
  152. return false, err
  153. }
  154. newClientHello, ok := msg.(*clientHelloMsg)
  155. if !ok {
  156. c.sendAlert(alertUnexpectedMessage)
  157. return false, unexpectedMessageError(hs.clientHello, msg)
  158. }
  159. if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
  160. return false, errors.New("dtls: invalid cookie")
  161. }
  162. // Apart from the cookie, the two ClientHellos must
  163. // match. Note that clientHello.equal compares the
  164. // serialization, so we make a copy.
  165. oldClientHelloCopy := *hs.clientHello
  166. oldClientHelloCopy.raw = nil
  167. oldClientHelloCopy.cookie = nil
  168. newClientHelloCopy := *newClientHello
  169. newClientHelloCopy.raw = nil
  170. newClientHelloCopy.cookie = nil
  171. if !oldClientHelloCopy.equal(&newClientHelloCopy) {
  172. return false, errors.New("dtls: retransmitted ClientHello does not match")
  173. }
  174. hs.clientHello = newClientHello
  175. }
  176. if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
  177. if c.clientVersion != hs.clientHello.vers {
  178. return false, fmt.Errorf("tls: client offered different version on renego")
  179. }
  180. }
  181. c.clientVersion = hs.clientHello.vers
  182. // Reject < 1.2 ClientHellos with signature_algorithms.
  183. if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
  184. return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
  185. }
  186. if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
  187. hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
  188. }
  189. c.vers, ok = config.mutualVersion(hs.clientHello.vers)
  190. if !ok {
  191. c.sendAlert(alertProtocolVersion)
  192. return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
  193. }
  194. c.haveVers = true
  195. hs.hello = &serverHelloMsg{
  196. isDTLS: c.isDTLS,
  197. customExtension: config.Bugs.CustomExtension,
  198. }
  199. supportedCurve := false
  200. preferredCurves := config.curvePreferences()
  201. if config.Bugs.IgnorePeerCurvePreferences {
  202. hs.clientHello.supportedCurves = preferredCurves
  203. }
  204. Curves:
  205. for _, curve := range hs.clientHello.supportedCurves {
  206. for _, supported := range preferredCurves {
  207. if supported == curve {
  208. supportedCurve = true
  209. break Curves
  210. }
  211. }
  212. }
  213. supportedPointFormat := false
  214. for _, pointFormat := range hs.clientHello.supportedPoints {
  215. if pointFormat == pointFormatUncompressed {
  216. supportedPointFormat = true
  217. break
  218. }
  219. }
  220. hs.ellipticOk = supportedCurve && supportedPointFormat
  221. foundCompression := false
  222. // We only support null compression, so check that the client offered it.
  223. for _, compression := range hs.clientHello.compressionMethods {
  224. if compression == compressionNone {
  225. foundCompression = true
  226. break
  227. }
  228. }
  229. if !foundCompression {
  230. c.sendAlert(alertHandshakeFailure)
  231. return false, errors.New("tls: client does not support uncompressed connections")
  232. }
  233. hs.hello.vers = c.vers
  234. hs.hello.random = make([]byte, 32)
  235. _, err = io.ReadFull(config.rand(), hs.hello.random)
  236. if err != nil {
  237. c.sendAlert(alertInternalError)
  238. return false, err
  239. }
  240. if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
  241. c.sendAlert(alertHandshakeFailure)
  242. return false, errors.New("tls: renegotiation mismatch")
  243. }
  244. if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
  245. hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
  246. hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
  247. if c.config.Bugs.BadRenegotiationInfo {
  248. hs.hello.secureRenegotiation[0] ^= 0x80
  249. }
  250. } else {
  251. hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
  252. }
  253. if c.config.Bugs.NoRenegotiationInfo {
  254. hs.hello.secureRenegotiation = nil
  255. }
  256. hs.hello.compressionMethod = compressionNone
  257. hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
  258. if len(hs.clientHello.serverName) > 0 {
  259. c.serverName = hs.clientHello.serverName
  260. }
  261. if len(hs.clientHello.alpnProtocols) > 0 {
  262. if proto := c.config.Bugs.ALPNProtocol; proto != nil {
  263. hs.hello.alpnProtocol = *proto
  264. hs.hello.alpnProtocolEmpty = len(*proto) == 0
  265. c.clientProtocol = *proto
  266. c.usedALPN = true
  267. } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
  268. hs.hello.alpnProtocol = selectedProto
  269. c.clientProtocol = selectedProto
  270. c.usedALPN = true
  271. }
  272. } else {
  273. // Although sending an empty NPN extension is reasonable, Firefox has
  274. // had a bug around this. Best to send nothing at all if
  275. // config.NextProtos is empty. See
  276. // https://code.google.com/p/go/issues/detail?id=5445.
  277. if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
  278. hs.hello.nextProtoNeg = true
  279. hs.hello.nextProtos = config.NextProtos
  280. }
  281. }
  282. hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
  283. if len(config.Certificates) == 0 {
  284. c.sendAlert(alertInternalError)
  285. return false, errors.New("tls: no certificates configured")
  286. }
  287. hs.cert = &config.Certificates[0]
  288. if len(hs.clientHello.serverName) > 0 {
  289. hs.cert = config.getCertificateForName(hs.clientHello.serverName)
  290. }
  291. if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
  292. return false, errors.New("tls: unexpected server name")
  293. }
  294. if hs.clientHello.channelIDSupported && config.RequestChannelID {
  295. hs.hello.channelIDRequested = true
  296. }
  297. if hs.clientHello.srtpProtectionProfiles != nil {
  298. SRTPLoop:
  299. for _, p1 := range c.config.SRTPProtectionProfiles {
  300. for _, p2 := range hs.clientHello.srtpProtectionProfiles {
  301. if p1 == p2 {
  302. hs.hello.srtpProtectionProfile = p1
  303. c.srtpProtectionProfile = p1
  304. break SRTPLoop
  305. }
  306. }
  307. }
  308. }
  309. if c.config.Bugs.SendSRTPProtectionProfile != 0 {
  310. hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
  311. }
  312. if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
  313. if hs.clientHello.customExtension != *expected {
  314. return false, fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
  315. }
  316. }
  317. _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
  318. // For test purposes, check that the peer never offers a session when
  319. // renegotiating.
  320. if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
  321. return false, errors.New("tls: offered resumption on renegotiation")
  322. }
  323. if hs.checkForResumption() {
  324. return true, nil
  325. }
  326. var scsvFound bool
  327. for _, cipherSuite := range hs.clientHello.cipherSuites {
  328. if cipherSuite == fallbackSCSV {
  329. scsvFound = true
  330. break
  331. }
  332. }
  333. if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
  334. return false, errors.New("tls: no fallback SCSV found when expected")
  335. } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
  336. return false, errors.New("tls: fallback SCSV found when not expected")
  337. }
  338. if config.Bugs.IgnorePeerCipherPreferences {
  339. hs.clientHello.cipherSuites = c.config.cipherSuites()
  340. }
  341. var preferenceList, supportedList []uint16
  342. if c.config.PreferServerCipherSuites {
  343. preferenceList = c.config.cipherSuites()
  344. supportedList = hs.clientHello.cipherSuites
  345. } else {
  346. preferenceList = hs.clientHello.cipherSuites
  347. supportedList = c.config.cipherSuites()
  348. }
  349. for _, id := range preferenceList {
  350. if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
  351. break
  352. }
  353. }
  354. if hs.suite == nil {
  355. c.sendAlert(alertHandshakeFailure)
  356. return false, errors.New("tls: no cipher suite supported by both client and server")
  357. }
  358. return false, nil
  359. }
  360. // checkForResumption returns true if we should perform resumption on this connection.
  361. func (hs *serverHandshakeState) checkForResumption() bool {
  362. c := hs.c
  363. if len(hs.clientHello.sessionTicket) > 0 {
  364. if c.config.SessionTicketsDisabled {
  365. return false
  366. }
  367. var ok bool
  368. if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
  369. return false
  370. }
  371. } else {
  372. if c.config.ServerSessionCache == nil {
  373. return false
  374. }
  375. var ok bool
  376. sessionId := string(hs.clientHello.sessionId)
  377. if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
  378. return false
  379. }
  380. }
  381. // Never resume a session for a different SSL version.
  382. if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
  383. return false
  384. }
  385. cipherSuiteOk := false
  386. // Check that the client is still offering the ciphersuite in the session.
  387. for _, id := range hs.clientHello.cipherSuites {
  388. if id == hs.sessionState.cipherSuite {
  389. cipherSuiteOk = true
  390. break
  391. }
  392. }
  393. if !cipherSuiteOk {
  394. return false
  395. }
  396. // Check that we also support the ciphersuite from the session.
  397. hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
  398. if hs.suite == nil {
  399. return false
  400. }
  401. sessionHasClientCerts := len(hs.sessionState.certificates) != 0
  402. needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
  403. if needClientCerts && !sessionHasClientCerts {
  404. return false
  405. }
  406. if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
  407. return false
  408. }
  409. return true
  410. }
  411. func (hs *serverHandshakeState) doResumeHandshake() error {
  412. c := hs.c
  413. hs.hello.cipherSuite = hs.suite.id
  414. if c.config.Bugs.SendCipherSuite != 0 {
  415. hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
  416. }
  417. // We echo the client's session ID in the ServerHello to let it know
  418. // that we're doing a resumption.
  419. hs.hello.sessionId = hs.clientHello.sessionId
  420. hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
  421. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  422. hs.finishedHash.discardHandshakeBuffer()
  423. hs.writeClientHash(hs.clientHello.marshal())
  424. hs.writeServerHash(hs.hello.marshal())
  425. c.writeRecord(recordTypeHandshake, hs.hello.marshal())
  426. if len(hs.sessionState.certificates) > 0 {
  427. if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
  428. return err
  429. }
  430. }
  431. hs.masterSecret = hs.sessionState.masterSecret
  432. c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
  433. return nil
  434. }
  435. func (hs *serverHandshakeState) doFullHandshake() error {
  436. config := hs.c.config
  437. c := hs.c
  438. isPSK := hs.suite.flags&suitePSK != 0
  439. if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  440. hs.hello.ocspStapling = true
  441. }
  442. if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
  443. hs.hello.sctList = hs.cert.SignedCertificateTimestampList
  444. }
  445. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
  446. hs.hello.cipherSuite = hs.suite.id
  447. if config.Bugs.SendCipherSuite != 0 {
  448. hs.hello.cipherSuite = config.Bugs.SendCipherSuite
  449. }
  450. c.extendedMasterSecret = hs.hello.extendedMasterSecret
  451. // Generate a session ID if we're to save the session.
  452. if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
  453. hs.hello.sessionId = make([]byte, 32)
  454. if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
  455. c.sendAlert(alertInternalError)
  456. return errors.New("tls: short read from Rand: " + err.Error())
  457. }
  458. }
  459. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  460. hs.writeClientHash(hs.clientHello.marshal())
  461. hs.writeServerHash(hs.hello.marshal())
  462. c.writeRecord(recordTypeHandshake, hs.hello.marshal())
  463. if !isPSK {
  464. certMsg := new(certificateMsg)
  465. if !config.Bugs.EmptyCertificateList {
  466. certMsg.certificates = hs.cert.Certificate
  467. }
  468. if !config.Bugs.UnauthenticatedECDH {
  469. certMsgBytes := certMsg.marshal()
  470. if config.Bugs.WrongCertificateMessageType {
  471. certMsgBytes[0] += 42
  472. }
  473. hs.writeServerHash(certMsgBytes)
  474. c.writeRecord(recordTypeHandshake, certMsgBytes)
  475. }
  476. }
  477. if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
  478. certStatus := new(certificateStatusMsg)
  479. certStatus.statusType = statusTypeOCSP
  480. certStatus.response = hs.cert.OCSPStaple
  481. hs.writeServerHash(certStatus.marshal())
  482. c.writeRecord(recordTypeHandshake, certStatus.marshal())
  483. }
  484. keyAgreement := hs.suite.ka(c.vers)
  485. skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
  486. if err != nil {
  487. c.sendAlert(alertHandshakeFailure)
  488. return err
  489. }
  490. if skx != nil && !config.Bugs.SkipServerKeyExchange {
  491. hs.writeServerHash(skx.marshal())
  492. c.writeRecord(recordTypeHandshake, skx.marshal())
  493. }
  494. if config.ClientAuth >= RequestClientCert {
  495. // Request a client certificate
  496. certReq := &certificateRequestMsg{
  497. certificateTypes: config.ClientCertificateTypes,
  498. }
  499. if certReq.certificateTypes == nil {
  500. certReq.certificateTypes = []byte{
  501. byte(CertTypeRSASign),
  502. byte(CertTypeECDSASign),
  503. }
  504. }
  505. if c.vers >= VersionTLS12 {
  506. certReq.hasSignatureAndHash = true
  507. if !config.Bugs.NoSignatureAndHashes {
  508. certReq.signatureAndHashes = config.signatureAndHashesForServer()
  509. }
  510. }
  511. // An empty list of certificateAuthorities signals to
  512. // the client that it may send any certificate in response
  513. // to our request. When we know the CAs we trust, then
  514. // we can send them down, so that the client can choose
  515. // an appropriate certificate to give to us.
  516. if config.ClientCAs != nil {
  517. certReq.certificateAuthorities = config.ClientCAs.Subjects()
  518. }
  519. hs.writeServerHash(certReq.marshal())
  520. c.writeRecord(recordTypeHandshake, certReq.marshal())
  521. }
  522. helloDone := new(serverHelloDoneMsg)
  523. hs.writeServerHash(helloDone.marshal())
  524. c.writeRecord(recordTypeHandshake, helloDone.marshal())
  525. c.dtlsFlushHandshake()
  526. var pub crypto.PublicKey // public key for client auth, if any
  527. if err := c.simulatePacketLoss(nil); err != nil {
  528. return err
  529. }
  530. msg, err := c.readHandshake()
  531. if err != nil {
  532. return err
  533. }
  534. var ok bool
  535. // If we requested a client certificate, then the client must send a
  536. // certificate message, even if it's empty.
  537. if config.ClientAuth >= RequestClientCert {
  538. var certMsg *certificateMsg
  539. if certMsg, ok = msg.(*certificateMsg); !ok {
  540. c.sendAlert(alertUnexpectedMessage)
  541. return unexpectedMessageError(certMsg, msg)
  542. }
  543. hs.writeClientHash(certMsg.marshal())
  544. if len(certMsg.certificates) == 0 {
  545. // The client didn't actually send a certificate
  546. switch config.ClientAuth {
  547. case RequireAnyClientCert, RequireAndVerifyClientCert:
  548. c.sendAlert(alertBadCertificate)
  549. return errors.New("tls: client didn't provide a certificate")
  550. }
  551. }
  552. pub, err = hs.processCertsFromClient(certMsg.certificates)
  553. if err != nil {
  554. return err
  555. }
  556. msg, err = c.readHandshake()
  557. if err != nil {
  558. return err
  559. }
  560. }
  561. // Get client key exchange
  562. ckx, ok := msg.(*clientKeyExchangeMsg)
  563. if !ok {
  564. c.sendAlert(alertUnexpectedMessage)
  565. return unexpectedMessageError(ckx, msg)
  566. }
  567. hs.writeClientHash(ckx.marshal())
  568. preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
  569. if err != nil {
  570. c.sendAlert(alertHandshakeFailure)
  571. return err
  572. }
  573. if c.extendedMasterSecret {
  574. hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
  575. } else {
  576. if c.config.Bugs.RequireExtendedMasterSecret {
  577. return errors.New("tls: extended master secret required but not supported by peer")
  578. }
  579. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
  580. }
  581. // If we received a client cert in response to our certificate request message,
  582. // the client will send us a certificateVerifyMsg immediately after the
  583. // clientKeyExchangeMsg. This message is a digest of all preceding
  584. // handshake-layer messages that is signed using the private key corresponding
  585. // to the client's certificate. This allows us to verify that the client is in
  586. // possession of the private key of the certificate.
  587. if len(c.peerCertificates) > 0 {
  588. msg, err = c.readHandshake()
  589. if err != nil {
  590. return err
  591. }
  592. certVerify, ok := msg.(*certificateVerifyMsg)
  593. if !ok {
  594. c.sendAlert(alertUnexpectedMessage)
  595. return unexpectedMessageError(certVerify, msg)
  596. }
  597. // Determine the signature type.
  598. var signatureAndHash signatureAndHash
  599. if certVerify.hasSignatureAndHash {
  600. signatureAndHash = certVerify.signatureAndHash
  601. if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
  602. return errors.New("tls: unsupported hash function for client certificate")
  603. }
  604. } else {
  605. // Before TLS 1.2 the signature algorithm was implicit
  606. // from the key type, and only one hash per signature
  607. // algorithm was possible. Leave the hash as zero.
  608. switch pub.(type) {
  609. case *ecdsa.PublicKey:
  610. signatureAndHash.signature = signatureECDSA
  611. case *rsa.PublicKey:
  612. signatureAndHash.signature = signatureRSA
  613. }
  614. }
  615. switch key := pub.(type) {
  616. case *ecdsa.PublicKey:
  617. if signatureAndHash.signature != signatureECDSA {
  618. err = errors.New("tls: bad signature type for client's ECDSA certificate")
  619. break
  620. }
  621. ecdsaSig := new(ecdsaSignature)
  622. if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
  623. break
  624. }
  625. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  626. err = errors.New("ECDSA signature contained zero or negative values")
  627. break
  628. }
  629. var digest []byte
  630. digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
  631. if err != nil {
  632. break
  633. }
  634. if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
  635. err = errors.New("ECDSA verification failure")
  636. break
  637. }
  638. case *rsa.PublicKey:
  639. if signatureAndHash.signature != signatureRSA {
  640. err = errors.New("tls: bad signature type for client's RSA certificate")
  641. break
  642. }
  643. var digest []byte
  644. var hashFunc crypto.Hash
  645. digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
  646. if err != nil {
  647. break
  648. }
  649. err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
  650. }
  651. if err != nil {
  652. c.sendAlert(alertBadCertificate)
  653. return errors.New("could not validate signature of connection nonces: " + err.Error())
  654. }
  655. hs.writeClientHash(certVerify.marshal())
  656. }
  657. hs.finishedHash.discardHandshakeBuffer()
  658. return nil
  659. }
  660. func (hs *serverHandshakeState) establishKeys() error {
  661. c := hs.c
  662. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  663. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  664. var clientCipher, serverCipher interface{}
  665. var clientHash, serverHash macFunction
  666. if hs.suite.aead == nil {
  667. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  668. clientHash = hs.suite.mac(c.vers, clientMAC)
  669. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  670. serverHash = hs.suite.mac(c.vers, serverMAC)
  671. } else {
  672. clientCipher = hs.suite.aead(clientKey, clientIV)
  673. serverCipher = hs.suite.aead(serverKey, serverIV)
  674. }
  675. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  676. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  677. return nil
  678. }
  679. func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
  680. c := hs.c
  681. c.readRecord(recordTypeChangeCipherSpec)
  682. if err := c.in.error(); err != nil {
  683. return err
  684. }
  685. if hs.hello.nextProtoNeg {
  686. msg, err := c.readHandshake()
  687. if err != nil {
  688. return err
  689. }
  690. nextProto, ok := msg.(*nextProtoMsg)
  691. if !ok {
  692. c.sendAlert(alertUnexpectedMessage)
  693. return unexpectedMessageError(nextProto, msg)
  694. }
  695. hs.writeClientHash(nextProto.marshal())
  696. c.clientProtocol = nextProto.proto
  697. }
  698. if hs.hello.channelIDRequested {
  699. msg, err := c.readHandshake()
  700. if err != nil {
  701. return err
  702. }
  703. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  704. if !ok {
  705. c.sendAlert(alertUnexpectedMessage)
  706. return unexpectedMessageError(encryptedExtensions, msg)
  707. }
  708. x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
  709. y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
  710. r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
  711. s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
  712. if !elliptic.P256().IsOnCurve(x, y) {
  713. return errors.New("tls: invalid channel ID public key")
  714. }
  715. channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
  716. var resumeHash []byte
  717. if isResume {
  718. resumeHash = hs.sessionState.handshakeHash
  719. }
  720. if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
  721. return errors.New("tls: invalid channel ID signature")
  722. }
  723. c.channelID = channelID
  724. hs.writeClientHash(encryptedExtensions.marshal())
  725. }
  726. msg, err := c.readHandshake()
  727. if err != nil {
  728. return err
  729. }
  730. clientFinished, ok := msg.(*finishedMsg)
  731. if !ok {
  732. c.sendAlert(alertUnexpectedMessage)
  733. return unexpectedMessageError(clientFinished, msg)
  734. }
  735. verify := hs.finishedHash.clientSum(hs.masterSecret)
  736. if len(verify) != len(clientFinished.verifyData) ||
  737. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  738. c.sendAlert(alertHandshakeFailure)
  739. return errors.New("tls: client's Finished message is incorrect")
  740. }
  741. c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
  742. copy(out, clientFinished.verifyData)
  743. hs.writeClientHash(clientFinished.marshal())
  744. return nil
  745. }
  746. func (hs *serverHandshakeState) sendSessionTicket() error {
  747. c := hs.c
  748. state := sessionState{
  749. vers: c.vers,
  750. cipherSuite: hs.suite.id,
  751. masterSecret: hs.masterSecret,
  752. certificates: hs.certsFromClient,
  753. handshakeHash: hs.finishedHash.server.Sum(nil),
  754. }
  755. if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
  756. if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
  757. c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
  758. }
  759. return nil
  760. }
  761. m := new(newSessionTicketMsg)
  762. var err error
  763. m.ticket, err = c.encryptTicket(&state)
  764. if err != nil {
  765. return err
  766. }
  767. hs.writeServerHash(m.marshal())
  768. c.writeRecord(recordTypeHandshake, m.marshal())
  769. return nil
  770. }
  771. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  772. c := hs.c
  773. finished := new(finishedMsg)
  774. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  775. copy(out, finished.verifyData)
  776. if c.config.Bugs.BadFinished {
  777. finished.verifyData[0]++
  778. }
  779. c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
  780. hs.finishedBytes = finished.marshal()
  781. hs.writeServerHash(hs.finishedBytes)
  782. postCCSBytes := hs.finishedBytes
  783. if c.config.Bugs.FragmentAcrossChangeCipherSpec {
  784. c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
  785. postCCSBytes = postCCSBytes[5:]
  786. }
  787. c.dtlsFlushHandshake()
  788. if !c.config.Bugs.SkipChangeCipherSpec {
  789. c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  790. }
  791. if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
  792. c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
  793. }
  794. if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
  795. c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
  796. return errors.New("tls: simulating post-CCS alert")
  797. }
  798. if !c.config.Bugs.SkipFinished {
  799. c.writeRecord(recordTypeHandshake, postCCSBytes)
  800. c.dtlsFlushHandshake()
  801. }
  802. c.cipherSuite = hs.suite
  803. return nil
  804. }
  805. // processCertsFromClient takes a chain of client certificates either from a
  806. // Certificates message or from a sessionState and verifies them. It returns
  807. // the public key of the leaf certificate.
  808. func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
  809. c := hs.c
  810. hs.certsFromClient = certificates
  811. certs := make([]*x509.Certificate, len(certificates))
  812. var err error
  813. for i, asn1Data := range certificates {
  814. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  815. c.sendAlert(alertBadCertificate)
  816. return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
  817. }
  818. }
  819. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  820. opts := x509.VerifyOptions{
  821. Roots: c.config.ClientCAs,
  822. CurrentTime: c.config.time(),
  823. Intermediates: x509.NewCertPool(),
  824. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  825. }
  826. for _, cert := range certs[1:] {
  827. opts.Intermediates.AddCert(cert)
  828. }
  829. chains, err := certs[0].Verify(opts)
  830. if err != nil {
  831. c.sendAlert(alertBadCertificate)
  832. return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
  833. }
  834. ok := false
  835. for _, ku := range certs[0].ExtKeyUsage {
  836. if ku == x509.ExtKeyUsageClientAuth {
  837. ok = true
  838. break
  839. }
  840. }
  841. if !ok {
  842. c.sendAlert(alertHandshakeFailure)
  843. return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
  844. }
  845. c.verifiedChains = chains
  846. }
  847. if len(certs) > 0 {
  848. var pub crypto.PublicKey
  849. switch key := certs[0].PublicKey.(type) {
  850. case *ecdsa.PublicKey, *rsa.PublicKey:
  851. pub = key
  852. default:
  853. c.sendAlert(alertUnsupportedCertificate)
  854. return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  855. }
  856. c.peerCertificates = certs
  857. return pub, nil
  858. }
  859. return nil, nil
  860. }
  861. func (hs *serverHandshakeState) writeServerHash(msg []byte) {
  862. // writeServerHash is called before writeRecord.
  863. hs.writeHash(msg, hs.c.sendHandshakeSeq)
  864. }
  865. func (hs *serverHandshakeState) writeClientHash(msg []byte) {
  866. // writeClientHash is called after readHandshake.
  867. hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
  868. }
  869. func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
  870. if hs.c.isDTLS {
  871. // This is somewhat hacky. DTLS hashes a slightly different format.
  872. // First, the TLS header.
  873. hs.finishedHash.Write(msg[:4])
  874. // Then the sequence number and reassembled fragment offset (always 0).
  875. hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
  876. // Then the reassembled fragment (always equal to the message length).
  877. hs.finishedHash.Write(msg[1:4])
  878. // And then the message body.
  879. hs.finishedHash.Write(msg[4:])
  880. } else {
  881. hs.finishedHash.Write(msg)
  882. }
  883. }
  884. // tryCipherSuite returns a cipherSuite with the given id if that cipher suite
  885. // is acceptable to use.
  886. func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
  887. for _, supported := range supportedCipherSuites {
  888. if id == supported {
  889. var candidate *cipherSuite
  890. for _, s := range cipherSuites {
  891. if s.id == id {
  892. candidate = s
  893. break
  894. }
  895. }
  896. if candidate == nil {
  897. continue
  898. }
  899. // Don't select a ciphersuite which we can't
  900. // support for this client.
  901. if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
  902. continue
  903. }
  904. if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
  905. continue
  906. }
  907. if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
  908. continue
  909. }
  910. if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
  911. continue
  912. }
  913. return candidate
  914. }
  915. }
  916. return nil
  917. }