handshake_server.go 34 KB

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