13.go 35 KB

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