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.

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