TlsServerProtocol.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls
  9. {
  10. public class TlsServerProtocol
  11. : TlsProtocol
  12. {
  13. protected TlsServer m_tlsServer = null;
  14. internal TlsServerContextImpl m_tlsServerContext = null;
  15. protected int[] m_offeredCipherSuites = null;
  16. protected TlsKeyExchange m_keyExchange = null;
  17. protected CertificateRequest m_certificateRequest = null;
  18. /// <summary>Constructor for non-blocking mode.</summary>
  19. /// <remarks>
  20. /// When data is received, use <see cref="TlsProtocol.OfferInput(byte[])"/> to provide the received ciphertext,
  21. /// then use <see cref="TlsProtocol.ReadInput(byte[],int,int)"/> to read the corresponding cleartext.<br/><br/>
  22. /// Similarly, when data needs to be sent, use <see cref="TlsProtocol.WriteApplicationData(byte[],int,int)"/>
  23. /// to provide the cleartext, then use <see cref="TlsProtocol.ReadOutput(byte[],int,int)"/> to get the
  24. /// corresponding ciphertext.
  25. /// </remarks>
  26. public TlsServerProtocol()
  27. : base()
  28. {
  29. }
  30. /// <summary>Constructor for blocking mode.</summary>
  31. /// <param name="stream">The <see cref="Stream"/> of data to/from the server.</param>
  32. public TlsServerProtocol(Stream stream)
  33. : base(stream)
  34. {
  35. }
  36. /// <summary>Constructor for blocking mode.</summary>
  37. /// <param name="input">The <see cref="Stream"/> of data from the server.</param>
  38. /// <param name="output">The <see cref="Stream"/> of data to the server.</param>
  39. public TlsServerProtocol(Stream input, Stream output)
  40. : base(input, output)
  41. {
  42. }
  43. /// <summary>Receives a TLS handshake in the role of server.</summary>
  44. /// <remarks>
  45. /// In blocking mode, this will not return until the handshake is complete. In non-blocking mode, use
  46. /// <see cref="TlsPeer.NotifyHandshakeComplete"/> to receive a callback when the handshake is complete.
  47. /// </remarks>
  48. /// <param name="tlsServer">The <see cref="TlsServer"/> to use for the handshake.</param>
  49. /// <exception cref="IOException">If in blocking mode and handshake was not successful.</exception>
  50. public void Accept(TlsServer tlsServer)
  51. {
  52. if (tlsServer == null)
  53. throw new ArgumentNullException("tlsServer");
  54. if (m_tlsServer != null)
  55. throw new InvalidOperationException("'Accept' can only be called once");
  56. this.m_tlsServer = tlsServer;
  57. this.m_tlsServerContext = new TlsServerContextImpl(tlsServer.Crypto);
  58. tlsServer.Init(m_tlsServerContext);
  59. tlsServer.NotifyCloseHandle(this);
  60. BeginHandshake(false);
  61. if (m_blocking)
  62. {
  63. BlockForHandshake();
  64. }
  65. }
  66. protected override void CleanupHandshake()
  67. {
  68. base.CleanupHandshake();
  69. this.m_offeredCipherSuites = null;
  70. this.m_keyExchange = null;
  71. this.m_certificateRequest = null;
  72. }
  73. protected virtual bool ExpectCertificateVerifyMessage()
  74. {
  75. if (null == m_certificateRequest)
  76. return false;
  77. Certificate clientCertificate = m_tlsServerContext.SecurityParameters.PeerCertificate;
  78. return null != clientCertificate && !clientCertificate.IsEmpty
  79. && (null == m_keyExchange || m_keyExchange.RequiresCertificateVerify);
  80. }
  81. /// <exception cref="IOException"/>
  82. protected virtual ServerHello Generate13HelloRetryRequest(ClientHello clientHello)
  83. {
  84. // TODO[tls13] In future there might be other reasons for a HelloRetryRequest.
  85. if (m_retryGroup < 0)
  86. throw new TlsFatalAlert(AlertDescription.internal_error);
  87. SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters;
  88. ProtocolVersion serverVersion = securityParameters.NegotiatedVersion;
  89. IDictionary serverHelloExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  90. TlsExtensionsUtilities.AddSupportedVersionsExtensionServer(serverHelloExtensions, serverVersion);
  91. if (m_retryGroup >= 0)
  92. {
  93. TlsExtensionsUtilities.AddKeyShareHelloRetryRequest(serverHelloExtensions, m_retryGroup);
  94. }
  95. if (null != m_retryCookie)
  96. {
  97. TlsExtensionsUtilities.AddCookieExtension(serverHelloExtensions, m_retryCookie);
  98. }
  99. TlsUtilities.CheckExtensionData13(serverHelloExtensions, HandshakeType.hello_retry_request,
  100. AlertDescription.internal_error);
  101. return new ServerHello(clientHello.SessionID, securityParameters.CipherSuite, serverHelloExtensions);
  102. }
  103. /// <exception cref="IOException"/>
  104. protected virtual ServerHello Generate13ServerHello(ClientHello clientHello,
  105. HandshakeMessageInput clientHelloMessage, bool afterHelloRetryRequest)
  106. {
  107. SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters;
  108. byte[] legacy_session_id = clientHello.SessionID;
  109. IDictionary clientHelloExtensions = clientHello.Extensions;
  110. if (null == clientHelloExtensions)
  111. throw new TlsFatalAlert(AlertDescription.missing_extension);
  112. ProtocolVersion serverVersion = securityParameters.NegotiatedVersion;
  113. TlsCrypto crypto = m_tlsServerContext.Crypto;
  114. // NOTE: Will only select for psk_dhe_ke
  115. OfferedPsks.SelectedConfig selectedPsk = TlsUtilities.SelectPreSharedKey(m_tlsServerContext, m_tlsServer,
  116. clientHelloExtensions, clientHelloMessage, m_handshakeHash, afterHelloRetryRequest);
  117. IList clientShares = TlsExtensionsUtilities.GetKeyShareClientHello(clientHelloExtensions);
  118. KeyShareEntry clientShare = null;
  119. if (afterHelloRetryRequest)
  120. {
  121. if (m_retryGroup < 0)
  122. throw new TlsFatalAlert(AlertDescription.internal_error);
  123. if (null == selectedPsk)
  124. {
  125. /*
  126. * RFC 8446 4.2.3. If a server is authenticating via a certificate and the client has
  127. * not sent a "signature_algorithms" extension, then the server MUST abort the handshake
  128. * with a "missing_extension" alert.
  129. */
  130. if (null == securityParameters.ClientSigAlgs)
  131. throw new TlsFatalAlert(AlertDescription.missing_extension);
  132. }
  133. else
  134. {
  135. // TODO[tls13] Maybe filter the offered PSKs by PRF algorithm before server selection instead
  136. if (selectedPsk.m_psk.PrfAlgorithm != securityParameters.PrfAlgorithm)
  137. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  138. }
  139. /*
  140. * TODO[tls13] Confirm fields in the ClientHello haven't changed
  141. *
  142. * RFC 8446 4.1.2 [..] when the server has responded to its ClientHello with a
  143. * HelloRetryRequest [..] the client MUST send the same ClientHello without
  144. * modification, except as follows: [key_share, early_data, cookie, pre_shared_key,
  145. * padding].
  146. */
  147. byte[] cookie = TlsExtensionsUtilities.GetCookieExtension(clientHelloExtensions);
  148. if (!Arrays.AreEqual(m_retryCookie, cookie))
  149. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  150. this.m_retryCookie = null;
  151. clientShare = TlsUtilities.SelectKeyShare(clientShares, m_retryGroup);
  152. if (null == clientShare)
  153. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  154. }
  155. else
  156. {
  157. this.m_clientExtensions = clientHelloExtensions;
  158. securityParameters.m_secureRenegotiation = false;
  159. // NOTE: Validates the padding extension data, if present
  160. TlsExtensionsUtilities.GetPaddingExtension(clientHelloExtensions);
  161. securityParameters.m_clientServerNames = TlsExtensionsUtilities
  162. .GetServerNameExtensionClient(clientHelloExtensions);
  163. TlsUtilities.EstablishClientSigAlgs(securityParameters, clientHelloExtensions);
  164. /*
  165. * RFC 8446 4.2.3. If a server is authenticating via a certificate and the client has
  166. * not sent a "signature_algorithms" extension, then the server MUST abort the handshake
  167. * with a "missing_extension" alert.
  168. */
  169. if (null == selectedPsk && null == securityParameters.ClientSigAlgs)
  170. throw new TlsFatalAlert(AlertDescription.missing_extension);
  171. m_tlsServer.ProcessClientExtensions(clientHelloExtensions);
  172. /*
  173. * NOTE: Currently no server support for session resumption
  174. *
  175. * If adding support, ensure securityParameters.tlsUnique is set to the localVerifyData, but
  176. * ONLY when extended_master_secret has been negotiated (otherwise NULL).
  177. */
  178. {
  179. // TODO[tls13] Resumption/PSK
  180. this.m_tlsSession = TlsUtilities.ImportSession(TlsUtilities.EmptyBytes, null);
  181. this.m_sessionParameters = null;
  182. this.m_sessionMasterSecret = null;
  183. }
  184. securityParameters.m_sessionID = m_tlsSession.SessionID;
  185. m_tlsServer.NotifySession(m_tlsSession);
  186. TlsUtilities.NegotiatedVersionTlsServer(m_tlsServerContext);
  187. {
  188. securityParameters.m_serverRandom = CreateRandomBlock(false, m_tlsServerContext);
  189. if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions())))
  190. {
  191. TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom);
  192. }
  193. }
  194. {
  195. // TODO[tls13] Constrain selection when PSK selected
  196. int cipherSuite = m_tlsServer.GetSelectedCipherSuite();
  197. if (!TlsUtilities.IsValidCipherSuiteSelection(m_offeredCipherSuites, cipherSuite) ||
  198. !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, serverVersion))
  199. {
  200. throw new TlsFatalAlert(AlertDescription.internal_error);
  201. }
  202. TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
  203. }
  204. int[] clientSupportedGroups = securityParameters.ClientSupportedGroups;
  205. int[] serverSupportedGroups = securityParameters.ServerSupportedGroups;
  206. clientShare = TlsUtilities.SelectKeyShare(crypto, serverVersion, clientShares, clientSupportedGroups,
  207. serverSupportedGroups);
  208. if (null == clientShare)
  209. {
  210. this.m_retryGroup = TlsUtilities.SelectKeyShareGroup(crypto, serverVersion, clientSupportedGroups,
  211. serverSupportedGroups);
  212. if (m_retryGroup < 0)
  213. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  214. this.m_retryCookie = m_tlsServerContext.NonceGenerator.GenerateNonce(16);
  215. return Generate13HelloRetryRequest(clientHello);
  216. }
  217. if (clientShare.NamedGroup != serverSupportedGroups[0])
  218. {
  219. /*
  220. * TODO[tls13] RFC 8446 4.2.7. As of TLS 1.3, servers are permitted to send the
  221. * "supported_groups" extension to the client. Clients MUST NOT act upon any
  222. * information found in "supported_groups" prior to successful completion of the
  223. * handshake but MAY use the information learned from a successfully completed
  224. * handshake to change what groups they use in their "key_share" extension in
  225. * subsequent connections. If the server has a group it prefers to the ones in the
  226. * "key_share" extension but is still willing to accept the ClientHello, it SHOULD
  227. * send "supported_groups" to update the client's view of its preferences; this
  228. * extension SHOULD contain all groups the server supports, regardless of whether
  229. * they are currently supported by the client.
  230. */
  231. }
  232. }
  233. IDictionary serverHelloExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  234. IDictionary serverEncryptedExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(
  235. m_tlsServer.GetServerExtensions());
  236. m_tlsServer.GetServerExtensionsForConnection(serverEncryptedExtensions);
  237. ProtocolVersion serverLegacyVersion = ProtocolVersion.TLSv12;
  238. TlsExtensionsUtilities.AddSupportedVersionsExtensionServer(serverHelloExtensions, serverVersion);
  239. /*
  240. * RFC 8446 Appendix D. Because TLS 1.3 always hashes in the transcript up to the server
  241. * Finished, implementations which support both TLS 1.3 and earlier versions SHOULD indicate
  242. * the use of the Extended Master Secret extension in their APIs whenever TLS 1.3 is used.
  243. */
  244. securityParameters.m_extendedMasterSecret = true;
  245. /*
  246. * RFC 7301 3.1. When session resumption or session tickets [...] are used, the previous
  247. * contents of this extension are irrelevant, and only the values in the new handshake
  248. * messages are considered.
  249. */
  250. securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(
  251. serverEncryptedExtensions);
  252. securityParameters.m_applicationProtocolSet = true;
  253. if (serverEncryptedExtensions.Count > 0)
  254. {
  255. securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(clientHelloExtensions,
  256. serverEncryptedExtensions, AlertDescription.internal_error);
  257. }
  258. securityParameters.m_encryptThenMac = false;
  259. securityParameters.m_truncatedHmac = false;
  260. /*
  261. * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
  262. *
  263. * OCSP information is carried in an extension for a CertificateEntry.
  264. */
  265. securityParameters.m_statusRequestVersion = clientHelloExtensions.Contains(ExtensionType.status_request)
  266. ? 1 : 0;
  267. this.m_expectSessionTicket = false;
  268. TlsSecret pskEarlySecret = null;
  269. if (null != selectedPsk)
  270. {
  271. pskEarlySecret = selectedPsk.m_earlySecret;
  272. this.m_selectedPsk13 = true;
  273. TlsExtensionsUtilities.AddPreSharedKeyServerHello(serverHelloExtensions, selectedPsk.m_index);
  274. }
  275. TlsSecret sharedSecret;
  276. {
  277. int namedGroup = clientShare.NamedGroup;
  278. TlsAgreement agreement;
  279. if (NamedGroup.RefersToASpecificCurve(namedGroup))
  280. {
  281. agreement = crypto.CreateECDomain(new TlsECConfig(namedGroup)).CreateECDH();
  282. }
  283. else if (NamedGroup.RefersToASpecificFiniteField(namedGroup))
  284. {
  285. agreement = crypto.CreateDHDomain(new TlsDHConfig(namedGroup, true)).CreateDH();
  286. }
  287. else
  288. {
  289. throw new TlsFatalAlert(AlertDescription.internal_error);
  290. }
  291. byte[] key_exchange = agreement.GenerateEphemeral();
  292. KeyShareEntry serverShare = new KeyShareEntry(namedGroup, key_exchange);
  293. TlsExtensionsUtilities.AddKeyShareServerHello(serverHelloExtensions, serverShare);
  294. agreement.ReceivePeerValue(clientShare.KeyExchange);
  295. sharedSecret = agreement.CalculateSecret();
  296. }
  297. TlsUtilities.Establish13PhaseSecrets(m_tlsServerContext, pskEarlySecret, sharedSecret);
  298. this.m_serverExtensions = serverEncryptedExtensions;
  299. ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);
  300. TlsUtilities.CheckExtensionData13(serverHelloExtensions, HandshakeType.server_hello,
  301. AlertDescription.internal_error);
  302. return new ServerHello(serverLegacyVersion, securityParameters.ServerRandom, legacy_session_id,
  303. securityParameters.CipherSuite, serverHelloExtensions);
  304. }
  305. /// <exception cref="IOException"/>
  306. protected virtual ServerHello GenerateServerHello(ClientHello clientHello,
  307. HandshakeMessageInput clientHelloMessage)
  308. {
  309. ProtocolVersion clientLegacyVersion = clientHello.Version;
  310. if (!clientLegacyVersion.IsTls)
  311. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  312. this.m_offeredCipherSuites = clientHello.CipherSuites;
  313. SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters;
  314. m_tlsServerContext.SetClientSupportedVersions(
  315. TlsExtensionsUtilities.GetSupportedVersionsExtensionClient(clientHello.Extensions));
  316. ProtocolVersion clientVersion = clientLegacyVersion;
  317. if (null == m_tlsServerContext.ClientSupportedVersions)
  318. {
  319. if (clientVersion.IsLaterVersionOf(ProtocolVersion.TLSv12))
  320. {
  321. clientVersion = ProtocolVersion.TLSv12;
  322. }
  323. m_tlsServerContext.SetClientSupportedVersions(clientVersion.DownTo(ProtocolVersion.SSLv3));
  324. }
  325. else
  326. {
  327. clientVersion = ProtocolVersion.GetLatestTls(m_tlsServerContext.ClientSupportedVersions);
  328. }
  329. // Set the legacy_record_version to use for early alerts
  330. m_recordStream.SetWriteVersion(clientVersion);
  331. if (!ProtocolVersion.SERVER_EARLIEST_SUPPORTED_TLS.IsEqualOrEarlierVersionOf(clientVersion))
  332. throw new TlsFatalAlert(AlertDescription.protocol_version);
  333. // NOT renegotiating
  334. {
  335. m_tlsServerContext.SetClientVersion(clientVersion);
  336. }
  337. m_tlsServer.NotifyClientVersion(m_tlsServerContext.ClientVersion);
  338. securityParameters.m_clientRandom = clientHello.Random;
  339. m_tlsServer.NotifyFallback(Arrays.Contains(m_offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV));
  340. m_tlsServer.NotifyOfferedCipherSuites(m_offeredCipherSuites);
  341. // TODO[tls13] Negotiate cipher suite first?
  342. ProtocolVersion serverVersion;
  343. // NOT renegotiating
  344. {
  345. serverVersion = m_tlsServer.GetServerVersion();
  346. if (!ProtocolVersion.Contains(m_tlsServerContext.ClientSupportedVersions, serverVersion))
  347. throw new TlsFatalAlert(AlertDescription.internal_error);
  348. securityParameters.m_negotiatedVersion = serverVersion;
  349. }
  350. securityParameters.m_clientSupportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(
  351. clientHello.Extensions);
  352. securityParameters.m_serverSupportedGroups = m_tlsServer.GetSupportedGroups();
  353. if (ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(serverVersion))
  354. {
  355. // See RFC 8446 D.4.
  356. m_recordStream.SetIgnoreChangeCipherSpec(true);
  357. m_recordStream.SetWriteVersion(ProtocolVersion.TLSv12);
  358. return Generate13ServerHello(clientHello, clientHelloMessage, false);
  359. }
  360. m_recordStream.SetWriteVersion(serverVersion);
  361. this.m_clientExtensions = clientHello.Extensions;
  362. byte[] clientRenegExtData = TlsUtilities.GetExtensionData(m_clientExtensions, ExtensionType.renegotiation_info);
  363. // NOT renegotiating
  364. {
  365. /*
  366. * RFC 5746 3.6. Server Behavior: Initial Handshake (both full and session-resumption)
  367. */
  368. /*
  369. * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
  370. * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
  371. * ClientHello. Including both is NOT RECOMMENDED.
  372. */
  373. /*
  374. * When a ClientHello is received, the server MUST check if it includes the
  375. * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If it does, set the secure_renegotiation flag
  376. * to TRUE.
  377. */
  378. if (Arrays.Contains(m_offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV))
  379. {
  380. securityParameters.m_secureRenegotiation = true;
  381. }
  382. /*
  383. * The server MUST check if the "renegotiation_info" extension is included in the
  384. * ClientHello.
  385. */
  386. if (clientRenegExtData != null)
  387. {
  388. /*
  389. * If the extension is present, set secure_renegotiation flag to TRUE. The
  390. * server MUST then verify that the length of the "renegotiated_connection"
  391. * field is zero, and if it is not, MUST abort the handshake.
  392. */
  393. securityParameters.m_secureRenegotiation = true;
  394. if (!Arrays.ConstantTimeAreEqual(clientRenegExtData,
  395. CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
  396. {
  397. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  398. }
  399. }
  400. }
  401. m_tlsServer.NotifySecureRenegotiation(securityParameters.IsSecureRenegotiation);
  402. bool offeredExtendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(
  403. m_clientExtensions);
  404. if (m_clientExtensions != null)
  405. {
  406. // NOTE: Validates the padding extension data, if present
  407. TlsExtensionsUtilities.GetPaddingExtension(m_clientExtensions);
  408. securityParameters.m_clientServerNames = TlsExtensionsUtilities.GetServerNameExtensionClient(
  409. m_clientExtensions);
  410. /*
  411. * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior
  412. * to 1.2. Clients MUST NOT offer it if they are offering prior versions.
  413. */
  414. if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion))
  415. {
  416. TlsUtilities.EstablishClientSigAlgs(securityParameters, m_clientExtensions);
  417. }
  418. securityParameters.m_clientSupportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(
  419. m_clientExtensions);
  420. m_tlsServer.ProcessClientExtensions(m_clientExtensions);
  421. }
  422. this.m_resumedSession = EstablishSession(m_tlsServer.GetSessionToResume(clientHello.SessionID));
  423. if (!m_resumedSession)
  424. {
  425. byte[] newSessionID = m_tlsServer.GetNewSessionID();
  426. if (null == newSessionID)
  427. {
  428. newSessionID = TlsUtilities.EmptyBytes;
  429. }
  430. this.m_tlsSession = TlsUtilities.ImportSession(newSessionID, null);
  431. this.m_sessionParameters = null;
  432. this.m_sessionMasterSecret = null;
  433. }
  434. securityParameters.m_sessionID = m_tlsSession.SessionID;
  435. m_tlsServer.NotifySession(m_tlsSession);
  436. TlsUtilities.NegotiatedVersionTlsServer(m_tlsServerContext);
  437. {
  438. bool useGmtUnixTime = m_tlsServer.ShouldUseGmtUnixTime();
  439. securityParameters.m_serverRandom = CreateRandomBlock(useGmtUnixTime, m_tlsServerContext);
  440. if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions())))
  441. {
  442. TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom);
  443. }
  444. }
  445. {
  446. int cipherSuite = m_resumedSession
  447. ? m_sessionParameters.CipherSuite
  448. : m_tlsServer.GetSelectedCipherSuite();
  449. if (!TlsUtilities.IsValidCipherSuiteSelection(m_offeredCipherSuites, cipherSuite) ||
  450. !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, serverVersion))
  451. {
  452. throw new TlsFatalAlert(AlertDescription.internal_error);
  453. }
  454. TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
  455. }
  456. m_tlsServerContext.SetRsaPreMasterSecretVersion(clientLegacyVersion);
  457. {
  458. IDictionary sessionServerExtensions = m_resumedSession
  459. ? m_sessionParameters.ReadServerExtensions()
  460. : m_tlsServer.GetServerExtensions();
  461. this.m_serverExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(sessionServerExtensions);
  462. }
  463. m_tlsServer.GetServerExtensionsForConnection(m_serverExtensions);
  464. // NOT renegotiating
  465. {
  466. /*
  467. * RFC 5746 3.6. Server Behavior: Initial Handshake (both full and session-resumption)
  468. */
  469. if (securityParameters.IsSecureRenegotiation)
  470. {
  471. byte[] serverRenegExtData = TlsUtilities.GetExtensionData(m_serverExtensions,
  472. ExtensionType.renegotiation_info);
  473. bool noRenegExt = (null == serverRenegExtData);
  474. if (noRenegExt)
  475. {
  476. /*
  477. * Note that sending a "renegotiation_info" extension in response to a ClientHello
  478. * containing only the SCSV is an explicit exception to the prohibition in RFC 5246,
  479. * Section 7.4.1.4, on the server sending unsolicited extensions and is only allowed
  480. * because the client is signaling its willingness to receive the extension via the
  481. * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
  482. */
  483. /*
  484. * If the secure_renegotiation flag is set to TRUE, the server MUST include an empty
  485. * "renegotiation_info" extension in the ServerHello message.
  486. */
  487. this.m_serverExtensions[ExtensionType.renegotiation_info] = CreateRenegotiationInfo(
  488. TlsUtilities.EmptyBytes);
  489. }
  490. }
  491. }
  492. /*
  493. * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended
  494. * master secret [..]. (and see 5.2, 5.3)
  495. */
  496. if (m_resumedSession)
  497. {
  498. if (!m_sessionParameters.IsExtendedMasterSecret)
  499. {
  500. /*
  501. * TODO[resumption] ProvTlsServer currently only resumes EMS sessions. Revisit this
  502. * in relation to 'tlsServer.allowLegacyResumption()'.
  503. */
  504. throw new TlsFatalAlert(AlertDescription.internal_error);
  505. }
  506. if (!offeredExtendedMasterSecret)
  507. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  508. securityParameters.m_extendedMasterSecret = true;
  509. TlsExtensionsUtilities.AddExtendedMasterSecretExtension(m_serverExtensions);
  510. }
  511. else
  512. {
  513. securityParameters.m_extendedMasterSecret = offeredExtendedMasterSecret && !serverVersion.IsSsl
  514. && m_tlsServer.ShouldUseExtendedMasterSecret();
  515. if (securityParameters.IsExtendedMasterSecret)
  516. {
  517. TlsExtensionsUtilities.AddExtendedMasterSecretExtension(m_serverExtensions);
  518. }
  519. else if (m_tlsServer.RequiresExtendedMasterSecret())
  520. {
  521. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  522. }
  523. }
  524. securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(m_serverExtensions);
  525. securityParameters.m_applicationProtocolSet = true;
  526. if (m_serverExtensions.Count > 0)
  527. {
  528. securityParameters.m_encryptThenMac = TlsExtensionsUtilities.HasEncryptThenMacExtension(
  529. m_serverExtensions);
  530. securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(m_clientExtensions,
  531. m_serverExtensions, AlertDescription.internal_error);
  532. securityParameters.m_truncatedHmac = TlsExtensionsUtilities.HasTruncatedHmacExtension(
  533. m_serverExtensions);
  534. if (!m_resumedSession)
  535. {
  536. if (TlsUtilities.HasExpectedEmptyExtensionData(m_serverExtensions, ExtensionType.status_request_v2,
  537. AlertDescription.internal_error))
  538. {
  539. securityParameters.m_statusRequestVersion = 2;
  540. }
  541. else if (TlsUtilities.HasExpectedEmptyExtensionData(m_serverExtensions, ExtensionType.status_request,
  542. AlertDescription.internal_error))
  543. {
  544. securityParameters.m_statusRequestVersion = 1;
  545. }
  546. this.m_expectSessionTicket = TlsUtilities.HasExpectedEmptyExtensionData(m_serverExtensions,
  547. ExtensionType.session_ticket, AlertDescription.internal_error);
  548. }
  549. }
  550. ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);
  551. return new ServerHello(serverVersion, securityParameters.ServerRandom, m_tlsSession.SessionID,
  552. securityParameters.CipherSuite, m_serverExtensions);
  553. }
  554. protected override TlsContext Context
  555. {
  556. get { return m_tlsServerContext; }
  557. }
  558. internal override AbstractTlsContext ContextAdmin
  559. {
  560. get { return m_tlsServerContext; }
  561. }
  562. protected override TlsPeer Peer
  563. {
  564. get { return m_tlsServer; }
  565. }
  566. /// <exception cref="IOException"/>
  567. protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInput buf)
  568. {
  569. if (!IsTlsV13ConnectionState())
  570. throw new TlsFatalAlert(AlertDescription.internal_error);
  571. if (m_resumedSession)
  572. {
  573. /*
  574. * TODO[tls13] Abbreviated handshakes (PSK resumption)
  575. *
  576. * NOTE: No CertificateRequest, Certificate, CertificateVerify messages, but client
  577. * might now send EndOfEarlyData after receiving server Finished message.
  578. */
  579. throw new TlsFatalAlert(AlertDescription.internal_error);
  580. }
  581. switch (type)
  582. {
  583. case HandshakeType.certificate:
  584. {
  585. switch (m_connectionState)
  586. {
  587. case CS_SERVER_FINISHED:
  588. {
  589. Receive13ClientCertificate(buf);
  590. this.m_connectionState = CS_CLIENT_CERTIFICATE;
  591. break;
  592. }
  593. default:
  594. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  595. }
  596. break;
  597. }
  598. case HandshakeType.certificate_verify:
  599. {
  600. switch (m_connectionState)
  601. {
  602. case CS_CLIENT_CERTIFICATE:
  603. {
  604. Receive13ClientCertificateVerify(buf);
  605. buf.UpdateHash(m_handshakeHash);
  606. this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
  607. break;
  608. }
  609. default:
  610. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  611. }
  612. break;
  613. }
  614. case HandshakeType.client_hello:
  615. {
  616. switch (m_connectionState)
  617. {
  618. case CS_START:
  619. {
  620. // NOTE: Legacy handler should be dispatching initial ClientHello.
  621. throw new TlsFatalAlert(AlertDescription.internal_error);
  622. }
  623. case CS_SERVER_HELLO_RETRY_REQUEST:
  624. {
  625. ClientHello clientHelloRetry = ReceiveClientHelloMessage(buf);
  626. this.m_connectionState = CS_CLIENT_HELLO_RETRY;
  627. ServerHello serverHello = Generate13ServerHello(clientHelloRetry, buf, true);
  628. SendServerHelloMessage(serverHello);
  629. this.m_connectionState = CS_SERVER_HELLO;
  630. Send13ServerHelloCoda(serverHello, true);
  631. break;
  632. }
  633. default:
  634. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  635. }
  636. break;
  637. }
  638. case HandshakeType.finished:
  639. {
  640. switch (m_connectionState)
  641. {
  642. case CS_SERVER_FINISHED:
  643. case CS_CLIENT_CERTIFICATE:
  644. case CS_CLIENT_CERTIFICATE_VERIFY:
  645. {
  646. if (m_connectionState == CS_SERVER_FINISHED)
  647. {
  648. Skip13ClientCertificate();
  649. }
  650. if (m_connectionState != CS_CLIENT_CERTIFICATE_VERIFY)
  651. {
  652. Skip13ClientCertificateVerify();
  653. }
  654. Receive13ClientFinished(buf);
  655. this.m_connectionState = CS_CLIENT_FINISHED;
  656. // See RFC 8446 D.4.
  657. m_recordStream.SetIgnoreChangeCipherSpec(false);
  658. // NOTE: Completes the switch to application-data phase (server entered after CS_SERVER_FINISHED).
  659. m_recordStream.EnablePendingCipherRead(false);
  660. CompleteHandshake();
  661. break;
  662. }
  663. default:
  664. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  665. }
  666. break;
  667. }
  668. case HandshakeType.key_update:
  669. {
  670. Receive13KeyUpdate(buf);
  671. break;
  672. }
  673. case HandshakeType.certificate_request:
  674. case HandshakeType.certificate_status:
  675. case HandshakeType.certificate_url:
  676. case HandshakeType.client_key_exchange:
  677. case HandshakeType.encrypted_extensions:
  678. case HandshakeType.end_of_early_data:
  679. case HandshakeType.hello_request:
  680. case HandshakeType.hello_verify_request:
  681. case HandshakeType.message_hash:
  682. case HandshakeType.new_session_ticket:
  683. case HandshakeType.server_hello:
  684. case HandshakeType.server_hello_done:
  685. case HandshakeType.server_key_exchange:
  686. case HandshakeType.supplemental_data:
  687. default:
  688. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  689. }
  690. }
  691. protected override void HandleHandshakeMessage(short type, HandshakeMessageInput buf)
  692. {
  693. SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters;
  694. if (m_connectionState > CS_CLIENT_HELLO
  695. && TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
  696. {
  697. Handle13HandshakeMessage(type, buf);
  698. return;
  699. }
  700. if (!IsLegacyConnectionState())
  701. throw new TlsFatalAlert(AlertDescription.internal_error);
  702. if (m_resumedSession)
  703. {
  704. if (type != HandshakeType.finished || m_connectionState != CS_SERVER_FINISHED)
  705. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  706. ProcessFinishedMessage(buf);
  707. this.m_connectionState = CS_CLIENT_FINISHED;
  708. CompleteHandshake();
  709. return;
  710. }
  711. switch (type)
  712. {
  713. case HandshakeType.client_hello:
  714. {
  715. if (IsApplicationDataReady)
  716. {
  717. RefuseRenegotiation();
  718. break;
  719. }
  720. switch (m_connectionState)
  721. {
  722. case CS_END:
  723. {
  724. throw new TlsFatalAlert(AlertDescription.internal_error);
  725. }
  726. case CS_START:
  727. {
  728. ClientHello clientHello = ReceiveClientHelloMessage(buf);
  729. this.m_connectionState = CS_CLIENT_HELLO;
  730. ServerHello serverHello = GenerateServerHello(clientHello, buf);
  731. m_handshakeHash.NotifyPrfDetermined();
  732. if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
  733. {
  734. m_handshakeHash.SealHashAlgorithms();
  735. if (serverHello.IsHelloRetryRequest())
  736. {
  737. TlsUtilities.AdjustTranscriptForRetry(m_handshakeHash);
  738. SendServerHelloMessage(serverHello);
  739. this.m_connectionState = CS_SERVER_HELLO_RETRY_REQUEST;
  740. // See RFC 8446 D.4.
  741. SendChangeCipherSpecMessage();
  742. }
  743. else
  744. {
  745. SendServerHelloMessage(serverHello);
  746. this.m_connectionState = CS_SERVER_HELLO;
  747. // See RFC 8446 D.4.
  748. SendChangeCipherSpecMessage();
  749. Send13ServerHelloCoda(serverHello, false);
  750. }
  751. break;
  752. }
  753. // For TLS 1.3+, this was already done by GenerateServerHello
  754. buf.UpdateHash(m_handshakeHash);
  755. SendServerHelloMessage(serverHello);
  756. this.m_connectionState = CS_SERVER_HELLO;
  757. if (m_resumedSession)
  758. {
  759. securityParameters.m_masterSecret = m_sessionMasterSecret;
  760. m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsServerContext));
  761. SendChangeCipherSpec();
  762. SendFinishedMessage();
  763. this.m_connectionState = CS_SERVER_FINISHED;
  764. break;
  765. }
  766. IList serverSupplementalData = m_tlsServer.GetServerSupplementalData();
  767. if (serverSupplementalData != null)
  768. {
  769. SendSupplementalDataMessage(serverSupplementalData);
  770. this.m_connectionState = CS_SERVER_SUPPLEMENTAL_DATA;
  771. }
  772. this.m_keyExchange = TlsUtilities.InitKeyExchangeServer(m_tlsServerContext, m_tlsServer);
  773. TlsCredentials serverCredentials = TlsUtilities.EstablishServerCredentials(m_tlsServer);
  774. // Server certificate
  775. {
  776. Certificate serverCertificate = null;
  777. MemoryStream endPointHash = new MemoryStream();
  778. if (null == serverCredentials)
  779. {
  780. m_keyExchange.SkipServerCredentials();
  781. }
  782. else
  783. {
  784. m_keyExchange.ProcessServerCredentials(serverCredentials);
  785. serverCertificate = serverCredentials.Certificate;
  786. SendCertificateMessage(serverCertificate, endPointHash);
  787. this.m_connectionState = CS_SERVER_CERTIFICATE;
  788. }
  789. securityParameters.m_tlsServerEndPoint = endPointHash.ToArray();
  790. // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes
  791. // CertificateStatus
  792. if (null == serverCertificate || serverCertificate.IsEmpty)
  793. {
  794. securityParameters.m_statusRequestVersion = 0;
  795. }
  796. }
  797. if (securityParameters.StatusRequestVersion > 0)
  798. {
  799. CertificateStatus certificateStatus = m_tlsServer.GetCertificateStatus();
  800. if (certificateStatus != null)
  801. {
  802. SendCertificateStatusMessage(certificateStatus);
  803. this.m_connectionState = CS_SERVER_CERTIFICATE_STATUS;
  804. }
  805. }
  806. byte[] serverKeyExchange = m_keyExchange.GenerateServerKeyExchange();
  807. if (serverKeyExchange != null)
  808. {
  809. SendServerKeyExchangeMessage(serverKeyExchange);
  810. this.m_connectionState = CS_SERVER_KEY_EXCHANGE;
  811. }
  812. if (null != serverCredentials)
  813. {
  814. this.m_certificateRequest = m_tlsServer.GetCertificateRequest();
  815. if (null == m_certificateRequest)
  816. {
  817. /*
  818. * For static agreement key exchanges, CertificateRequest is required since
  819. * the client Certificate message is mandatory but can only be sent if the
  820. * server requests it.
  821. */
  822. if (!m_keyExchange.RequiresCertificateVerify)
  823. throw new TlsFatalAlert(AlertDescription.internal_error);
  824. }
  825. else
  826. {
  827. if (TlsUtilities.IsTlsV12(m_tlsServerContext)
  828. != (m_certificateRequest.SupportedSignatureAlgorithms != null))
  829. {
  830. throw new TlsFatalAlert(AlertDescription.internal_error);
  831. }
  832. this.m_certificateRequest = TlsUtilities.ValidateCertificateRequest(m_certificateRequest,
  833. m_keyExchange);
  834. TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest);
  835. TlsUtilities.TrackHashAlgorithms(m_handshakeHash, securityParameters.ServerSigAlgs);
  836. SendCertificateRequestMessage(m_certificateRequest);
  837. this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
  838. }
  839. }
  840. SendServerHelloDoneMessage();
  841. this.m_connectionState = CS_SERVER_HELLO_DONE;
  842. bool forceBuffering = false;
  843. TlsUtilities.SealHandshakeHash(m_tlsServerContext, m_handshakeHash, forceBuffering);
  844. break;
  845. }
  846. default:
  847. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  848. }
  849. break;
  850. }
  851. case HandshakeType.supplemental_data:
  852. {
  853. switch (m_connectionState)
  854. {
  855. case CS_SERVER_HELLO_DONE:
  856. {
  857. m_tlsServer.ProcessClientSupplementalData(ReadSupplementalDataMessage(buf));
  858. this.m_connectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
  859. break;
  860. }
  861. default:
  862. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  863. }
  864. break;
  865. }
  866. case HandshakeType.certificate:
  867. {
  868. switch (m_connectionState)
  869. {
  870. case CS_SERVER_HELLO_DONE:
  871. case CS_CLIENT_SUPPLEMENTAL_DATA:
  872. {
  873. if (m_connectionState != CS_CLIENT_SUPPLEMENTAL_DATA)
  874. {
  875. m_tlsServer.ProcessClientSupplementalData(null);
  876. }
  877. ReceiveCertificateMessage(buf);
  878. this.m_connectionState = CS_CLIENT_CERTIFICATE;
  879. break;
  880. }
  881. default:
  882. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  883. }
  884. break;
  885. }
  886. case HandshakeType.client_key_exchange:
  887. {
  888. switch (m_connectionState)
  889. {
  890. case CS_SERVER_HELLO_DONE:
  891. case CS_CLIENT_SUPPLEMENTAL_DATA:
  892. case CS_CLIENT_CERTIFICATE:
  893. {
  894. if (m_connectionState == CS_SERVER_HELLO_DONE)
  895. {
  896. m_tlsServer.ProcessClientSupplementalData(null);
  897. }
  898. if (m_connectionState != CS_CLIENT_CERTIFICATE)
  899. {
  900. if (null == m_certificateRequest)
  901. {
  902. m_keyExchange.SkipClientCredentials();
  903. }
  904. else if (TlsUtilities.IsTlsV12(m_tlsServerContext))
  905. {
  906. /*
  907. * RFC 5246 If no suitable certificate is available, the client MUST send a
  908. * certificate message containing no certificates.
  909. *
  910. * NOTE: In previous RFCs, this was SHOULD instead of MUST.
  911. */
  912. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  913. }
  914. else if (TlsUtilities.IsSsl(m_tlsServerContext))
  915. {
  916. /*
  917. * SSL 3.0 If the server has sent a certificate request Message, the client must
  918. * send either the certificate message or a no_certificate alert.
  919. */
  920. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  921. }
  922. else
  923. {
  924. NotifyClientCertificate(Certificate.EmptyChain);
  925. }
  926. }
  927. ReceiveClientKeyExchangeMessage(buf);
  928. this.m_connectionState = CS_CLIENT_KEY_EXCHANGE;
  929. break;
  930. }
  931. default:
  932. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  933. }
  934. break;
  935. }
  936. case HandshakeType.certificate_verify:
  937. {
  938. switch (m_connectionState)
  939. {
  940. case CS_CLIENT_KEY_EXCHANGE:
  941. {
  942. /*
  943. * RFC 5246 7.4.8 This message is only sent following a client certificate that has
  944. * signing capability (i.e., all certificates except those containing fixed
  945. * Diffie-Hellman parameters).
  946. */
  947. if (!ExpectCertificateVerifyMessage())
  948. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  949. ReceiveCertificateVerifyMessage(buf);
  950. buf.UpdateHash(m_handshakeHash);
  951. this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
  952. break;
  953. }
  954. default:
  955. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  956. }
  957. break;
  958. }
  959. case HandshakeType.finished:
  960. {
  961. switch (m_connectionState)
  962. {
  963. case CS_CLIENT_KEY_EXCHANGE:
  964. case CS_CLIENT_CERTIFICATE_VERIFY:
  965. {
  966. if (m_connectionState != CS_CLIENT_CERTIFICATE_VERIFY)
  967. {
  968. if (ExpectCertificateVerifyMessage())
  969. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  970. }
  971. ProcessFinishedMessage(buf);
  972. buf.UpdateHash(m_handshakeHash);
  973. this.m_connectionState = CS_CLIENT_FINISHED;
  974. if (m_expectSessionTicket)
  975. {
  976. /*
  977. * TODO[new_session_ticket] Check the server-side rules regarding the session ID, since
  978. * the client is going to ignore any session ID it received once it sees the
  979. * new_session_ticket message.
  980. */
  981. SendNewSessionTicketMessage(m_tlsServer.GetNewSessionTicket());
  982. this.m_connectionState = CS_SERVER_SESSION_TICKET;
  983. }
  984. SendChangeCipherSpec();
  985. SendFinishedMessage();
  986. this.m_connectionState = CS_SERVER_FINISHED;
  987. CompleteHandshake();
  988. break;
  989. }
  990. default:
  991. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  992. }
  993. break;
  994. }
  995. case HandshakeType.certificate_request:
  996. case HandshakeType.certificate_status:
  997. case HandshakeType.certificate_url:
  998. case HandshakeType.encrypted_extensions:
  999. case HandshakeType.end_of_early_data:
  1000. case HandshakeType.hello_request:
  1001. case HandshakeType.hello_verify_request:
  1002. case HandshakeType.key_update:
  1003. case HandshakeType.message_hash:
  1004. case HandshakeType.new_session_ticket:
  1005. case HandshakeType.server_hello:
  1006. case HandshakeType.server_hello_done:
  1007. case HandshakeType.server_key_exchange:
  1008. default:
  1009. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1010. }
  1011. }
  1012. protected override void HandleAlertWarningMessage(short alertDescription)
  1013. {
  1014. /*
  1015. * SSL 3.0 If the server has sent a certificate request Message, the client must send
  1016. * either the certificate message or a no_certificate alert.
  1017. */
  1018. if (AlertDescription.no_certificate == alertDescription && null != m_certificateRequest
  1019. && TlsUtilities.IsSsl(m_tlsServerContext))
  1020. {
  1021. switch (m_connectionState)
  1022. {
  1023. case CS_SERVER_HELLO_DONE:
  1024. case CS_CLIENT_SUPPLEMENTAL_DATA:
  1025. {
  1026. if (m_connectionState != CS_CLIENT_SUPPLEMENTAL_DATA)
  1027. {
  1028. m_tlsServer.ProcessClientSupplementalData(null);
  1029. }
  1030. NotifyClientCertificate(Certificate.EmptyChain);
  1031. this.m_connectionState = CS_CLIENT_CERTIFICATE;
  1032. return;
  1033. }
  1034. }
  1035. }
  1036. base.HandleAlertWarningMessage(alertDescription);
  1037. }
  1038. /// <exception cref="IOException"/>
  1039. protected virtual void NotifyClientCertificate(Certificate clientCertificate)
  1040. {
  1041. if (null == m_certificateRequest)
  1042. throw new TlsFatalAlert(AlertDescription.internal_error);
  1043. TlsUtilities.ProcessClientCertificate(m_tlsServerContext, clientCertificate, m_keyExchange, m_tlsServer);
  1044. }
  1045. /// <exception cref="IOException"/>
  1046. protected virtual void Receive13ClientCertificate(MemoryStream buf)
  1047. {
  1048. // TODO[tls13] This currently just duplicates 'receiveCertificateMessage'
  1049. if (null == m_certificateRequest)
  1050. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1051. Certificate.ParseOptions options = new Certificate.ParseOptions()
  1052. .SetMaxChainLength(m_tlsServer.GetMaxCertificateChainLength());
  1053. Certificate clientCertificate = Certificate.Parse(options, m_tlsServerContext, buf, null);
  1054. AssertEmpty(buf);
  1055. NotifyClientCertificate(clientCertificate);
  1056. }
  1057. /// <exception cref="IOException"/>
  1058. protected void Receive13ClientCertificateVerify(MemoryStream buf)
  1059. {
  1060. Certificate clientCertificate = m_tlsServerContext.SecurityParameters.PeerCertificate;
  1061. if (null == clientCertificate || clientCertificate.IsEmpty)
  1062. throw new TlsFatalAlert(AlertDescription.internal_error);
  1063. // TODO[tls13] Actual structure is 'CertificateVerify' in RFC 8446, consider adding for clarity
  1064. DigitallySigned certificateVerify = DigitallySigned.Parse(m_tlsServerContext, buf);
  1065. AssertEmpty(buf);
  1066. TlsUtilities.Verify13CertificateVerifyClient(m_tlsServerContext, m_certificateRequest, certificateVerify,
  1067. m_handshakeHash);
  1068. }
  1069. /// <exception cref="IOException"/>
  1070. protected virtual void Receive13ClientFinished(MemoryStream buf)
  1071. {
  1072. Process13FinishedMessage(buf);
  1073. }
  1074. /// <exception cref="IOException"/>
  1075. protected virtual void ReceiveCertificateMessage(MemoryStream buf)
  1076. {
  1077. if (null == m_certificateRequest)
  1078. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1079. Certificate.ParseOptions options = new Certificate.ParseOptions()
  1080. .SetMaxChainLength(m_tlsServer.GetMaxCertificateChainLength());
  1081. Certificate clientCertificate = Certificate.Parse(options, m_tlsServerContext, buf, null);
  1082. AssertEmpty(buf);
  1083. NotifyClientCertificate(clientCertificate);
  1084. }
  1085. /// <exception cref="IOException"/>
  1086. protected virtual void ReceiveCertificateVerifyMessage(MemoryStream buf)
  1087. {
  1088. DigitallySigned certificateVerify = DigitallySigned.Parse(m_tlsServerContext, buf);
  1089. AssertEmpty(buf);
  1090. TlsUtilities.VerifyCertificateVerifyClient(m_tlsServerContext, m_certificateRequest, certificateVerify,
  1091. m_handshakeHash);
  1092. this.m_handshakeHash = m_handshakeHash.StopTracking();
  1093. }
  1094. /// <exception cref="IOException"/>
  1095. protected virtual ClientHello ReceiveClientHelloMessage(MemoryStream buf)
  1096. {
  1097. return ClientHello.Parse(buf, null);
  1098. }
  1099. /// <exception cref="IOException"/>
  1100. protected virtual void ReceiveClientKeyExchangeMessage(MemoryStream buf)
  1101. {
  1102. m_keyExchange.ProcessClientKeyExchange(buf);
  1103. AssertEmpty(buf);
  1104. bool isSsl = TlsUtilities.IsSsl(m_tlsServerContext);
  1105. if (isSsl)
  1106. {
  1107. // NOTE: For SSLv3 (only), master_secret needed to calculate session hash
  1108. EstablishMasterSecret(m_tlsServerContext, m_keyExchange);
  1109. }
  1110. m_tlsServerContext.SecurityParameters.m_sessionHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  1111. if (!isSsl)
  1112. {
  1113. // NOTE: For (D)TLS, session hash potentially needed for extended_master_secret
  1114. EstablishMasterSecret(m_tlsServerContext, m_keyExchange);
  1115. }
  1116. m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsServerContext));
  1117. if (!ExpectCertificateVerifyMessage())
  1118. {
  1119. this.m_handshakeHash = m_handshakeHash.StopTracking();
  1120. }
  1121. }
  1122. /// <exception cref="IOException"/>
  1123. protected virtual void Send13EncryptedExtensionsMessage(IDictionary serverExtensions)
  1124. {
  1125. // TODO[tls13] Avoid extra copy; use placeholder to write opaque-16 data directly to message buffer
  1126. byte[] extBytes = WriteExtensionsData(serverExtensions);
  1127. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.encrypted_extensions);
  1128. TlsUtilities.WriteOpaque16(extBytes, message);
  1129. message.Send(this);
  1130. }
  1131. /// <exception cref="IOException"/>
  1132. protected virtual void Send13ServerHelloCoda(ServerHello serverHello, bool afterHelloRetryRequest)
  1133. {
  1134. SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters;
  1135. byte[] serverHelloTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  1136. TlsUtilities.Establish13PhaseHandshake(m_tlsServerContext, serverHelloTranscriptHash, m_recordStream);
  1137. m_recordStream.EnablePendingCipherWrite();
  1138. m_recordStream.EnablePendingCipherRead(true);
  1139. Send13EncryptedExtensionsMessage(m_serverExtensions);
  1140. this.m_connectionState = CS_SERVER_ENCRYPTED_EXTENSIONS;
  1141. if (m_selectedPsk13)
  1142. {
  1143. /*
  1144. * For PSK-only key exchange, there's no CertificateRequest, Certificate, CertificateVerify.
  1145. */
  1146. }
  1147. else
  1148. {
  1149. // CertificateRequest
  1150. {
  1151. this.m_certificateRequest = m_tlsServer.GetCertificateRequest();
  1152. if (null != m_certificateRequest)
  1153. {
  1154. if (!m_certificateRequest.HasCertificateRequestContext(TlsUtilities.EmptyBytes))
  1155. throw new TlsFatalAlert(AlertDescription.internal_error);
  1156. TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest);
  1157. SendCertificateRequestMessage(m_certificateRequest);
  1158. this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
  1159. }
  1160. }
  1161. TlsCredentialedSigner serverCredentials = TlsUtilities.Establish13ServerCredentials(m_tlsServer);
  1162. if (null == serverCredentials)
  1163. throw new TlsFatalAlert(AlertDescription.internal_error);
  1164. // Certificate
  1165. {
  1166. /*
  1167. * TODO[tls13] Note that we are expecting the TlsServer implementation to take care of
  1168. * e.g. adding optional "status_request" extension to each CertificateEntry.
  1169. */
  1170. /*
  1171. * No CertificateStatus message is sent; TLS 1.3 uses per-CertificateEntry
  1172. * "status_request" extension instead.
  1173. */
  1174. Certificate serverCertificate = serverCredentials.Certificate;
  1175. Send13CertificateMessage(serverCertificate);
  1176. securityParameters.m_tlsServerEndPoint = null;
  1177. this.m_connectionState = CS_SERVER_CERTIFICATE;
  1178. }
  1179. // CertificateVerify
  1180. {
  1181. DigitallySigned certificateVerify = TlsUtilities.Generate13CertificateVerify(m_tlsServerContext,
  1182. serverCredentials, m_handshakeHash);
  1183. Send13CertificateVerifyMessage(certificateVerify);
  1184. this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
  1185. }
  1186. }
  1187. // Finished
  1188. {
  1189. Send13FinishedMessage();
  1190. this.m_connectionState = CS_SERVER_FINISHED;
  1191. }
  1192. byte[] serverFinishedTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  1193. TlsUtilities.Establish13PhaseApplication(m_tlsServerContext, serverFinishedTranscriptHash, m_recordStream);
  1194. m_recordStream.EnablePendingCipherWrite();
  1195. }
  1196. /// <exception cref="IOException"/>
  1197. protected virtual void SendCertificateRequestMessage(CertificateRequest certificateRequest)
  1198. {
  1199. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.certificate_request);
  1200. certificateRequest.Encode(m_tlsServerContext, message);
  1201. message.Send(this);
  1202. }
  1203. /// <exception cref="IOException"/>
  1204. protected virtual void SendCertificateStatusMessage(CertificateStatus certificateStatus)
  1205. {
  1206. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.certificate_status);
  1207. // TODO[tls13] Ensure this cannot happen for (D)TLS1.3+
  1208. certificateStatus.Encode(message);
  1209. message.Send(this);
  1210. }
  1211. /// <exception cref="IOException"/>
  1212. protected virtual void SendHelloRequestMessage()
  1213. {
  1214. HandshakeMessageOutput.Send(this, HandshakeType.hello_request, TlsUtilities.EmptyBytes);
  1215. }
  1216. /// <exception cref="IOException"/>
  1217. protected virtual void SendNewSessionTicketMessage(NewSessionTicket newSessionTicket)
  1218. {
  1219. if (newSessionTicket == null)
  1220. throw new TlsFatalAlert(AlertDescription.internal_error);
  1221. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.new_session_ticket);
  1222. newSessionTicket.Encode(message);
  1223. message.Send(this);
  1224. }
  1225. /// <exception cref="IOException"/>
  1226. protected virtual void SendServerHelloDoneMessage()
  1227. {
  1228. HandshakeMessageOutput.Send(this, HandshakeType.server_hello_done, TlsUtilities.EmptyBytes);
  1229. }
  1230. /// <exception cref="IOException"/>
  1231. protected virtual void SendServerHelloMessage(ServerHello serverHello)
  1232. {
  1233. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.server_hello);
  1234. serverHello.Encode(m_tlsServerContext, message);
  1235. message.Send(this);
  1236. }
  1237. /// <exception cref="IOException"/>
  1238. protected virtual void SendServerKeyExchangeMessage(byte[] serverKeyExchange)
  1239. {
  1240. HandshakeMessageOutput.Send(this, HandshakeType.server_key_exchange, serverKeyExchange);
  1241. }
  1242. /// <exception cref="IOException"/>
  1243. protected virtual void Skip13ClientCertificate()
  1244. {
  1245. if (null != m_certificateRequest)
  1246. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1247. }
  1248. /// <exception cref="IOException"/>
  1249. protected virtual void Skip13ClientCertificateVerify()
  1250. {
  1251. if (ExpectCertificateVerifyMessage())
  1252. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1253. }
  1254. }
  1255. }
  1256. #pragma warning restore
  1257. #endif