TlsServerProtocol.cs 65 KB

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