Alternative TLS implementation in Go
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

1500 righe
48 KiB

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