25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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