Alternative TLS implementation in Go
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1500 lignes
48 KiB

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