handshake_server.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. "sync/atomic"
  17. "time"
  18. )
  19. // serverHandshakeState contains details of a server handshake in progress.
  20. // It's discarded once the handshake has completed.
  21. type serverHandshakeState struct {
  22. c *Conn
  23. suite *cipherSuite
  24. masterSecret []byte
  25. cachedClientHelloInfo *ClientHelloInfo
  26. clientHello *clientHelloMsg
  27. hello *serverHelloMsg
  28. cert *Certificate
  29. privateKey crypto.PrivateKey
  30. // A marshalled DelegatedCredential to be sent to the client in the
  31. // handshake.
  32. delegatedCredential []byte
  33. // TLS 1.0-1.2 fields
  34. ellipticOk bool
  35. ecdsaOk bool
  36. rsaDecryptOk bool
  37. rsaSignOk bool
  38. sessionState *sessionState
  39. finishedHash finishedHash
  40. certsFromClient [][]byte
  41. // TLS 1.3 fields
  42. hello13Enc *encryptedExtensionsMsg
  43. keySchedule *keySchedule13
  44. clientFinishedKey []byte
  45. hsClientCipher interface{}
  46. appClientCipher interface{}
  47. }
  48. // serverHandshake performs a TLS handshake as a server.
  49. // c.out.Mutex <= L; c.handshakeMutex <= L.
  50. func (c *Conn) serverHandshake() error {
  51. // If this is the first server handshake, we generate a random key to
  52. // encrypt the tickets with.
  53. c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
  54. hs := serverHandshakeState{
  55. c: c,
  56. }
  57. c.in.traceErr = hs.traceErr
  58. c.out.traceErr = hs.traceErr
  59. isResume, err := hs.readClientHello()
  60. // [Psiphon]
  61. // The ClientHello with the passthrough message is now available. Route the
  62. // client to passthrough based on message inspection. This code assumes the
  63. // client TCP conn has been wrapped with recorderConn, which has recorded
  64. // all bytes sent by the client, which will be replayed, byte-for-byte, to
  65. // the passthrough; as a result, passthrough clients will perform their TLS
  66. // handshake with the passthrough target, receive its certificate, and in the
  67. // case of HTTPS, receive the passthrough target's HTTP responses.
  68. //
  69. // Passthrough is also triggered if readClientHello fails. E.g., on other
  70. // invalid input cases including "tls: handshake message of length..." or if
  71. // the ClientHello is otherwise invalid. This ensures that clients sending
  72. // random data will be relayed to the passthrough and not receive a
  73. // distinguishing error response.
  74. //
  75. // The `tls` API performs handshakes on demand. E.g., the first call to
  76. // tls.Conn.Read will perform a handshake if it's not yet been performed.
  77. // Consumers such as `http` may call Read and then Close. To minimize code
  78. // changes, in the passthrough case the ownership of Conn.conn, the client
  79. // TCP conn, is transferred to the passthrough relay and a closedConn is
  80. // substituted for Conn.conn. This allows the remaining `tls` code paths to
  81. // continue reference a net.Conn, albeit one that is closed, so Reads and
  82. // Writes will fail.
  83. if c.config.PassthroughAddress != "" {
  84. doPassthrough := false
  85. if err != nil {
  86. doPassthrough = true
  87. err = fmt.Errorf("passthrough: %s", err)
  88. }
  89. clientAddr := c.conn.RemoteAddr().String()
  90. clientIP, _, _ := net.SplitHostPort(clientAddr)
  91. if !doPassthrough {
  92. if !c.config.PassthroughVerifyMessage(hs.clientHello.random) {
  93. c.config.PassthroughLogInvalidMessage(clientIP)
  94. doPassthrough = true
  95. err = errors.New("passthrough: invalid client random")
  96. }
  97. }
  98. if !doPassthrough {
  99. if !c.config.PassthroughHistoryAddNew(
  100. clientIP, hs.clientHello.random) {
  101. doPassthrough = true
  102. err = errors.New("passthrough: duplicate client random")
  103. }
  104. }
  105. // Call GetReadBuffer, in both passthrough and non-passthrough cases, to
  106. // stop buffering all read bytes.
  107. passthroughReadBuffer := c.conn.(*recorderConn).GetReadBuffer().Bytes()
  108. if doPassthrough {
  109. // When performing passthrough, we must exit at the "return err" below.
  110. // This is a failsafe to ensure err is always set.
  111. if err == nil {
  112. err = errors.New("passthrough: missing error")
  113. }
  114. // Modifying c.conn directly is safe only because Conn.Handshake, which
  115. // calls Conn.serverHandshake, is holding c.handshakeMutex and c.in locks,
  116. // and because of the serial nature of c.conn access during the handshake
  117. // sequence.
  118. conn := c.conn
  119. c.conn = newClosedConn(conn)
  120. go func() {
  121. // Perform the passthrough relay.
  122. //
  123. // Limitations:
  124. //
  125. // - The local TCP stack may differ from passthrough target in a
  126. // detectable way.
  127. //
  128. // - There may be detectable timing characteristics due to the network hop
  129. // to the passthrough target.
  130. //
  131. // - Application-level socket operations may produce detectable
  132. // differences (e.g., CloseWrite/FIN).
  133. //
  134. // - The dial to the passthrough, or other upstream network operations,
  135. // may fail. These errors are not logged.
  136. //
  137. // - There's no timeout on the passthrough dial and no time limit on the
  138. // passthrough relay so that the invalid client can't detect a timeout
  139. // shorter than the passthrough target; this may cause additional load.
  140. defer conn.Close()
  141. // Remove any pre-existing deadlines to ensure the passthrough
  142. // is not interrupted.
  143. _ = conn.SetDeadline(time.Time{})
  144. passthroughConn, err := net.Dial("tcp", c.config.PassthroughAddress)
  145. if err != nil {
  146. return
  147. }
  148. defer passthroughConn.Close()
  149. _, err = passthroughConn.Write(passthroughReadBuffer)
  150. if err != nil {
  151. return
  152. }
  153. // Allow garbage collection.
  154. passthroughReadBuffer = nil
  155. go func() {
  156. _, _ = io.Copy(passthroughConn, conn)
  157. passthroughConn.Close()
  158. }()
  159. _, _ = io.Copy(conn, passthroughConn)
  160. }()
  161. }
  162. }
  163. if err != nil {
  164. return err
  165. }
  166. // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
  167. // and https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2
  168. c.buffering = true
  169. if c.vers >= VersionTLS13 {
  170. if err := hs.doTLS13Handshake(); err != nil {
  171. return err
  172. }
  173. if _, err := c.flush(); err != nil {
  174. return err
  175. }
  176. c.hs = &hs
  177. // If the client is sending early data while the server expects
  178. // it, delay the Finished check until HandshakeConfirmed() is
  179. // called or until all early data is Read(). Otherwise, complete
  180. // authenticating the client now (there is no support for
  181. // sending 0.5-RTT data to a potential unauthenticated client).
  182. if c.phase != readingEarlyData {
  183. if err := hs.readClientFinished13(false); err != nil {
  184. return err
  185. }
  186. }
  187. atomic.StoreUint32(&c.handshakeStatus, 1)
  188. return nil
  189. } else if isResume {
  190. // The client has included a session ticket and so we do an abbreviated handshake.
  191. if err := hs.doResumeHandshake(); err != nil {
  192. return err
  193. }
  194. if err := hs.establishKeys(); err != nil {
  195. return err
  196. }
  197. // ticketSupported is set in a resumption handshake if the
  198. // ticket from the client was encrypted with an old session
  199. // ticket key and thus a refreshed ticket should be sent.
  200. if hs.hello.ticketSupported {
  201. if err := hs.sendSessionTicket(); err != nil {
  202. return err
  203. }
  204. }
  205. if err := hs.sendFinished(c.serverFinished[:]); err != nil {
  206. return err
  207. }
  208. if _, err := c.flush(); err != nil {
  209. return err
  210. }
  211. c.clientFinishedIsFirst = false
  212. if err := hs.readFinished(nil); err != nil {
  213. return err
  214. }
  215. c.didResume = true
  216. } else {
  217. // The client didn't include a session ticket, or it wasn't
  218. // valid so we do a full handshake.
  219. if err := hs.doFullHandshake(); err != nil {
  220. return err
  221. }
  222. if err := hs.establishKeys(); err != nil {
  223. return err
  224. }
  225. if err := hs.readFinished(c.clientFinished[:]); err != nil {
  226. return err
  227. }
  228. c.clientFinishedIsFirst = true
  229. c.buffering = true
  230. if err := hs.sendSessionTicket(); err != nil {
  231. return err
  232. }
  233. if err := hs.sendFinished(nil); err != nil {
  234. return err
  235. }
  236. if _, err := c.flush(); err != nil {
  237. return err
  238. }
  239. }
  240. if c.hand.Len() > 0 {
  241. return c.sendAlert(alertUnexpectedMessage)
  242. }
  243. c.phase = handshakeConfirmed
  244. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  245. // [Psiphon]
  246. // https://github.com/golang/go/commit/e5b13401c6b19f58a8439f1019a80fe540c0c687
  247. atomic.StoreUint32(&c.handshakeStatus, 1)
  248. return nil
  249. }
  250. // [Psiphon]
  251. // recorderConn is a net.Conn which records all bytes read from the wrapped
  252. // conn until GetReadBuffer is called, which returns the buffered bytes and
  253. // stops recording. This is used to replay, byte-for-byte, the bytes sent by a
  254. // client when switching to passthrough.
  255. //
  256. // recorderConn operations are not safe for concurrent use and intended only
  257. // to be used in the initial phase of the TLS handshake, where the order of
  258. // operations is deterministic.
  259. type recorderConn struct {
  260. net.Conn
  261. readBuffer *bytes.Buffer
  262. }
  263. func newRecorderConn(conn net.Conn) *recorderConn {
  264. return &recorderConn{
  265. Conn: conn,
  266. readBuffer: new(bytes.Buffer),
  267. }
  268. }
  269. func (c *recorderConn) Read(p []byte) (n int, err error) {
  270. n, err = c.Conn.Read(p)
  271. if n > 0 && c.readBuffer != nil {
  272. _, _ = c.readBuffer.Write(p[:n])
  273. }
  274. return n, err
  275. }
  276. func (c *recorderConn) GetReadBuffer() *bytes.Buffer {
  277. b := c.readBuffer
  278. c.readBuffer = nil
  279. return b
  280. }
  281. func (c *recorderConn) IsRecording() bool {
  282. return c.readBuffer != nil
  283. }
  284. // [Psiphon]
  285. // closedConn is a net.Conn which behaves as if it were closed: all reads and
  286. // writes fail. This is used when switching to passthrough mode: ownership of
  287. // the invalid client conn is taken by the passthrough relay and a closedConn
  288. // replaces the network conn used by the local TLS server code path.
  289. type closedConn struct {
  290. localAddr net.Addr
  291. remoteAddr net.Addr
  292. }
  293. var closedClosedError = errors.New("closed")
  294. func newClosedConn(conn net.Conn) *closedConn {
  295. return &closedConn{
  296. localAddr: conn.LocalAddr(),
  297. remoteAddr: conn.RemoteAddr(),
  298. }
  299. }
  300. func (c *closedConn) Read(_ []byte) (int, error) {
  301. return 0, closedClosedError
  302. }
  303. func (c *closedConn) Write(_ []byte) (int, error) {
  304. return 0, closedClosedError
  305. }
  306. func (c *closedConn) Close() error {
  307. return nil
  308. }
  309. func (c *closedConn) LocalAddr() net.Addr {
  310. return c.localAddr
  311. }
  312. func (c *closedConn) RemoteAddr() net.Addr {
  313. return c.remoteAddr
  314. }
  315. func (c *closedConn) SetDeadline(_ time.Time) error {
  316. return closedClosedError
  317. }
  318. func (c *closedConn) SetReadDeadline(_ time.Time) error {
  319. return closedClosedError
  320. }
  321. func (c *closedConn) SetWriteDeadline(_ time.Time) error {
  322. return closedClosedError
  323. }
  324. // readClientHello reads a ClientHello message from the client and decides
  325. // whether we will perform session resumption.
  326. func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
  327. c := hs.c
  328. msg, err := c.readHandshake()
  329. if err != nil {
  330. return false, err
  331. }
  332. var ok bool
  333. hs.clientHello, ok = msg.(*clientHelloMsg)
  334. if !ok {
  335. c.sendAlert(alertUnexpectedMessage)
  336. return false, unexpectedMessageError(hs.clientHello, msg)
  337. }
  338. if c.config.GetConfigForClient != nil {
  339. if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
  340. c.out.traceErr, c.in.traceErr = nil, nil // disable tracing
  341. c.sendAlert(alertInternalError)
  342. return false, err
  343. } else if newConfig != nil {
  344. newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
  345. c.config = newConfig
  346. }
  347. }
  348. var keyShares []CurveID
  349. for _, ks := range hs.clientHello.keyShares {
  350. keyShares = append(keyShares, ks.group)
  351. }
  352. if hs.clientHello.supportedVersions != nil {
  353. c.vers, ok = c.config.pickVersion(hs.clientHello.supportedVersions)
  354. if !ok {
  355. c.sendAlert(alertProtocolVersion)
  356. return false, fmt.Errorf("tls: none of the client versions (%x) are supported", hs.clientHello.supportedVersions)
  357. }
  358. } else {
  359. c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
  360. if !ok {
  361. c.sendAlert(alertProtocolVersion)
  362. return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
  363. }
  364. }
  365. c.haveVers = true
  366. preferredCurves := c.config.curvePreferences()
  367. Curves:
  368. for _, curve := range hs.clientHello.supportedCurves {
  369. for _, supported := range preferredCurves {
  370. if supported == curve {
  371. hs.ellipticOk = true
  372. break Curves
  373. }
  374. }
  375. }
  376. // [Psiphon]
  377. hasSupportedPoints := false
  378. // If present, the supported points extension must include uncompressed.
  379. // Can be absent. This behavior mirrors BoringSSL.
  380. if hs.clientHello.supportedPoints != nil {
  381. supportedPointFormat := false
  382. for _, pointFormat := range hs.clientHello.supportedPoints {
  383. if pointFormat == pointFormatUncompressed {
  384. supportedPointFormat = true
  385. break
  386. }
  387. }
  388. if !supportedPointFormat {
  389. c.sendAlert(alertHandshakeFailure)
  390. return false, errors.New("tls: client does not support uncompressed points")
  391. }
  392. hasSupportedPoints = true
  393. }
  394. foundCompression := false
  395. // We only support null compression, so check that the client offered it.
  396. for _, compression := range hs.clientHello.compressionMethods {
  397. if compression == compressionNone {
  398. foundCompression = true
  399. break
  400. }
  401. }
  402. if !foundCompression {
  403. c.sendAlert(alertIllegalParameter)
  404. return false, errors.New("tls: client does not support uncompressed connections")
  405. }
  406. if len(hs.clientHello.compressionMethods) != 1 && c.vers >= VersionTLS13 {
  407. c.sendAlert(alertIllegalParameter)
  408. return false, errors.New("tls: 1.3 client offered compression")
  409. }
  410. if len(hs.clientHello.secureRenegotiation) != 0 {
  411. c.sendAlert(alertHandshakeFailure)
  412. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  413. }
  414. if c.vers < VersionTLS13 {
  415. hs.hello = new(serverHelloMsg)
  416. hs.hello.vers = c.vers
  417. hs.hello.random = make([]byte, 32)
  418. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  419. if err != nil {
  420. c.sendAlert(alertInternalError)
  421. return false, err
  422. }
  423. hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
  424. hs.hello.compressionMethod = compressionNone
  425. } else {
  426. hs.hello = new(serverHelloMsg)
  427. hs.hello13Enc = new(encryptedExtensionsMsg)
  428. hs.hello.vers = c.vers
  429. hs.hello.random = make([]byte, 32)
  430. hs.hello.sessionId = hs.clientHello.sessionId
  431. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  432. if err != nil {
  433. c.sendAlert(alertInternalError)
  434. return false, err
  435. }
  436. }
  437. // [Psiphon]
  438. // https://github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
  439. if hasSupportedPoints && c.vers < VersionTLS13 {
  440. // Although omitting the ec_point_formats extension is permitted, some
  441. // old OpenSSL versions will refuse to handshake if not present.
  442. //
  443. // Per RFC 4492, section 5.1.2, implementations MUST support the
  444. // uncompressed point format. See golang.org/issue/31943.
  445. hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
  446. }
  447. if len(hs.clientHello.serverName) > 0 {
  448. c.serverName = hs.clientHello.serverName
  449. }
  450. if len(hs.clientHello.alpnProtocols) > 0 {
  451. if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
  452. if hs.hello13Enc != nil {
  453. hs.hello13Enc.alpnProtocol = selectedProto
  454. } else {
  455. hs.hello.alpnProtocol = selectedProto
  456. }
  457. c.clientProtocol = selectedProto
  458. }
  459. } else {
  460. // Although sending an empty NPN extension is reasonable, Firefox has
  461. // had a bug around this. Best to send nothing at all if
  462. // c.config.NextProtos is empty. See
  463. // https://golang.org/issue/5445.
  464. if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 && c.vers < VersionTLS13 {
  465. hs.hello.nextProtoNeg = true
  466. hs.hello.nextProtos = c.config.NextProtos
  467. }
  468. }
  469. hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
  470. if err != nil {
  471. c.sendAlert(alertInternalError)
  472. return false, err
  473. }
  474. // Set the private key for this handshake to the certificate's secret key.
  475. hs.privateKey = hs.cert.PrivateKey
  476. if hs.clientHello.scts {
  477. hs.hello.scts = hs.cert.SignedCertificateTimestamps
  478. }
  479. // Set the private key to the DC private key if the client and server are
  480. // willing to negotiate the delegated credential extension.
  481. //
  482. // Check to see if a DelegatedCredential is available and should be used.
  483. // If one is available, the session is using TLS >= 1.2, and the client
  484. // accepts the delegated credential extension, then set the handshake
  485. // private key to the DC private key.
  486. if c.config.GetDelegatedCredential != nil && hs.clientHello.delegatedCredential && c.vers >= VersionTLS12 {
  487. dc, sk, err := c.config.GetDelegatedCredential(hs.clientHelloInfo(), c.vers)
  488. if err != nil {
  489. c.sendAlert(alertInternalError)
  490. return false, err
  491. }
  492. // Set the handshake private key.
  493. if dc != nil {
  494. hs.privateKey = sk
  495. hs.delegatedCredential = dc
  496. }
  497. }
  498. if priv, ok := hs.privateKey.(crypto.Signer); ok {
  499. switch priv.Public().(type) {
  500. case *ecdsa.PublicKey:
  501. hs.ecdsaOk = true
  502. case *rsa.PublicKey:
  503. hs.rsaSignOk = true
  504. default:
  505. c.sendAlert(alertInternalError)
  506. return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
  507. }
  508. }
  509. if priv, ok := hs.privateKey.(crypto.Decrypter); ok {
  510. switch priv.Public().(type) {
  511. case *rsa.PublicKey:
  512. hs.rsaDecryptOk = true
  513. default:
  514. c.sendAlert(alertInternalError)
  515. return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
  516. }
  517. }
  518. if c.vers != VersionTLS13 && hs.checkForResumption() {
  519. return true, nil
  520. }
  521. var preferenceList, supportedList []uint16
  522. if c.config.PreferServerCipherSuites {
  523. preferenceList = c.config.cipherSuites()
  524. supportedList = hs.clientHello.cipherSuites
  525. } else {
  526. preferenceList = hs.clientHello.cipherSuites
  527. supportedList = c.config.cipherSuites()
  528. }
  529. for _, id := range preferenceList {
  530. if hs.setCipherSuite(id, supportedList, c.vers) {
  531. break
  532. }
  533. }
  534. if hs.suite == nil {
  535. c.sendAlert(alertHandshakeFailure)
  536. return false, errors.New("tls: no cipher suite supported by both client and server")
  537. }
  538. // See https://tools.ietf.org/html/rfc7507.
  539. for _, id := range hs.clientHello.cipherSuites {
  540. if id == TLS_FALLBACK_SCSV {
  541. // The client is doing a fallback connection.
  542. if c.vers < c.config.maxVersion() {
  543. c.sendAlert(alertInappropriateFallback)
  544. return false, errors.New("tls: client using inappropriate protocol fallback")
  545. }
  546. break
  547. }
  548. }
  549. return false, nil
  550. }
  551. // checkForResumption reports whether we should perform resumption on this connection.
  552. func (hs *serverHandshakeState) checkForResumption() bool {
  553. c := hs.c
  554. if c.config.SessionTicketsDisabled {
  555. return false
  556. }
  557. sessionTicket := append([]uint8{}, hs.clientHello.sessionTicket...)
  558. serializedState, usedOldKey := c.decryptTicket(sessionTicket)
  559. hs.sessionState = &sessionState{usedOldKey: usedOldKey}
  560. if hs.sessionState.unmarshal(serializedState) != alertSuccess {
  561. return false
  562. }
  563. // Never resume a session for a different TLS version.
  564. if c.vers != hs.sessionState.vers {
  565. return false
  566. }
  567. // [Psiphon]
  568. // When using obfuscated session tickets, the client-generated session ticket
  569. // state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
  570. // skip this check to ensure the obfuscated session tickets are not
  571. // rejected.
  572. if !c.config.UseObfuscatedSessionTickets {
  573. // Do not resume connections where client support for EMS has changed
  574. if (hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret) != hs.sessionState.usedEMS {
  575. return false
  576. }
  577. }
  578. cipherSuiteOk := false
  579. // Check that the client is still offering the ciphersuite in the session.
  580. for _, id := range hs.clientHello.cipherSuites {
  581. if id == hs.sessionState.cipherSuite {
  582. cipherSuiteOk = true
  583. break
  584. }
  585. }
  586. if !cipherSuiteOk {
  587. return false
  588. }
  589. // Check that we also support the ciphersuite from the session.
  590. if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
  591. return false
  592. }
  593. sessionHasClientCerts := len(hs.sessionState.certificates) != 0
  594. needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
  595. if needClientCerts && !sessionHasClientCerts {
  596. return false
  597. }
  598. if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
  599. return false
  600. }
  601. return true
  602. }
  603. func (hs *serverHandshakeState) doResumeHandshake() error {
  604. c := hs.c
  605. hs.hello.cipherSuite = hs.suite.id
  606. // We echo the client's session ID in the ServerHello to let it know
  607. // that we're doing a resumption.
  608. hs.hello.sessionId = hs.clientHello.sessionId
  609. hs.hello.ticketSupported = hs.sessionState.usedOldKey
  610. hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
  611. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  612. hs.finishedHash.discardHandshakeBuffer()
  613. hs.finishedHash.Write(hs.clientHello.marshal())
  614. hs.finishedHash.Write(hs.hello.marshal())
  615. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  616. return err
  617. }
  618. if len(hs.sessionState.certificates) > 0 {
  619. if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
  620. return err
  621. }
  622. }
  623. hs.masterSecret = hs.sessionState.masterSecret
  624. c.useEMS = hs.sessionState.usedEMS
  625. return nil
  626. }
  627. func (hs *serverHandshakeState) doFullHandshake() error {
  628. c := hs.c
  629. if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  630. hs.hello.ocspStapling = true
  631. }
  632. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
  633. hs.hello.cipherSuite = hs.suite.id
  634. hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
  635. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  636. if c.config.ClientAuth == NoClientCert {
  637. // No need to keep a full record of the handshake if client
  638. // certificates won't be used.
  639. hs.finishedHash.discardHandshakeBuffer()
  640. }
  641. hs.finishedHash.Write(hs.clientHello.marshal())
  642. hs.finishedHash.Write(hs.hello.marshal())
  643. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  644. return err
  645. }
  646. certMsg := new(certificateMsg)
  647. certMsg.certificates = hs.cert.Certificate
  648. hs.finishedHash.Write(certMsg.marshal())
  649. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  650. return err
  651. }
  652. if hs.hello.ocspStapling {
  653. certStatus := new(certificateStatusMsg)
  654. certStatus.statusType = statusTypeOCSP
  655. certStatus.response = hs.cert.OCSPStaple
  656. hs.finishedHash.Write(certStatus.marshal())
  657. if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
  658. return err
  659. }
  660. }
  661. keyAgreement := hs.suite.ka(c.vers)
  662. skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.privateKey, hs.clientHello, hs.hello)
  663. if err != nil {
  664. c.sendAlert(alertHandshakeFailure)
  665. return err
  666. }
  667. if skx != nil {
  668. hs.finishedHash.Write(skx.marshal())
  669. if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
  670. return err
  671. }
  672. }
  673. if c.config.ClientAuth >= RequestClientCert {
  674. // Request a client certificate
  675. certReq := new(certificateRequestMsg)
  676. certReq.certificateTypes = []byte{
  677. byte(certTypeRSASign),
  678. byte(certTypeECDSASign),
  679. }
  680. if c.vers >= VersionTLS12 {
  681. certReq.hasSignatureAndHash = true
  682. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  683. }
  684. // An empty list of certificateAuthorities signals to
  685. // the client that it may send any certificate in response
  686. // to our request. When we know the CAs we trust, then
  687. // we can send them down, so that the client can choose
  688. // an appropriate certificate to give to us.
  689. if c.config.ClientCAs != nil {
  690. certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
  691. }
  692. hs.finishedHash.Write(certReq.marshal())
  693. if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
  694. return err
  695. }
  696. }
  697. helloDone := new(serverHelloDoneMsg)
  698. hs.finishedHash.Write(helloDone.marshal())
  699. if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
  700. return err
  701. }
  702. if _, err := c.flush(); err != nil {
  703. return err
  704. }
  705. var pub crypto.PublicKey // public key for client auth, if any
  706. msg, err := c.readHandshake()
  707. if err != nil {
  708. return err
  709. }
  710. var ok bool
  711. // If we requested a client certificate, then the client must send a
  712. // certificate message, even if it's empty.
  713. if c.config.ClientAuth >= RequestClientCert {
  714. if certMsg, ok = msg.(*certificateMsg); !ok {
  715. c.sendAlert(alertUnexpectedMessage)
  716. return unexpectedMessageError(certMsg, msg)
  717. }
  718. hs.finishedHash.Write(certMsg.marshal())
  719. if len(certMsg.certificates) == 0 {
  720. // The client didn't actually send a certificate
  721. switch c.config.ClientAuth {
  722. case RequireAnyClientCert, RequireAndVerifyClientCert:
  723. c.sendAlert(alertBadCertificate)
  724. return errors.New("tls: client didn't provide a certificate")
  725. }
  726. }
  727. pub, err = hs.processCertsFromClient(certMsg.certificates)
  728. if err != nil {
  729. return err
  730. }
  731. msg, err = c.readHandshake()
  732. if err != nil {
  733. return err
  734. }
  735. }
  736. // Get client key exchange
  737. ckx, ok := msg.(*clientKeyExchangeMsg)
  738. if !ok {
  739. c.sendAlert(alertUnexpectedMessage)
  740. return unexpectedMessageError(ckx, msg)
  741. }
  742. hs.finishedHash.Write(ckx.marshal())
  743. preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.privateKey, ckx, c.vers)
  744. if err != nil {
  745. if err == errClientKeyExchange {
  746. c.sendAlert(alertDecodeError)
  747. } else {
  748. c.sendAlert(alertInternalError)
  749. }
  750. return err
  751. }
  752. c.useEMS = hs.hello.extendedMSSupported
  753. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random, hs.finishedHash, c.useEMS)
  754. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.clientHello.random, hs.masterSecret); err != nil {
  755. c.sendAlert(alertInternalError)
  756. return err
  757. }
  758. // If we received a client cert in response to our certificate request message,
  759. // the client will send us a certificateVerifyMsg immediately after the
  760. // clientKeyExchangeMsg. This message is a digest of all preceding
  761. // handshake-layer messages that is signed using the private key corresponding
  762. // to the client's certificate. This allows us to verify that the client is in
  763. // possession of the private key of the certificate.
  764. if len(c.peerCertificates) > 0 {
  765. msg, err = c.readHandshake()
  766. if err != nil {
  767. return err
  768. }
  769. certVerify, ok := msg.(*certificateVerifyMsg)
  770. if !ok {
  771. c.sendAlert(alertUnexpectedMessage)
  772. return unexpectedMessageError(certVerify, msg)
  773. }
  774. // Determine the signature type.
  775. _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
  776. if err != nil {
  777. c.sendAlert(alertIllegalParameter)
  778. return err
  779. }
  780. var digest []byte
  781. if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
  782. err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
  783. }
  784. if err != nil {
  785. c.sendAlert(alertBadCertificate)
  786. return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
  787. }
  788. hs.finishedHash.Write(certVerify.marshal())
  789. }
  790. hs.finishedHash.discardHandshakeBuffer()
  791. return nil
  792. }
  793. func (hs *serverHandshakeState) establishKeys() error {
  794. c := hs.c
  795. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  796. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  797. var clientCipher, serverCipher interface{}
  798. var clientHash, serverHash macFunction
  799. if hs.suite.aead == nil {
  800. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  801. clientHash = hs.suite.mac(c.vers, clientMAC)
  802. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  803. serverHash = hs.suite.mac(c.vers, serverMAC)
  804. } else {
  805. clientCipher = hs.suite.aead(clientKey, clientIV)
  806. serverCipher = hs.suite.aead(serverKey, serverIV)
  807. }
  808. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  809. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  810. return nil
  811. }
  812. func (hs *serverHandshakeState) readFinished(out []byte) error {
  813. c := hs.c
  814. c.readRecord(recordTypeChangeCipherSpec)
  815. if c.in.err != nil {
  816. return c.in.err
  817. }
  818. if hs.hello.nextProtoNeg {
  819. msg, err := c.readHandshake()
  820. if err != nil {
  821. return err
  822. }
  823. nextProto, ok := msg.(*nextProtoMsg)
  824. if !ok {
  825. c.sendAlert(alertUnexpectedMessage)
  826. return unexpectedMessageError(nextProto, msg)
  827. }
  828. hs.finishedHash.Write(nextProto.marshal())
  829. c.clientProtocol = nextProto.proto
  830. }
  831. msg, err := c.readHandshake()
  832. if err != nil {
  833. return err
  834. }
  835. clientFinished, ok := msg.(*finishedMsg)
  836. if !ok {
  837. c.sendAlert(alertUnexpectedMessage)
  838. return unexpectedMessageError(clientFinished, msg)
  839. }
  840. verify := hs.finishedHash.clientSum(hs.masterSecret)
  841. if len(verify) != len(clientFinished.verifyData) ||
  842. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  843. c.sendAlert(alertDecryptError)
  844. return errors.New("tls: client's Finished message is incorrect")
  845. }
  846. hs.finishedHash.Write(clientFinished.marshal())
  847. copy(out, verify)
  848. return nil
  849. }
  850. func (hs *serverHandshakeState) sendSessionTicket() error {
  851. if !hs.hello.ticketSupported {
  852. return nil
  853. }
  854. c := hs.c
  855. m := new(newSessionTicketMsg)
  856. var err error
  857. state := sessionState{
  858. vers: c.vers,
  859. cipherSuite: hs.suite.id,
  860. masterSecret: hs.masterSecret,
  861. certificates: hs.certsFromClient,
  862. usedEMS: c.useEMS,
  863. }
  864. m.ticket, err = c.encryptTicket(state.marshal())
  865. if err != nil {
  866. return err
  867. }
  868. hs.finishedHash.Write(m.marshal())
  869. if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
  870. return err
  871. }
  872. return nil
  873. }
  874. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  875. c := hs.c
  876. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  877. return err
  878. }
  879. finished := new(finishedMsg)
  880. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  881. hs.finishedHash.Write(finished.marshal())
  882. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  883. return err
  884. }
  885. c.cipherSuite = hs.suite.id
  886. copy(out, finished.verifyData)
  887. return nil
  888. }
  889. // processCertsFromClient takes a chain of client certificates either from a
  890. // Certificates message or from a sessionState and verifies them. It returns
  891. // the public key of the leaf certificate.
  892. func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
  893. c := hs.c
  894. hs.certsFromClient = certificates
  895. certs := make([]*x509.Certificate, len(certificates))
  896. var err error
  897. for i, asn1Data := range certificates {
  898. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  899. c.sendAlert(alertBadCertificate)
  900. return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
  901. }
  902. }
  903. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  904. opts := x509.VerifyOptions{
  905. Roots: c.config.ClientCAs,
  906. CurrentTime: c.config.time(),
  907. Intermediates: x509.NewCertPool(),
  908. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  909. }
  910. for _, cert := range certs[1:] {
  911. opts.Intermediates.AddCert(cert)
  912. }
  913. chains, err := certs[0].Verify(opts)
  914. if err != nil {
  915. c.sendAlert(alertBadCertificate)
  916. return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
  917. }
  918. c.verifiedChains = chains
  919. }
  920. if c.config.VerifyPeerCertificate != nil {
  921. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  922. c.sendAlert(alertBadCertificate)
  923. return nil, err
  924. }
  925. }
  926. if len(certs) == 0 {
  927. return nil, nil
  928. }
  929. var pub crypto.PublicKey
  930. switch key := certs[0].PublicKey.(type) {
  931. case *ecdsa.PublicKey, *rsa.PublicKey:
  932. pub = key
  933. default:
  934. c.sendAlert(alertUnsupportedCertificate)
  935. return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  936. }
  937. c.peerCertificates = certs
  938. return pub, nil
  939. }
  940. // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
  941. // suite if that cipher suite is acceptable to use.
  942. // It returns a bool indicating if the suite was set.
  943. func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
  944. for _, supported := range supportedCipherSuites {
  945. if id == supported {
  946. var candidate *cipherSuite
  947. for _, s := range cipherSuites {
  948. if s.id == id {
  949. candidate = s
  950. break
  951. }
  952. }
  953. if candidate == nil {
  954. continue
  955. }
  956. if version >= VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  957. hs.suite = candidate
  958. return true
  959. }
  960. if version < VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  961. continue
  962. }
  963. // Don't select a ciphersuite which we can't
  964. // support for this client.
  965. if candidate.flags&suiteECDHE != 0 {
  966. if !hs.ellipticOk {
  967. continue
  968. }
  969. if candidate.flags&suiteECDSA != 0 {
  970. if !hs.ecdsaOk {
  971. continue
  972. }
  973. } else if !hs.rsaSignOk {
  974. continue
  975. }
  976. } else if !hs.rsaDecryptOk {
  977. continue
  978. }
  979. if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
  980. continue
  981. }
  982. hs.suite = candidate
  983. return true
  984. }
  985. }
  986. return false
  987. }
  988. // suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
  989. var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  990. func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
  991. if hs.cachedClientHelloInfo != nil {
  992. return hs.cachedClientHelloInfo
  993. }
  994. var supportedVersions []uint16
  995. if hs.clientHello.supportedVersions != nil {
  996. supportedVersions = hs.clientHello.supportedVersions
  997. } else if hs.clientHello.vers > VersionTLS12 {
  998. supportedVersions = suppVersArray[:]
  999. } else if hs.clientHello.vers >= VersionSSL30 {
  1000. supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
  1001. }
  1002. var pskBinder []byte
  1003. if len(hs.clientHello.psks) > 0 {
  1004. pskBinder = hs.clientHello.psks[0].binder
  1005. }
  1006. hs.cachedClientHelloInfo = &ClientHelloInfo{
  1007. CipherSuites: hs.clientHello.cipherSuites,
  1008. ServerName: hs.clientHello.serverName,
  1009. SupportedCurves: hs.clientHello.supportedCurves,
  1010. SupportedPoints: hs.clientHello.supportedPoints,
  1011. SignatureSchemes: hs.clientHello.supportedSignatureAlgorithms,
  1012. SupportedProtos: hs.clientHello.alpnProtocols,
  1013. SupportedVersions: supportedVersions,
  1014. Conn: hs.c.conn,
  1015. Offered0RTTData: hs.clientHello.earlyData,
  1016. AcceptsDelegatedCredential: hs.clientHello.delegatedCredential,
  1017. Fingerprint: pskBinder,
  1018. }
  1019. return hs.cachedClientHelloInfo
  1020. }