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