handshake_client.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/rsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "strconv"
  17. "strings"
  18. "sync/atomic"
  19. )
  20. type clientHandshakeState struct {
  21. c *Conn
  22. serverHello *serverHelloMsg
  23. hello *clientHelloMsg
  24. suite *cipherSuite
  25. masterSecret []byte
  26. session *ClientSessionState
  27. // TLS 1.0-1.2 fields
  28. finishedHash finishedHash
  29. // TLS 1.3 fields
  30. keySchedule *keySchedule13
  31. privateKey []byte
  32. }
  33. func makeClientHello(config *Config) (*clientHelloMsg, error) {
  34. if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
  35. return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  36. }
  37. nextProtosLength := 0
  38. for _, proto := range config.NextProtos {
  39. if l := len(proto); l == 0 || l > 255 {
  40. return nil, errors.New("tls: invalid NextProtos value")
  41. } else {
  42. nextProtosLength += 1 + l
  43. }
  44. }
  45. if nextProtosLength > 0xffff {
  46. return nil, errors.New("tls: NextProtos values too large")
  47. }
  48. if config.ClientHelloPRNGSeed == nil {
  49. return nil, errors.New("tls: missing Config.ClientHelloPRNGSeed")
  50. }
  51. hello := &clientHelloMsg{
  52. vers: config.maxVersion(),
  53. compressionMethods: []uint8{compressionNone},
  54. random: make([]byte, 32),
  55. ocspStapling: true,
  56. scts: true,
  57. serverName: hostnameInSNI(config.ServerName),
  58. supportedCurves: config.curvePreferences(),
  59. supportedPoints: []uint8{pointFormatUncompressed},
  60. nextProtoNeg: len(config.NextProtos) > 0,
  61. secureRenegotiationSupported: true,
  62. delegatedCredential: config.AcceptDelegatedCredential,
  63. alpnProtocols: config.NextProtos,
  64. extendedMSSupported: config.UseExtendedMasterSecret,
  65. // [Psiphon]
  66. clientHelloPRNGSeed: config.ClientHelloPRNGSeed,
  67. }
  68. possibleCipherSuites := config.cipherSuites()
  69. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  70. NextCipherSuite:
  71. for _, suiteId := range possibleCipherSuites {
  72. for _, suite := range cipherSuites {
  73. if suite.id != suiteId {
  74. continue
  75. }
  76. // Don't advertise TLS 1.2-only cipher suites unless
  77. // we're attempting TLS 1.2.
  78. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  79. continue NextCipherSuite
  80. }
  81. // Don't advertise TLS 1.3-only cipher suites unless
  82. // we're attempting TLS 1.3.
  83. if hello.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
  84. continue NextCipherSuite
  85. }
  86. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  87. continue NextCipherSuite
  88. }
  89. }
  90. _, err := io.ReadFull(config.rand(), hello.random)
  91. if err != nil {
  92. return nil, errors.New("tls: short read from Rand: " + err.Error())
  93. }
  94. if hello.vers >= VersionTLS12 {
  95. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  96. }
  97. if hello.vers >= VersionTLS13 {
  98. // Version preference is indicated via "supported_extensions",
  99. // set legacy_version to TLS 1.2 for backwards compatibility.
  100. hello.vers = VersionTLS12
  101. hello.supportedVersions = config.getSupportedVersions()
  102. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms13
  103. hello.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13)
  104. }
  105. return hello, nil
  106. }
  107. // c.out.Mutex <= L; c.handshakeMutex <= L.
  108. func (c *Conn) clientHandshake() error {
  109. if c.config == nil {
  110. c.config = defaultConfig()
  111. }
  112. // This may be a renegotiation handshake, in which case some fields
  113. // need to be reset.
  114. c.didResume = false
  115. hello, err := makeClientHello(c.config)
  116. if err != nil {
  117. return err
  118. }
  119. if c.handshakes > 0 {
  120. hello.secureRenegotiation = c.clientFinished[:]
  121. }
  122. var session *ClientSessionState
  123. var cacheKey string
  124. sessionCache := c.config.ClientSessionCache
  125. // TLS 1.3 has no session resumption based on session tickets.
  126. if c.config.SessionTicketsDisabled || c.config.maxVersion() >= VersionTLS13 {
  127. sessionCache = nil
  128. }
  129. if sessionCache != nil {
  130. hello.ticketSupported = true
  131. }
  132. // Session resumption is not allowed if renegotiating because
  133. // renegotiation is primarily used to allow a client to send a client
  134. // certificate, which would be skipped if session resumption occurred.
  135. if sessionCache != nil && c.handshakes == 0 {
  136. // Try to resume a previously negotiated TLS session, if
  137. // available.
  138. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  139. candidateSession, ok := sessionCache.Get(cacheKey)
  140. if ok {
  141. // Check that the ciphersuite/version used for the
  142. // previous session are still valid.
  143. cipherSuiteOk := false
  144. for _, id := range hello.cipherSuites {
  145. if id == candidateSession.cipherSuite {
  146. cipherSuiteOk = true
  147. break
  148. }
  149. }
  150. versOk := candidateSession.vers >= c.config.minVersion() &&
  151. candidateSession.vers <= c.config.maxVersion()
  152. if versOk && cipherSuiteOk {
  153. session = candidateSession
  154. }
  155. }
  156. }
  157. if session != nil {
  158. hello.sessionTicket = session.sessionTicket
  159. // A random session ID is used to detect when the
  160. // server accepted the ticket and is resuming a session
  161. // (see RFC 5077).
  162. hello.sessionId = make([]byte, 16)
  163. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  164. return errors.New("tls: short read from Rand: " + err.Error())
  165. }
  166. }
  167. hs := &clientHandshakeState{
  168. c: c,
  169. hello: hello,
  170. session: session,
  171. }
  172. var clientKS keyShare
  173. if c.config.maxVersion() >= VersionTLS13 {
  174. // Create one keyshare for the first default curve. If it is not
  175. // appropriate, the server should raise a HRR.
  176. defaultGroup := c.config.curvePreferences()[0]
  177. hs.privateKey, clientKS, err = c.config.generateKeyShare(defaultGroup)
  178. if err != nil {
  179. c.sendAlert(alertInternalError)
  180. return err
  181. }
  182. hello.keyShares = []keyShare{clientKS}
  183. // middlebox compatibility mode, provide a non-empty session ID
  184. hello.sessionId = make([]byte, 16)
  185. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  186. return errors.New("tls: short read from Rand: " + err.Error())
  187. }
  188. }
  189. if err = hs.handshake(); err != nil {
  190. return err
  191. }
  192. // If we had a successful handshake and hs.session is different from
  193. // the one already cached - cache a new one
  194. if sessionCache != nil && hs.session != nil && session != hs.session && c.vers < VersionTLS13 {
  195. sessionCache.Put(cacheKey, hs.session)
  196. }
  197. return nil
  198. }
  199. // Does the handshake, either a full one or resumes old session.
  200. // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
  201. func (hs *clientHandshakeState) handshake() error {
  202. c := hs.c
  203. // send ClientHello
  204. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  205. return err
  206. }
  207. msg, err := c.readHandshake()
  208. if err != nil {
  209. return err
  210. }
  211. var ok bool
  212. if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
  213. c.sendAlert(alertUnexpectedMessage)
  214. return unexpectedMessageError(hs.serverHello, msg)
  215. }
  216. if err = hs.pickTLSVersion(); err != nil {
  217. return err
  218. }
  219. if err = hs.pickCipherSuite(); err != nil {
  220. return err
  221. }
  222. var isResume bool
  223. if c.vers >= VersionTLS13 {
  224. hs.keySchedule = newKeySchedule13(hs.suite, c.config, hs.hello.random)
  225. hs.keySchedule.write(hs.hello.marshal())
  226. hs.keySchedule.write(hs.serverHello.marshal())
  227. } else {
  228. isResume, err = hs.processServerHello()
  229. if err != nil {
  230. return err
  231. }
  232. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  233. // No signatures of the handshake are needed in a resumption.
  234. // Otherwise, in a full handshake, if we don't have any certificates
  235. // configured then we will never send a CertificateVerify message and
  236. // thus no signatures are needed in that case either.
  237. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  238. hs.finishedHash.discardHandshakeBuffer()
  239. }
  240. hs.finishedHash.Write(hs.hello.marshal())
  241. hs.finishedHash.Write(hs.serverHello.marshal())
  242. }
  243. c.buffering = true
  244. if c.vers >= VersionTLS13 {
  245. if err := hs.doTLS13Handshake(); err != nil {
  246. return err
  247. }
  248. if _, err := c.flush(); err != nil {
  249. return err
  250. }
  251. } else if isResume {
  252. if err := hs.establishKeys(); err != nil {
  253. return err
  254. }
  255. if err := hs.readSessionTicket(); err != nil {
  256. return err
  257. }
  258. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  259. return err
  260. }
  261. c.clientFinishedIsFirst = false
  262. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  263. return err
  264. }
  265. if _, err := c.flush(); err != nil {
  266. return err
  267. }
  268. } else {
  269. if err := hs.doFullHandshake(); err != nil {
  270. return err
  271. }
  272. if err := hs.establishKeys(); err != nil {
  273. return err
  274. }
  275. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  276. return err
  277. }
  278. if _, err := c.flush(); err != nil {
  279. return err
  280. }
  281. c.clientFinishedIsFirst = true
  282. if err := hs.readSessionTicket(); err != nil {
  283. return err
  284. }
  285. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  286. return err
  287. }
  288. }
  289. c.didResume = isResume
  290. c.phase = handshakeConfirmed
  291. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  292. c.handshakeComplete = true
  293. return nil
  294. }
  295. func (hs *clientHandshakeState) pickTLSVersion() error {
  296. vers, ok := hs.c.config.pickVersion([]uint16{hs.serverHello.vers})
  297. if !ok || vers < VersionTLS10 {
  298. // TLS 1.0 is the minimum version supported as a client.
  299. hs.c.sendAlert(alertProtocolVersion)
  300. return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
  301. }
  302. hs.c.vers = vers
  303. hs.c.haveVers = true
  304. return nil
  305. }
  306. func (hs *clientHandshakeState) pickCipherSuite() error {
  307. if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
  308. hs.c.sendAlert(alertHandshakeFailure)
  309. return errors.New("tls: server chose an unconfigured cipher suite")
  310. }
  311. // Check that the chosen cipher suite matches the protocol version.
  312. if hs.c.vers >= VersionTLS13 && hs.suite.flags&suiteTLS13 == 0 ||
  313. hs.c.vers < VersionTLS13 && hs.suite.flags&suiteTLS13 != 0 {
  314. hs.c.sendAlert(alertHandshakeFailure)
  315. return errors.New("tls: server chose an inappropriate cipher suite")
  316. }
  317. hs.c.cipherSuite = hs.suite.id
  318. return nil
  319. }
  320. // processCertsFromServer takes a chain of server certificates from a
  321. // Certificate message and verifies them.
  322. func (hs *clientHandshakeState) processCertsFromServer(certificates [][]byte) error {
  323. c := hs.c
  324. certs := make([]*x509.Certificate, len(certificates))
  325. for i, asn1Data := range certificates {
  326. cert, err := x509.ParseCertificate(asn1Data)
  327. if err != nil {
  328. c.sendAlert(alertBadCertificate)
  329. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  330. }
  331. certs[i] = cert
  332. }
  333. if !c.config.InsecureSkipVerify {
  334. opts := x509.VerifyOptions{
  335. Roots: c.config.RootCAs,
  336. CurrentTime: c.config.time(),
  337. DNSName: c.config.ServerName,
  338. Intermediates: x509.NewCertPool(),
  339. }
  340. for i, cert := range certs {
  341. if i == 0 {
  342. continue
  343. }
  344. opts.Intermediates.AddCert(cert)
  345. }
  346. var err error
  347. c.verifiedChains, err = certs[0].Verify(opts)
  348. if err != nil {
  349. c.sendAlert(alertBadCertificate)
  350. return err
  351. }
  352. }
  353. if c.config.VerifyPeerCertificate != nil {
  354. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  355. c.sendAlert(alertBadCertificate)
  356. return err
  357. }
  358. }
  359. switch certs[0].PublicKey.(type) {
  360. case *rsa.PublicKey, *ecdsa.PublicKey:
  361. break
  362. default:
  363. c.sendAlert(alertUnsupportedCertificate)
  364. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  365. }
  366. c.peerCertificates = certs
  367. return nil
  368. }
  369. // processDelegatedCredentialFromServer unmarshals the delegated credential
  370. // offered by the server (if present) and validates it using the peer
  371. // certificate and the signature scheme (`scheme`) indicated by the server in
  372. // the "signature_scheme" extension.
  373. func (hs *clientHandshakeState) processDelegatedCredentialFromServer(serialized []byte, scheme SignatureScheme) error {
  374. c := hs.c
  375. var dc *delegatedCredential
  376. var err error
  377. if serialized != nil {
  378. // Assert that the DC extension was indicated by the client.
  379. if !hs.hello.delegatedCredential {
  380. c.sendAlert(alertUnexpectedMessage)
  381. return errors.New("tls: got delegated credential extension without indication")
  382. }
  383. // Parse the delegated credential.
  384. dc, err = unmarshalDelegatedCredential(serialized)
  385. if err != nil {
  386. c.sendAlert(alertDecodeError)
  387. return fmt.Errorf("tls: delegated credential: %s", err)
  388. }
  389. }
  390. if dc != nil && !c.config.InsecureSkipVerify {
  391. if v, err := dc.validate(c.peerCertificates[0], c.config.time()); err != nil {
  392. c.sendAlert(alertIllegalParameter)
  393. return fmt.Errorf("delegated credential: %s", err)
  394. } else if !v {
  395. c.sendAlert(alertIllegalParameter)
  396. return errors.New("delegated credential: signature invalid")
  397. } else if dc.cred.expectedVersion != hs.c.vers {
  398. c.sendAlert(alertIllegalParameter)
  399. return errors.New("delegated credential: protocol version mismatch")
  400. } else if dc.cred.expectedCertVerifyAlgorithm != scheme {
  401. c.sendAlert(alertIllegalParameter)
  402. return errors.New("delegated credential: signature scheme mismatch")
  403. }
  404. }
  405. c.verifiedDc = dc
  406. return nil
  407. }
  408. func (hs *clientHandshakeState) doFullHandshake() error {
  409. c := hs.c
  410. msg, err := c.readHandshake()
  411. if err != nil {
  412. return err
  413. }
  414. certMsg, ok := msg.(*certificateMsg)
  415. if !ok || len(certMsg.certificates) == 0 {
  416. c.sendAlert(alertUnexpectedMessage)
  417. return unexpectedMessageError(certMsg, msg)
  418. }
  419. hs.finishedHash.Write(certMsg.marshal())
  420. if c.handshakes == 0 {
  421. // If this is the first handshake on a connection, process and
  422. // (optionally) verify the server's certificates.
  423. if err := hs.processCertsFromServer(certMsg.certificates); err != nil {
  424. return err
  425. }
  426. } else {
  427. // This is a renegotiation handshake. We require that the
  428. // server's identity (i.e. leaf certificate) is unchanged and
  429. // thus any previous trust decision is still valid.
  430. //
  431. // See https://mitls.org/pages/attacks/3SHAKE for the
  432. // motivation behind this requirement.
  433. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  434. c.sendAlert(alertBadCertificate)
  435. return errors.New("tls: server's identity changed during renegotiation")
  436. }
  437. }
  438. msg, err = c.readHandshake()
  439. if err != nil {
  440. return err
  441. }
  442. cs, ok := msg.(*certificateStatusMsg)
  443. if ok {
  444. // RFC4366 on Certificate Status Request:
  445. // The server MAY return a "certificate_status" message.
  446. if !hs.serverHello.ocspStapling {
  447. // If a server returns a "CertificateStatus" message, then the
  448. // server MUST have included an extension of type "status_request"
  449. // with empty "extension_data" in the extended server hello.
  450. c.sendAlert(alertUnexpectedMessage)
  451. return errors.New("tls: received unexpected CertificateStatus message")
  452. }
  453. hs.finishedHash.Write(cs.marshal())
  454. if cs.statusType == statusTypeOCSP {
  455. c.ocspResponse = cs.response
  456. }
  457. msg, err = c.readHandshake()
  458. if err != nil {
  459. return err
  460. }
  461. }
  462. keyAgreement := hs.suite.ka(c.vers)
  463. // Set the public key used to verify the handshake.
  464. pk := c.peerCertificates[0].PublicKey
  465. skx, ok := msg.(*serverKeyExchangeMsg)
  466. if ok {
  467. hs.finishedHash.Write(skx.marshal())
  468. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, pk, skx)
  469. if err != nil {
  470. c.sendAlert(alertUnexpectedMessage)
  471. return err
  472. }
  473. msg, err = c.readHandshake()
  474. if err != nil {
  475. return err
  476. }
  477. }
  478. var chainToSend *Certificate
  479. var certRequested bool
  480. certReq, ok := msg.(*certificateRequestMsg)
  481. if ok {
  482. certRequested = true
  483. hs.finishedHash.Write(certReq.marshal())
  484. if chainToSend, err = hs.getCertificate(certReq); err != nil {
  485. c.sendAlert(alertInternalError)
  486. return err
  487. }
  488. msg, err = c.readHandshake()
  489. if err != nil {
  490. return err
  491. }
  492. }
  493. shd, ok := msg.(*serverHelloDoneMsg)
  494. if !ok {
  495. c.sendAlert(alertUnexpectedMessage)
  496. return unexpectedMessageError(shd, msg)
  497. }
  498. hs.finishedHash.Write(shd.marshal())
  499. // If the server requested a certificate then we have to send a
  500. // Certificate message, even if it's empty because we don't have a
  501. // certificate to send.
  502. if certRequested {
  503. certMsg = new(certificateMsg)
  504. certMsg.certificates = chainToSend.Certificate
  505. hs.finishedHash.Write(certMsg.marshal())
  506. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  507. return err
  508. }
  509. }
  510. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, pk)
  511. if err != nil {
  512. c.sendAlert(alertInternalError)
  513. return err
  514. }
  515. if ckx != nil {
  516. hs.finishedHash.Write(ckx.marshal())
  517. if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
  518. return err
  519. }
  520. }
  521. c.useEMS = hs.serverHello.extendedMSSupported
  522. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random, hs.finishedHash, c.useEMS)
  523. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.hello.random, hs.masterSecret); err != nil {
  524. c.sendAlert(alertInternalError)
  525. return errors.New("tls: failed to write to key log: " + err.Error())
  526. }
  527. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  528. certVerify := &certificateVerifyMsg{
  529. hasSignatureAndHash: c.vers >= VersionTLS12,
  530. }
  531. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  532. if !ok {
  533. c.sendAlert(alertInternalError)
  534. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  535. }
  536. signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
  537. if err != nil {
  538. c.sendAlert(alertInternalError)
  539. return err
  540. }
  541. // SignatureAndHashAlgorithm was introduced in TLS 1.2.
  542. if certVerify.hasSignatureAndHash {
  543. certVerify.signatureAlgorithm = signatureAlgorithm
  544. }
  545. digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
  546. if err != nil {
  547. c.sendAlert(alertInternalError)
  548. return err
  549. }
  550. signOpts := crypto.SignerOpts(hashFunc)
  551. if sigType == signatureRSAPSS {
  552. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
  553. }
  554. certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
  555. if err != nil {
  556. c.sendAlert(alertInternalError)
  557. return err
  558. }
  559. hs.finishedHash.Write(certVerify.marshal())
  560. if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
  561. return err
  562. }
  563. }
  564. hs.finishedHash.discardHandshakeBuffer()
  565. return nil
  566. }
  567. func (hs *clientHandshakeState) establishKeys() error {
  568. c := hs.c
  569. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  570. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  571. var clientCipher, serverCipher interface{}
  572. var clientHash, serverHash macFunction
  573. if hs.suite.cipher != nil {
  574. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  575. clientHash = hs.suite.mac(c.vers, clientMAC)
  576. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  577. serverHash = hs.suite.mac(c.vers, serverMAC)
  578. } else {
  579. clientCipher = hs.suite.aead(clientKey, clientIV)
  580. serverCipher = hs.suite.aead(serverKey, serverIV)
  581. }
  582. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  583. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  584. return nil
  585. }
  586. func (hs *clientHandshakeState) serverResumedSession() bool {
  587. // If the server responded with the same sessionId then it means the
  588. // sessionTicket is being used to resume a TLS session.
  589. return hs.session != nil && hs.hello.sessionId != nil &&
  590. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  591. }
  592. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  593. c := hs.c
  594. if hs.serverHello.compressionMethod != compressionNone {
  595. c.sendAlert(alertUnexpectedMessage)
  596. return false, errors.New("tls: server selected unsupported compression format")
  597. }
  598. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  599. c.secureRenegotiation = true
  600. if len(hs.serverHello.secureRenegotiation) != 0 {
  601. c.sendAlert(alertHandshakeFailure)
  602. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  603. }
  604. }
  605. if c.handshakes > 0 && c.secureRenegotiation {
  606. var expectedSecureRenegotiation [24]byte
  607. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  608. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  609. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  610. c.sendAlert(alertHandshakeFailure)
  611. return false, errors.New("tls: incorrect renegotiation extension contents")
  612. }
  613. }
  614. if hs.serverHello.extendedMSSupported {
  615. if hs.hello.extendedMSSupported {
  616. c.useEMS = true
  617. } else {
  618. // server wants to calculate master secret in a different way than client
  619. c.sendAlert(alertUnsupportedExtension)
  620. return false, errors.New("tls: unexpected extension (EMS) received in SH")
  621. }
  622. }
  623. clientDidNPN := hs.hello.nextProtoNeg
  624. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  625. serverHasNPN := hs.serverHello.nextProtoNeg
  626. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  627. if !clientDidNPN && serverHasNPN {
  628. c.sendAlert(alertHandshakeFailure)
  629. return false, errors.New("tls: server advertised unrequested NPN extension")
  630. }
  631. if !clientDidALPN && serverHasALPN {
  632. c.sendAlert(alertHandshakeFailure)
  633. return false, errors.New("tls: server advertised unrequested ALPN extension")
  634. }
  635. if serverHasNPN && serverHasALPN {
  636. c.sendAlert(alertHandshakeFailure)
  637. return false, errors.New("tls: server advertised both NPN and ALPN extensions")
  638. }
  639. if serverHasALPN {
  640. c.clientProtocol = hs.serverHello.alpnProtocol
  641. c.clientProtocolFallback = false
  642. }
  643. c.scts = hs.serverHello.scts
  644. if !hs.serverResumedSession() {
  645. return false, nil
  646. }
  647. if hs.session.useEMS != c.useEMS {
  648. return false, errors.New("differing EMS state")
  649. }
  650. if hs.session.vers != c.vers {
  651. c.sendAlert(alertHandshakeFailure)
  652. return false, errors.New("tls: server resumed a session with a different version")
  653. }
  654. if hs.session.cipherSuite != hs.suite.id {
  655. c.sendAlert(alertHandshakeFailure)
  656. return false, errors.New("tls: server resumed a session with a different cipher suite")
  657. }
  658. // Restore masterSecret and peerCerts from previous state
  659. hs.masterSecret = hs.session.masterSecret
  660. c.peerCertificates = hs.session.serverCertificates
  661. c.verifiedChains = hs.session.verifiedChains
  662. return true, nil
  663. }
  664. func (hs *clientHandshakeState) readFinished(out []byte) error {
  665. c := hs.c
  666. c.readRecord(recordTypeChangeCipherSpec)
  667. if c.in.err != nil {
  668. return c.in.err
  669. }
  670. msg, err := c.readHandshake()
  671. if err != nil {
  672. return err
  673. }
  674. serverFinished, ok := msg.(*finishedMsg)
  675. if !ok {
  676. c.sendAlert(alertUnexpectedMessage)
  677. return unexpectedMessageError(serverFinished, msg)
  678. }
  679. verify := hs.finishedHash.serverSum(hs.masterSecret)
  680. if len(verify) != len(serverFinished.verifyData) ||
  681. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  682. c.sendAlert(alertDecryptError)
  683. return errors.New("tls: server's Finished message was incorrect")
  684. }
  685. hs.finishedHash.Write(serverFinished.marshal())
  686. copy(out, verify)
  687. return nil
  688. }
  689. func (hs *clientHandshakeState) readSessionTicket() error {
  690. if !hs.serverHello.ticketSupported {
  691. return nil
  692. }
  693. c := hs.c
  694. msg, err := c.readHandshake()
  695. if err != nil {
  696. return err
  697. }
  698. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  699. if !ok {
  700. c.sendAlert(alertUnexpectedMessage)
  701. return unexpectedMessageError(sessionTicketMsg, msg)
  702. }
  703. hs.finishedHash.Write(sessionTicketMsg.marshal())
  704. hs.session = &ClientSessionState{
  705. sessionTicket: sessionTicketMsg.ticket,
  706. vers: c.vers,
  707. cipherSuite: hs.suite.id,
  708. masterSecret: hs.masterSecret,
  709. serverCertificates: c.peerCertificates,
  710. verifiedChains: c.verifiedChains,
  711. useEMS: c.useEMS,
  712. }
  713. return nil
  714. }
  715. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  716. c := hs.c
  717. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  718. return err
  719. }
  720. if hs.serverHello.nextProtoNeg {
  721. nextProto := new(nextProtoMsg)
  722. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  723. nextProto.proto = proto
  724. c.clientProtocol = proto
  725. c.clientProtocolFallback = fallback
  726. hs.finishedHash.Write(nextProto.marshal())
  727. if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
  728. return err
  729. }
  730. }
  731. finished := new(finishedMsg)
  732. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  733. hs.finishedHash.Write(finished.marshal())
  734. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  735. return err
  736. }
  737. copy(out, finished.verifyData)
  738. return nil
  739. }
  740. // tls11SignatureSchemes contains the signature schemes that we synthesise for
  741. // a TLS <= 1.1 connection, based on the supported certificate types.
  742. var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
  743. const (
  744. // tls11SignatureSchemesNumECDSA is the number of initial elements of
  745. // tls11SignatureSchemes that use ECDSA.
  746. tls11SignatureSchemesNumECDSA = 3
  747. // tls11SignatureSchemesNumRSA is the number of trailing elements of
  748. // tls11SignatureSchemes that use RSA.
  749. tls11SignatureSchemesNumRSA = 4
  750. )
  751. func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
  752. c := hs.c
  753. var rsaAvail, ecdsaAvail bool
  754. for _, certType := range certReq.certificateTypes {
  755. switch certType {
  756. case certTypeRSASign:
  757. rsaAvail = true
  758. case certTypeECDSASign:
  759. ecdsaAvail = true
  760. }
  761. }
  762. if c.config.GetClientCertificate != nil {
  763. var signatureSchemes []SignatureScheme
  764. if !certReq.hasSignatureAndHash {
  765. // Prior to TLS 1.2, the signature schemes were not
  766. // included in the certificate request message. In this
  767. // case we use a plausible list based on the acceptable
  768. // certificate types.
  769. signatureSchemes = tls11SignatureSchemes
  770. if !ecdsaAvail {
  771. signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
  772. }
  773. if !rsaAvail {
  774. signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
  775. }
  776. } else {
  777. signatureSchemes = certReq.supportedSignatureAlgorithms
  778. }
  779. return c.config.GetClientCertificate(&CertificateRequestInfo{
  780. AcceptableCAs: certReq.certificateAuthorities,
  781. SignatureSchemes: signatureSchemes,
  782. })
  783. }
  784. // RFC 4346 on the certificateAuthorities field: A list of the
  785. // distinguished names of acceptable certificate authorities.
  786. // These distinguished names may specify a desired
  787. // distinguished name for a root CA or for a subordinate CA;
  788. // thus, this message can be used to describe both known roots
  789. // and a desired authorization space. If the
  790. // certificate_authorities list is empty then the client MAY
  791. // send any certificate of the appropriate
  792. // ClientCertificateType, unless there is some external
  793. // arrangement to the contrary.
  794. // We need to search our list of client certs for one
  795. // where SignatureAlgorithm is acceptable to the server and the
  796. // Issuer is in certReq.certificateAuthorities
  797. findCert:
  798. for i, chain := range c.config.Certificates {
  799. if !rsaAvail && !ecdsaAvail {
  800. continue
  801. }
  802. for j, cert := range chain.Certificate {
  803. x509Cert := chain.Leaf
  804. // parse the certificate if this isn't the leaf
  805. // node, or if chain.Leaf was nil
  806. if j != 0 || x509Cert == nil {
  807. var err error
  808. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  809. c.sendAlert(alertInternalError)
  810. return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
  811. }
  812. }
  813. switch {
  814. case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
  815. case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
  816. default:
  817. continue findCert
  818. }
  819. if len(certReq.certificateAuthorities) == 0 {
  820. // they gave us an empty list, so just take the
  821. // first cert from c.config.Certificates
  822. return &chain, nil
  823. }
  824. for _, ca := range certReq.certificateAuthorities {
  825. if bytes.Equal(x509Cert.RawIssuer, ca) {
  826. return &chain, nil
  827. }
  828. }
  829. }
  830. }
  831. // No acceptable certificate found. Don't send a certificate.
  832. return new(Certificate), nil
  833. }
  834. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  835. // be used to resume previously negotiated TLS sessions with a server.
  836. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  837. if len(config.ServerName) > 0 {
  838. return config.ServerName
  839. }
  840. // [Psiphon]
  841. //
  842. // In certain error conditions, serverAddr may be nil. In this case, since
  843. // ServerName is blank, there is no valid session cache key. Calling code
  844. // assumes clientSessionCacheKey always succeeds. To minimize changes to
  845. // this tls fork, we return "" and no error.
  846. //
  847. // We assume the cache key won't be used for setting the cache, as the
  848. // existing error condition in the conn should result in handshake
  849. // failure. In the unlikely case of success and caching a session, the
  850. // outcome could include future failure to renegotiate, although in the
  851. // case of Psiphon, each connection has its own cache.
  852. if serverAddr == nil {
  853. return ""
  854. }
  855. return serverAddr.String()
  856. }
  857. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  858. // given list of possible protocols and a list of the preference order. The
  859. // first list must not be empty. It returns the resulting protocol and flag
  860. // indicating if the fallback case was reached.
  861. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  862. for _, s := range preferenceProtos {
  863. for _, c := range protos {
  864. if s == c {
  865. return s, false
  866. }
  867. }
  868. }
  869. return protos[0], true
  870. }
  871. // hostnameInSNI converts name into an appropriate hostname for SNI.
  872. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  873. // See https://tools.ietf.org/html/rfc6066#section-3.
  874. func hostnameInSNI(name string) string {
  875. host := name
  876. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  877. host = host[1 : len(host)-1]
  878. }
  879. if i := strings.LastIndex(host, "%"); i > 0 {
  880. host = host[:i]
  881. }
  882. if net.ParseIP(host) != nil {
  883. return ""
  884. }
  885. for len(name) > 0 && name[len(name)-1] == '.' {
  886. name = name[:len(name)-1]
  887. }
  888. return name
  889. }