github.com/Psiphon-Labs/tls-tris@v0.0.0-20230824155421-58bf6d336a9a/13.go (about) 1 package tls 2 3 import ( 4 "bytes" 5 "crypto" 6 "crypto/ecdsa" 7 "crypto/elliptic" 8 "crypto/hmac" 9 "crypto/rsa" 10 "crypto/subtle" 11 "encoding/hex" 12 "errors" 13 "fmt" 14 "hash" 15 "io" 16 "log" 17 "os" 18 "runtime" 19 "runtime/debug" 20 "strings" 21 "sync/atomic" 22 "time" 23 24 "golang.org/x/crypto/curve25519" 25 26 // [Psiphon] 27 "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng" 28 ) 29 30 // numSessionTickets is the number of different session tickets the 31 // server sends to a TLS 1.3 client, who will use each only once. 32 const numSessionTickets = 2 33 34 type secretLabel int 35 36 const ( 37 secretResumptionPskBinder secretLabel = iota 38 secretEarlyClient 39 secretHandshakeClient 40 secretHandshakeServer 41 secretApplicationClient 42 secretApplicationServer 43 secretResumption 44 ) 45 46 type keySchedule13 struct { 47 suite *cipherSuite 48 transcriptHash hash.Hash // uses the cipher suite hash algo 49 secret []byte // Current secret as used for Derive-Secret 50 handshakeCtx []byte // cached handshake context, invalidated on updates. 51 clientRandom []byte // Used for keylogging, nil if keylogging is disabled. 52 config *Config // Used for KeyLogWriter callback, nil if keylogging is disabled. 53 } 54 55 func newKeySchedule13(suite *cipherSuite, config *Config, clientRandom []byte) *keySchedule13 { 56 if config.KeyLogWriter == nil { 57 clientRandom = nil 58 config = nil 59 } 60 return &keySchedule13{ 61 suite: suite, 62 transcriptHash: hashForSuite(suite).New(), 63 clientRandom: clientRandom, 64 config: config, 65 } 66 } 67 68 // setSecret sets the early/handshake/master secret based on the given secret 69 // (IKM). The salt is based on previous secrets (nil for the early secret). 70 func (ks *keySchedule13) setSecret(secret []byte) { 71 hash := hashForSuite(ks.suite) 72 salt := ks.secret 73 if salt != nil { 74 h0 := hash.New().Sum(nil) 75 salt = hkdfExpandLabel(hash, salt, h0, "derived", hash.Size()) 76 } 77 ks.secret = hkdfExtract(hash, secret, salt) 78 } 79 80 // write appends the data to the transcript hash context. 81 func (ks *keySchedule13) write(data []byte) { 82 ks.handshakeCtx = nil 83 ks.transcriptHash.Write(data) 84 } 85 86 func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label, keylogType string) { 87 switch secretLabel { 88 case secretResumptionPskBinder: 89 label = "res binder" 90 case secretEarlyClient: 91 label = "c e traffic" 92 keylogType = "CLIENT_EARLY_TRAFFIC_SECRET" 93 case secretHandshakeClient: 94 label = "c hs traffic" 95 keylogType = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" 96 case secretHandshakeServer: 97 label = "s hs traffic" 98 keylogType = "SERVER_HANDSHAKE_TRAFFIC_SECRET" 99 case secretApplicationClient: 100 label = "c ap traffic" 101 keylogType = "CLIENT_TRAFFIC_SECRET_0" 102 case secretApplicationServer: 103 label = "s ap traffic" 104 keylogType = "SERVER_TRAFFIC_SECRET_0" 105 case secretResumption: 106 label = "res master" 107 } 108 return 109 } 110 111 // deriveSecret returns the secret derived from the handshake context and label. 112 func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte { 113 label, keylogType := ks.getLabel(secretLabel) 114 if ks.handshakeCtx == nil { 115 ks.handshakeCtx = ks.transcriptHash.Sum(nil) 116 } 117 hash := hashForSuite(ks.suite) 118 secret := hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size()) 119 if keylogType != "" && ks.config != nil { 120 ks.config.writeKeyLog(keylogType, ks.clientRandom, secret) 121 } 122 return secret 123 } 124 125 func (ks *keySchedule13) prepareCipher(secretLabel secretLabel) (interface{}, []byte) { 126 trafficSecret := ks.deriveSecret(secretLabel) 127 hash := hashForSuite(ks.suite) 128 key := hkdfExpandLabel(hash, trafficSecret, nil, "key", ks.suite.keyLen) 129 iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", ks.suite.ivLen) 130 return ks.suite.aead(key, iv), trafficSecret 131 } 132 133 func (hs *serverHandshakeState) doTLS13Handshake() error { 134 config := hs.c.config 135 c := hs.c 136 137 hs.c.cipherSuite, hs.hello.cipherSuite = hs.suite.id, hs.suite.id 138 hs.c.clientHello = hs.clientHello.marshal() 139 140 // When picking the group for the handshake, priority is given to groups 141 // that the client provided a keyShare for, so to avoid a round-trip. 142 // After that the order of CurvePreferences is respected. 143 var ks keyShare 144 CurvePreferenceLoop: 145 for _, curveID := range config.curvePreferences() { 146 for _, keyShare := range hs.clientHello.keyShares { 147 if curveID == keyShare.group { 148 ks = keyShare 149 break CurvePreferenceLoop 150 } 151 } 152 } 153 if ks.group == 0 { 154 c.sendAlert(alertInternalError) 155 return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo) 156 } 157 158 privateKey, serverKS, err := config.generateKeyShare(ks.group) 159 if err != nil { 160 c.sendAlert(alertInternalError) 161 return err 162 } 163 hs.hello.keyShare = serverKS 164 165 hash := hashForSuite(hs.suite) 166 hashSize := hash.Size() 167 hs.keySchedule = newKeySchedule13(hs.suite, config, hs.clientHello.random) 168 169 // Check for PSK and update key schedule with new early secret key 170 isResumed, pskAlert := hs.checkPSK() 171 switch { 172 case pskAlert != alertSuccess: 173 c.sendAlert(pskAlert) 174 return errors.New("tls: invalid client PSK") 175 case !isResumed: 176 // apply an empty PSK if not resumed. 177 hs.keySchedule.setSecret(nil) 178 case isResumed: 179 c.didResume = true 180 } 181 182 hs.keySchedule.write(hs.clientHello.marshal()) 183 184 earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient) 185 186 ecdheSecret := deriveECDHESecret(ks, privateKey) 187 if ecdheSecret == nil { 188 c.sendAlert(alertIllegalParameter) 189 return errors.New("tls: bad ECDHE client share") 190 } 191 192 hs.keySchedule.write(hs.hello.marshal()) 193 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 194 return err 195 } 196 197 // middlebox compatibility mode: send CCS after first handshake message 198 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 199 return err 200 } 201 202 hs.keySchedule.setSecret(ecdheSecret) 203 clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient) 204 hs.hsClientCipher = clientCipher 205 serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer) 206 c.out.setCipher(c.vers, serverCipher) 207 208 serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize) 209 hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize) 210 211 // EncryptedExtensions 212 hs.keySchedule.write(hs.hello13Enc.marshal()) 213 if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil { 214 return err 215 } 216 217 // TODO: we should have 2 separated methods - one for full-handshake and the other for PSK-handshake 218 if !c.didResume { 219 // Server MUST NOT send CertificateRequest if authenticating with PSK 220 if c.config.ClientAuth >= RequestClientCert { 221 222 certReq := new(certificateRequestMsg13) 223 // extension 'signature_algorithms' MUST be specified 224 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms13 225 certReq.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13) 226 hs.keySchedule.write(certReq.marshal()) 227 if _, err := hs.c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 228 return err 229 } 230 } 231 232 if err := hs.sendCertificate13(); err != nil { 233 return err 234 } 235 } 236 237 verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey) 238 serverFinished := &finishedMsg{ 239 verifyData: verifyData, 240 } 241 hs.keySchedule.write(serverFinished.marshal()) 242 if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil { 243 return err 244 } 245 246 hs.keySchedule.setSecret(nil) // derive master secret 247 hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient) 248 serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer) 249 c.out.setCipher(c.vers, serverCipher) 250 251 if c.hand.Len() > 0 { 252 return c.sendAlert(alertUnexpectedMessage) 253 } 254 if hs.hello13Enc.earlyData { 255 c.in.setCipher(c.vers, earlyClientCipher) 256 c.phase = readingEarlyData 257 } else if hs.clientHello.earlyData { 258 c.in.setCipher(c.vers, hs.hsClientCipher) 259 c.phase = discardingEarlyData 260 } else { 261 c.in.setCipher(c.vers, hs.hsClientCipher) 262 c.phase = waitingClientFinished 263 } 264 265 return nil 266 } 267 268 // readClientFinished13 is called during the server handshake (when no early 269 // data it available) or after reading all early data. It discards early data if 270 // the server did not accept it and then verifies the Finished message. Once 271 // done it sends the session tickets. Under c.in lock. 272 func (hs *serverHandshakeState) readClientFinished13(hasConfirmLock bool) error { 273 c := hs.c 274 275 // If the client advertised and sends early data while the server does 276 // not accept it, it must be fully skipped until the Finished message. 277 for c.phase == discardingEarlyData { 278 if err := c.readRecord(recordTypeApplicationData); err != nil { 279 return err 280 } 281 // Assume receipt of Finished message (will be checked below). 282 if c.hand.Len() > 0 { 283 c.phase = waitingClientFinished 284 break 285 } 286 } 287 288 // If the client sends early data followed by a Finished message (but 289 // no end_of_early_data), the server MUST terminate the connection. 290 if c.phase != waitingClientFinished { 291 c.sendAlert(alertUnexpectedMessage) 292 return errors.New("tls: did not expect Client Finished yet") 293 } 294 295 c.phase = readingClientFinished 296 msg, err := c.readHandshake() 297 if err != nil { 298 return err 299 } 300 301 // client authentication 302 if certMsg, ok := msg.(*certificateMsg13); ok { 303 304 // (4.4.2) Client MUST send certificate msg if requested by server 305 if c.config.ClientAuth < RequestClientCert { 306 c.sendAlert(alertUnexpectedMessage) 307 return unexpectedMessageError(certMsg, msg) 308 } 309 310 hs.keySchedule.write(certMsg.marshal()) 311 certs := getCertsFromEntries(certMsg.certificates) 312 pubKey, err := hs.processCertsFromClient(certs) 313 if err != nil { 314 return err 315 } 316 317 // 4.4.3: CertificateVerify MUST appear immediately after Certificate msg 318 msg, err = c.readHandshake() 319 if err != nil { 320 return err 321 } 322 323 certVerify, ok := msg.(*certificateVerifyMsg) 324 if !ok { 325 c.sendAlert(alertUnexpectedMessage) 326 return unexpectedMessageError(certVerify, msg) 327 } 328 329 err, alertCode := verifyPeerHandshakeSignature( 330 certVerify, 331 pubKey, 332 supportedSignatureAlgorithms13, 333 hs.keySchedule.transcriptHash.Sum(nil), 334 "TLS 1.3, client CertificateVerify") 335 if err != nil { 336 c.sendAlert(alertCode) 337 return err 338 } 339 hs.keySchedule.write(certVerify.marshal()) 340 341 // Read next chunk 342 msg, err = c.readHandshake() 343 if err != nil { 344 return err 345 } 346 347 } else if (c.config.ClientAuth >= RequestClientCert) && !c.didResume { 348 c.sendAlert(alertCertificateRequired) 349 return unexpectedMessageError(certMsg, msg) 350 } 351 352 clientFinished, ok := msg.(*finishedMsg) 353 if !ok { 354 c.sendAlert(alertUnexpectedMessage) 355 return unexpectedMessageError(clientFinished, msg) 356 } 357 358 hash := hashForSuite(hs.suite) 359 expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey) 360 if len(expectedVerifyData) != len(clientFinished.verifyData) || 361 subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 { 362 c.sendAlert(alertDecryptError) 363 return errors.New("tls: client's Finished message is incorrect") 364 } 365 hs.keySchedule.write(clientFinished.marshal()) 366 367 c.hs = nil // Discard the server handshake state 368 if c.hand.Len() > 0 { 369 return c.sendAlert(alertUnexpectedMessage) 370 } 371 c.in.setCipher(c.vers, hs.appClientCipher) 372 c.in.traceErr, c.out.traceErr = nil, nil 373 c.phase = handshakeConfirmed 374 atomic.StoreInt32(&c.handshakeConfirmed, 1) 375 376 // Any read operation after handshakeRunning and before handshakeConfirmed 377 // will be holding this lock, which we release as soon as the confirmation 378 // happens, even if the Read call might do more work. 379 // If a Handshake is pending, c.confirmMutex will never be locked as 380 // ConfirmHandshake will wait for the handshake to complete. If a 381 // handshake was complete, and this was a confirmation, unlock 382 // c.confirmMutex now to allow readers to proceed. 383 if hasConfirmLock { 384 c.confirmMutex.Unlock() 385 } 386 387 return hs.sendSessionTicket13() // TODO: do in a goroutine 388 } 389 390 func (hs *serverHandshakeState) sendCertificate13() error { 391 c := hs.c 392 393 certEntries := []certificateEntry{} 394 for _, cert := range hs.cert.Certificate { 395 certEntries = append(certEntries, certificateEntry{data: cert}) 396 } 397 if len(certEntries) > 0 && hs.clientHello.ocspStapling { 398 certEntries[0].ocspStaple = hs.cert.OCSPStaple 399 } 400 if len(certEntries) > 0 && hs.clientHello.scts { 401 certEntries[0].sctList = hs.cert.SignedCertificateTimestamps 402 } 403 404 // If hs.delegatedCredential is set (see hs.readClientHello()) then the 405 // server is using the delegated credential extension. The DC is added as an 406 // extension to the end-entity certificate, i.e., the last CertificateEntry 407 // of Certificate.certficate_list. (For details, see 408 // https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.) 409 if len(certEntries) > 0 && hs.clientHello.delegatedCredential && hs.delegatedCredential != nil { 410 certEntries[0].delegatedCredential = hs.delegatedCredential 411 } 412 413 certMsg := &certificateMsg13{certificates: certEntries} 414 415 hs.keySchedule.write(certMsg.marshal()) 416 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 417 return err 418 } 419 420 sigScheme, err := hs.selectTLS13SignatureScheme() 421 if err != nil { 422 c.sendAlert(alertInternalError) 423 return err 424 } 425 426 sigHash := hashForSignatureScheme(sigScheme) 427 opts := crypto.SignerOpts(sigHash) 428 if signatureSchemeIsPSS(sigScheme) { 429 opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 430 } 431 432 toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil)) 433 signature, err := hs.privateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts) 434 if err != nil { 435 c.sendAlert(alertInternalError) 436 return err 437 } 438 439 verifyMsg := &certificateVerifyMsg{ 440 hasSignatureAndHash: true, 441 signatureAlgorithm: sigScheme, 442 signature: signature, 443 } 444 hs.keySchedule.write(verifyMsg.marshal()) 445 if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil { 446 return err 447 } 448 449 return nil 450 } 451 452 func (c *Conn) handleEndOfEarlyData() error { 453 if c.phase != readingEarlyData || c.vers < VersionTLS13 { 454 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 455 } 456 msg, err := c.readHandshake() 457 if err != nil { 458 return err 459 } 460 endOfEarlyData, ok := msg.(*endOfEarlyDataMsg) 461 // No handshake messages are allowed after EOD. 462 if !ok || c.hand.Len() > 0 { 463 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 464 } 465 c.hs.keySchedule.write(endOfEarlyData.marshal()) 466 c.phase = waitingClientFinished 467 c.in.setCipher(c.vers, c.hs.hsClientCipher) 468 return nil 469 } 470 471 // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify 472 // based on the certificate type and client supported schemes. If no overlap is found, 473 // a fallback is selected. 474 // 475 // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2 476 func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) { 477 var supportedSchemes []SignatureScheme 478 signer, ok := hs.privateKey.(crypto.Signer) 479 if !ok { 480 return 0, errors.New("tls: private key does not implement crypto.Signer") 481 } 482 pk := signer.Public() 483 if _, ok := pk.(*rsa.PublicKey); ok { 484 sigScheme = PSSWithSHA256 485 supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512} 486 } else if pk, ok := pk.(*ecdsa.PublicKey); ok { 487 switch pk.Curve { 488 case elliptic.P256(): 489 sigScheme = ECDSAWithP256AndSHA256 490 supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256} 491 case elliptic.P384(): 492 sigScheme = ECDSAWithP384AndSHA384 493 supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384} 494 case elliptic.P521(): 495 sigScheme = ECDSAWithP521AndSHA512 496 supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512} 497 default: 498 return 0, errors.New("tls: unknown ECDSA certificate curve") 499 } 500 } else { 501 return 0, errors.New("tls: unknown certificate key type") 502 } 503 504 for _, ss := range supportedSchemes { 505 for _, cs := range hs.clientHello.supportedSignatureAlgorithms { 506 if ss == cs { 507 return ss, nil 508 } 509 } 510 } 511 512 return sigScheme, nil 513 } 514 515 func signatureSchemeIsPSS(s SignatureScheme) bool { 516 return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512 517 } 518 519 // hashForSignatureScheme returns the Hash used by a SignatureScheme which is 520 // supported by selectTLS13SignatureScheme. 521 func hashForSignatureScheme(ss SignatureScheme) crypto.Hash { 522 switch ss { 523 case PSSWithSHA256, ECDSAWithP256AndSHA256: 524 return crypto.SHA256 525 case PSSWithSHA384, ECDSAWithP384AndSHA384: 526 return crypto.SHA384 527 case PSSWithSHA512, ECDSAWithP521AndSHA512: 528 return crypto.SHA512 529 default: 530 panic("unsupported SignatureScheme passed to hashForSignatureScheme") 531 } 532 } 533 534 func hashForSuite(suite *cipherSuite) crypto.Hash { 535 if suite.flags&suiteSHA384 != 0 { 536 return crypto.SHA384 537 } 538 return crypto.SHA256 539 } 540 541 func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte { 542 message := bytes.Repeat([]byte{32}, 64) 543 message = append(message, context...) 544 message = append(message, 0) 545 message = append(message, data...) 546 h := hash.New() 547 h.Write(message) 548 return h.Sum(nil) 549 } 550 551 func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) { 552 if curveID == X25519 { 553 var scalar, public [32]byte 554 if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil { 555 return nil, keyShare{}, err 556 } 557 558 curve25519.ScalarBaseMult(&public, &scalar) 559 return scalar[:], keyShare{group: curveID, data: public[:]}, nil 560 } 561 562 curve, ok := curveForCurveID(curveID) 563 if !ok { 564 return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve") 565 } 566 567 privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand()) 568 if err != nil { 569 return nil, keyShare{}, err 570 } 571 ecdhePublic := elliptic.Marshal(curve, x, y) 572 573 return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil 574 } 575 576 func deriveECDHESecret(ks keyShare, secretKey []byte) []byte { 577 if ks.group == X25519 { 578 if len(ks.data) != 32 { 579 return nil 580 } 581 582 var theirPublic, sharedKey, scalar [32]byte 583 copy(theirPublic[:], ks.data) 584 copy(scalar[:], secretKey) 585 curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic) 586 return sharedKey[:] 587 } 588 589 curve, ok := curveForCurveID(ks.group) 590 if !ok { 591 return nil 592 } 593 x, y := elliptic.Unmarshal(curve, ks.data) 594 if x == nil { 595 return nil 596 } 597 x, _ = curve.ScalarMult(x, y, secretKey) 598 xBytes := x.Bytes() 599 curveSize := (curve.Params().BitSize + 8 - 1) >> 3 600 if len(xBytes) == curveSize { 601 return xBytes 602 } 603 buf := make([]byte, curveSize) 604 copy(buf[len(buf)-len(xBytes):], xBytes) 605 return buf 606 } 607 608 func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte { 609 prefix := "tls13 " 610 hkdfLabel := make([]byte, 4+len(prefix)+len(label)+len(hashValue)) 611 hkdfLabel[0] = byte(L >> 8) 612 hkdfLabel[1] = byte(L) 613 hkdfLabel[2] = byte(len(prefix) + len(label)) 614 copy(hkdfLabel[3:], prefix) 615 z := hkdfLabel[3+len(prefix):] 616 copy(z, label) 617 z = z[len(label):] 618 z[0] = byte(len(hashValue)) 619 copy(z[1:], hashValue) 620 621 return hkdfExpand(hash, secret, hkdfLabel, L) 622 } 623 624 func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte { 625 h := hmac.New(f.New, key) 626 h.Write(hash.Sum(nil)) 627 return h.Sum(nil) 628 } 629 630 // Maximum allowed mismatch between the stated age of a ticket 631 // and the server-observed one. See 632 // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2. 633 const ticketAgeSkewAllowance = 10 * time.Second 634 635 // checkPSK tries to resume using a PSK, returning true (and updating the 636 // early secret in the key schedule) if the PSK was used and false otherwise. 637 func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) { 638 if hs.c.config.SessionTicketsDisabled { 639 return false, alertSuccess 640 } 641 642 foundDHE := false 643 for _, mode := range hs.clientHello.pskKeyExchangeModes { 644 if mode == pskDHEKeyExchange { 645 foundDHE = true 646 break 647 } 648 } 649 if !foundDHE { 650 return false, alertSuccess 651 } 652 653 hash := hashForSuite(hs.suite) 654 hashSize := hash.Size() 655 for i := range hs.clientHello.psks { 656 sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...) 657 if hs.c.config.SessionTicketSealer != nil { 658 var ok bool 659 sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket) 660 if !ok { 661 continue 662 } 663 } else { 664 sessionTicket, _ = hs.c.decryptTicket(sessionTicket) 665 if sessionTicket == nil { 666 continue 667 } 668 } 669 s := &sessionState13{} 670 if s.unmarshal(sessionTicket) != alertSuccess { 671 continue 672 } 673 if s.vers != hs.c.vers { 674 continue 675 } 676 clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond 677 serverAge := time.Since(time.Unix(int64(s.createdAt), 0)) 678 if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance { 679 // XXX: NSS is off spec and sends obfuscated_ticket_age as seconds 680 clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second 681 if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance { 682 continue 683 } 684 } 685 686 // This enforces the stricter 0-RTT requirements on all ticket uses. 687 // The benefit of using PSK+ECDHE without 0-RTT are small enough that 688 // we can give them up in the edge case of changed suite or ALPN or SNI. 689 if s.suite != hs.suite.id { 690 continue 691 } 692 if s.alpnProtocol != hs.c.clientProtocol { 693 continue 694 } 695 if s.SNI != hs.c.serverName { 696 continue 697 } 698 699 hs.keySchedule.setSecret(s.pskSecret) 700 binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder) 701 binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize) 702 chHash := hash.New() 703 chHash.Write(hs.clientHello.rawTruncated) 704 expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey) 705 706 if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 { 707 return false, alertDecryptError 708 } 709 710 if i == 0 && hs.clientHello.earlyData { 711 // This is a ticket intended to be used for 0-RTT 712 if s.maxEarlyDataLen == 0 { 713 // But we had not tagged it as such. 714 return false, alertIllegalParameter 715 } 716 if hs.c.config.Accept0RTTData { 717 hs.c.binder = expectedBinder 718 hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen) 719 hs.hello13Enc.earlyData = true 720 } 721 } 722 hs.hello.psk = true 723 hs.hello.pskIdentity = uint16(i) 724 return true, alertSuccess 725 } 726 727 return false, alertSuccess 728 } 729 730 func (hs *serverHandshakeState) sendSessionTicket13() error { 731 c := hs.c 732 if c.config.SessionTicketsDisabled { 733 return nil 734 } 735 736 foundDHE := false 737 for _, mode := range hs.clientHello.pskKeyExchangeModes { 738 if mode == pskDHEKeyExchange { 739 foundDHE = true 740 break 741 } 742 } 743 if !foundDHE { 744 return nil 745 } 746 747 resumptionMasterSecret := hs.keySchedule.deriveSecret(secretResumption) 748 749 ageAddBuf := make([]byte, 4) 750 sessionState := &sessionState13{ 751 vers: c.vers, 752 suite: hs.suite.id, 753 createdAt: uint64(time.Now().Unix()), 754 alpnProtocol: c.clientProtocol, 755 SNI: c.serverName, 756 maxEarlyDataLen: c.config.Max0RTTDataSize, 757 } 758 hash := hashForSuite(hs.suite) 759 760 for i := 0; i < numSessionTickets; i++ { 761 if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil { 762 c.sendAlert(alertInternalError) 763 return err 764 } 765 sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 | 766 uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3]) 767 // ticketNonce must be a unique value for this connection. 768 // Assume there are no more than 255 tickets, otherwise two 769 // tickets might have the same PSK which could be a problem if 770 // one of them is compromised. 771 ticketNonce := []byte{byte(i)} 772 sessionState.pskSecret = hkdfExpandLabel(hash, resumptionMasterSecret, ticketNonce, "resumption", hash.Size()) 773 ticket := sessionState.marshal() 774 var err error 775 if c.config.SessionTicketSealer != nil { 776 cs := c.ConnectionState() 777 ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket) 778 } else { 779 ticket, err = c.encryptTicket(ticket) 780 } 781 if err != nil { 782 c.sendAlert(alertInternalError) 783 return err 784 } 785 if ticket == nil { 786 continue 787 } 788 789 // [Psiphon] 790 // Set lifetime hint to a more typical value. 791 lifetime := uint32(24 * 3600) // TODO(filippo) 792 if obfuscateSessionTickets { 793 hints := []uint32{300, 1200, 7200, 10800, 64800, 100800, 129600} 794 index := prng.Intn(len(hints)) 795 lifetime = hints[index] 796 } 797 798 ticketMsg := &newSessionTicketMsg13{ 799 //lifetime: 24 * 3600, // TODO(filippo) 800 lifetime: lifetime, 801 maxEarlyDataLength: c.config.Max0RTTDataSize, 802 withEarlyDataInfo: c.config.Max0RTTDataSize > 0, 803 ageAdd: sessionState.ageAdd, 804 nonce: ticketNonce, 805 ticket: ticket, 806 } 807 if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil { 808 return err 809 } 810 } 811 812 return nil 813 } 814 815 func (hs *serverHandshakeState) traceErr(err error) { 816 if err == nil { 817 return 818 } 819 if os.Getenv("TLSDEBUG") == "error" { 820 if hs != nil && hs.clientHello != nil { 821 os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal())) 822 } else if err == io.EOF { 823 return // don't stack trace on EOF before CH 824 } 825 fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack()) 826 } 827 if os.Getenv("TLSDEBUG") == "short" { 828 var pcs [4]uintptr 829 frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])]) 830 for { 831 frame, more := frames.Next() 832 if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" && 833 frame.Function != "crypto/tls.(*Conn).sendAlertLocked" && 834 frame.Function != "crypto/tls.(*Conn).sendAlert" { 835 file := frame.File[strings.LastIndex(frame.File, "/")+1:] 836 log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err) 837 return 838 } 839 if !more { 840 break 841 } 842 } 843 } 844 } 845 846 func getCertsFromEntries(certEntries []certificateEntry) [][]byte { 847 certs := make([][]byte, len(certEntries)) 848 for i, cert := range certEntries { 849 certs[i] = cert.data 850 } 851 return certs 852 } 853 854 func (hs *clientHandshakeState) processEncryptedExtensions(ee *encryptedExtensionsMsg) error { 855 c := hs.c 856 if ee.alpnProtocol != "" { 857 c.clientProtocol = ee.alpnProtocol 858 c.clientProtocolFallback = false 859 } 860 return nil 861 } 862 863 func verifyPeerHandshakeSignature( 864 certVerify *certificateVerifyMsg, 865 pubKey crypto.PublicKey, 866 signAlgosKnown []SignatureScheme, 867 transHash []byte, 868 contextString string) (error, alert) { 869 870 _, sigType, hashFunc, err := pickSignatureAlgorithm( 871 pubKey, 872 []SignatureScheme{certVerify.signatureAlgorithm}, 873 signAlgosKnown, 874 VersionTLS13) 875 if err != nil { 876 return err, alertHandshakeFailure 877 } 878 879 digest := prepareDigitallySigned(hashFunc, contextString, transHash) 880 err = verifyHandshakeSignature(sigType, pubKey, hashFunc, digest, certVerify.signature) 881 882 if err != nil { 883 return err, alertDecryptError 884 } 885 886 return nil, alertSuccess 887 } 888 889 func (hs *clientHandshakeState) getCertificate13(certReq *certificateRequestMsg13) (*Certificate, error) { 890 certReq12 := &certificateRequestMsg{ 891 hasSignatureAndHash: true, 892 supportedSignatureAlgorithms: certReq.supportedSignatureAlgorithms, 893 certificateAuthorities: certReq.certificateAuthorities, 894 } 895 896 var rsaAvail, ecdsaAvail bool 897 for _, sigAlg := range certReq.supportedSignatureAlgorithms { 898 switch signatureFromSignatureScheme(sigAlg) { 899 case signaturePKCS1v15, signatureRSAPSS: 900 rsaAvail = true 901 case signatureECDSA: 902 ecdsaAvail = true 903 } 904 } 905 if rsaAvail { 906 certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeRSASign) 907 } 908 if ecdsaAvail { 909 certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeECDSASign) 910 } 911 912 return hs.getCertificate(certReq12) 913 } 914 915 func (hs *clientHandshakeState) sendCertificate13(chainToSend *Certificate, certReq *certificateRequestMsg13) error { 916 c := hs.c 917 918 certEntries := []certificateEntry{} 919 for _, cert := range chainToSend.Certificate { 920 certEntries = append(certEntries, certificateEntry{data: cert}) 921 } 922 certMsg := &certificateMsg13{certificates: certEntries} 923 924 hs.keySchedule.write(certMsg.marshal()) 925 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 926 return err 927 } 928 929 if len(certEntries) == 0 { 930 // No client cert available, nothing to sign. 931 return nil 932 } 933 934 key, ok := chainToSend.PrivateKey.(crypto.Signer) 935 if !ok { 936 c.sendAlert(alertInternalError) 937 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) 938 } 939 940 signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers) 941 if err != nil { 942 hs.c.sendAlert(alertHandshakeFailure) 943 return err 944 } 945 946 digest := prepareDigitallySigned(hashFunc, "TLS 1.3, client CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil)) 947 signOpts := crypto.SignerOpts(hashFunc) 948 if sigType == signatureRSAPSS { 949 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc} 950 } 951 signature, err := key.Sign(c.config.rand(), digest, signOpts) 952 if err != nil { 953 c.sendAlert(alertInternalError) 954 return err 955 } 956 957 verifyMsg := &certificateVerifyMsg{ 958 hasSignatureAndHash: true, 959 signatureAlgorithm: signatureAlgorithm, 960 signature: signature, 961 } 962 hs.keySchedule.write(verifyMsg.marshal()) 963 if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil { 964 return err 965 } 966 967 return nil 968 } 969 970 func (hs *clientHandshakeState) doTLS13Handshake() error { 971 c := hs.c 972 hash := hashForSuite(hs.suite) 973 hashSize := hash.Size() 974 serverHello := hs.serverHello 975 c.scts = serverHello.scts 976 977 // middlebox compatibility mode, send CCS before second flight. 978 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 979 return err 980 } 981 982 // TODO check if keyshare is unacceptable, raise HRR. 983 984 clientKS := hs.hello.keyShares[0] 985 if serverHello.keyShare.group != clientKS.group { 986 c.sendAlert(alertIllegalParameter) 987 return errors.New("bad or missing key share from server") 988 } 989 990 // 0-RTT is not supported yet, so use an empty PSK. 991 hs.keySchedule.setSecret(nil) 992 ecdheSecret := deriveECDHESecret(serverHello.keyShare, hs.privateKey) 993 if ecdheSecret == nil { 994 c.sendAlert(alertIllegalParameter) 995 return errors.New("tls: bad ECDHE server share") 996 } 997 998 // Calculate handshake secrets. 999 hs.keySchedule.setSecret(ecdheSecret) 1000 clientCipher, clientHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeClient) 1001 serverCipher, serverHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeServer) 1002 if c.hand.Len() > 0 { 1003 c.sendAlert(alertUnexpectedMessage) 1004 return errors.New("tls: unexpected data after Server Hello") 1005 } 1006 // Do not change the sender key yet, the server must authenticate first. 1007 c.in.setCipher(c.vers, serverCipher) 1008 1009 // Calculate MAC key for Finished messages. 1010 serverFinishedKey := hkdfExpandLabel(hash, serverHandshakeSecret, nil, "finished", hashSize) 1011 clientFinishedKey := hkdfExpandLabel(hash, clientHandshakeSecret, nil, "finished", hashSize) 1012 1013 msg, err := c.readHandshake() 1014 if err != nil { 1015 return err 1016 } 1017 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 1018 if !ok { 1019 c.sendAlert(alertUnexpectedMessage) 1020 return unexpectedMessageError(encryptedExtensions, msg) 1021 } 1022 if err := hs.processEncryptedExtensions(encryptedExtensions); err != nil { 1023 return err 1024 } 1025 hs.keySchedule.write(encryptedExtensions.marshal()) 1026 1027 // PSKs are not supported, so receive Certificate message. 1028 msg, err = c.readHandshake() 1029 if err != nil { 1030 return err 1031 } 1032 1033 var chainToSend *Certificate 1034 certReq, isCertRequested := msg.(*certificateRequestMsg13) 1035 if isCertRequested { 1036 hs.keySchedule.write(certReq.marshal()) 1037 1038 if chainToSend, err = hs.getCertificate13(certReq); err != nil { 1039 c.sendAlert(alertInternalError) 1040 return err 1041 } 1042 1043 msg, err = c.readHandshake() 1044 if err != nil { 1045 return err 1046 } 1047 } 1048 1049 certMsg, ok := msg.(*certificateMsg13) 1050 if !ok { 1051 c.sendAlert(alertUnexpectedMessage) 1052 return unexpectedMessageError(certMsg, msg) 1053 } 1054 hs.keySchedule.write(certMsg.marshal()) 1055 1056 // Validate certificates. 1057 certs := getCertsFromEntries(certMsg.certificates) 1058 if err := hs.processCertsFromServer(certs); err != nil { 1059 return err 1060 } 1061 1062 // Receive CertificateVerify message. 1063 msg, err = c.readHandshake() 1064 if err != nil { 1065 return err 1066 } 1067 certVerifyMsg, ok := msg.(*certificateVerifyMsg) 1068 if !ok { 1069 c.sendAlert(alertUnexpectedMessage) 1070 return unexpectedMessageError(certVerifyMsg, msg) 1071 } 1072 1073 // Validate the DC if present. The DC is only processed if the extension was 1074 // indicated by the ClientHello; otherwise this call will result in an 1075 // "illegal_parameter" alert. 1076 if len(certMsg.certificates) > 0 { 1077 if err := hs.processDelegatedCredentialFromServer( 1078 certMsg.certificates[0].delegatedCredential, 1079 certVerifyMsg.signatureAlgorithm); err != nil { 1080 return err 1081 } 1082 } 1083 1084 // Set the public key used to verify the handshake. 1085 pk := hs.c.peerCertificates[0].PublicKey 1086 1087 // If the delegated credential extension has successfully been negotiated, 1088 // then the CertificateVerify signature will have been produced with the 1089 // DelegatedCredential's private key. 1090 if hs.c.verifiedDc != nil { 1091 pk = hs.c.verifiedDc.cred.publicKey 1092 } 1093 1094 // Verify the handshake signature. 1095 err, alertCode := verifyPeerHandshakeSignature( 1096 certVerifyMsg, 1097 pk, 1098 hs.hello.supportedSignatureAlgorithms, 1099 hs.keySchedule.transcriptHash.Sum(nil), 1100 "TLS 1.3, server CertificateVerify") 1101 if err != nil { 1102 c.sendAlert(alertCode) 1103 return err 1104 } 1105 hs.keySchedule.write(certVerifyMsg.marshal()) 1106 1107 // Receive Finished message. 1108 msg, err = c.readHandshake() 1109 if err != nil { 1110 return err 1111 } 1112 serverFinished, ok := msg.(*finishedMsg) 1113 if !ok { 1114 c.sendAlert(alertUnexpectedMessage) 1115 return unexpectedMessageError(serverFinished, msg) 1116 } 1117 // Validate server Finished hash. 1118 expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey) 1119 if subtle.ConstantTimeCompare(expectedVerifyData, serverFinished.verifyData) != 1 { 1120 c.sendAlert(alertDecryptError) 1121 return errors.New("tls: server's Finished message is incorrect") 1122 } 1123 hs.keySchedule.write(serverFinished.marshal()) 1124 1125 // Server has authenticated itself. Calculate application traffic secrets. 1126 hs.keySchedule.setSecret(nil) // derive master secret 1127 appServerCipher, _ := hs.keySchedule.prepareCipher(secretApplicationServer) 1128 appClientCipher, _ := hs.keySchedule.prepareCipher(secretApplicationClient) 1129 // TODO store initial traffic secret key for KeyUpdate GH #85 1130 1131 // Change outbound handshake cipher for final step 1132 c.out.setCipher(c.vers, clientCipher) 1133 1134 // Client auth requires sending a (possibly empty) Certificate followed 1135 // by a CertificateVerify message (if there was an actual certificate). 1136 if isCertRequested { 1137 if err := hs.sendCertificate13(chainToSend, certReq); err != nil { 1138 return err 1139 } 1140 } 1141 1142 // Send Finished 1143 verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, clientFinishedKey) 1144 clientFinished := &finishedMsg{ 1145 verifyData: verifyData, 1146 } 1147 if _, err := c.writeRecord(recordTypeHandshake, clientFinished.marshal()); err != nil { 1148 return err 1149 } 1150 1151 // Handshake done, set application traffic secret 1152 c.out.setCipher(c.vers, appClientCipher) 1153 if c.hand.Len() > 0 { 1154 c.sendAlert(alertUnexpectedMessage) 1155 return errors.New("tls: unexpected data after handshake") 1156 } 1157 c.in.setCipher(c.vers, appServerCipher) 1158 return nil 1159 } 1160 1161 // supportedSigAlgorithmsCert iterates over schemes and filters out those algorithms 1162 // which are not supported for certificate verification. 1163 func supportedSigAlgorithmsCert(schemes []SignatureScheme) (ret []SignatureScheme) { 1164 for _, sig := range schemes { 1165 // X509 doesn't support PSS signatures 1166 if !signatureSchemeIsPSS(sig) { 1167 ret = append(ret, sig) 1168 } 1169 } 1170 return 1171 }