TlsClientProtocol.cs 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  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 TlsClientProtocol
  11. : TlsProtocol
  12. {
  13. protected TlsClient m_tlsClient = null;
  14. internal TlsClientContextImpl m_tlsClientContext = null;
  15. protected IDictionary m_clientAgreements = null;
  16. internal OfferedPsks.BindersConfig m_clientBinders = null;
  17. protected ClientHello m_clientHello = null;
  18. protected TlsKeyExchange m_keyExchange = null;
  19. protected TlsAuthentication m_authentication = null;
  20. protected CertificateStatus m_certificateStatus = null;
  21. protected CertificateRequest m_certificateRequest = null;
  22. /// <summary>Constructor for non-blocking mode.</summary>
  23. /// <remarks>
  24. /// When data is received, use <see cref="TlsProtocol.OfferInput(byte[])"/> to provide the received ciphertext,
  25. /// then use <see cref="TlsProtocol.ReadInput(byte[],int,int)"/> to read the corresponding cleartext.<br/><br/>
  26. /// Similarly, when data needs to be sent, use <see cref="TlsProtocol.WriteApplicationData(byte[],int,int)"/>
  27. /// to provide the cleartext, then use <see cref="TlsProtocol.ReadOutput(byte[],int,int)"/> to get the
  28. /// corresponding ciphertext.
  29. /// </remarks>
  30. public TlsClientProtocol()
  31. : base()
  32. {
  33. }
  34. /// <summary>Constructor for blocking mode.</summary>
  35. /// <param name="stream">The <see cref="Stream"/> of data to/from the server.</param>
  36. public TlsClientProtocol(Stream stream)
  37. : base(stream)
  38. {
  39. }
  40. /// <summary>Constructor for blocking mode.</summary>
  41. /// <param name="input">The <see cref="Stream"/> of data from the server.</param>
  42. /// <param name="output">The <see cref="Stream"/> of data to the server.</param>
  43. public TlsClientProtocol(Stream input, Stream output)
  44. : base(input, output)
  45. {
  46. }
  47. /// <summary>Initiates a TLS handshake in the role of client.</summary>
  48. /// <remarks>
  49. /// In blocking mode, this will not return until the handshake is complete. In non-blocking mode, use
  50. /// <see cref="TlsPeer.NotifyHandshakeComplete"/> to receive a callback when the handshake is complete.
  51. /// </remarks>
  52. /// <param name="tlsClient">The <see cref="TlsClient"/> to use for the handshake.</param>
  53. /// <exception cref="IOException">If in blocking mode and handshake was not successful.</exception>
  54. public virtual void Connect(TlsClient tlsClient)
  55. {
  56. if (tlsClient == null)
  57. throw new ArgumentNullException("tlsClient");
  58. if (m_tlsClient != null)
  59. throw new InvalidOperationException("'Connect' can only be called once");
  60. this.m_tlsClient = tlsClient;
  61. this.m_tlsClientContext = new TlsClientContextImpl(tlsClient.Crypto);
  62. tlsClient.Init(m_tlsClientContext);
  63. tlsClient.NotifyCloseHandle(this);
  64. BeginHandshake(false);
  65. if (m_blocking)
  66. {
  67. BlockForHandshake();
  68. }
  69. }
  70. protected override void BeginHandshake(bool renegotiation)
  71. {
  72. base.BeginHandshake(renegotiation);
  73. SendClientHello();
  74. this.m_connectionState = CS_CLIENT_HELLO;
  75. }
  76. protected override void CleanupHandshake()
  77. {
  78. base.CleanupHandshake();
  79. this.m_clientAgreements = null;
  80. this.m_clientBinders = null;
  81. this.m_clientHello = null;
  82. this.m_keyExchange = null;
  83. this.m_authentication = null;
  84. this.m_certificateStatus = null;
  85. this.m_certificateRequest = null;
  86. }
  87. protected override TlsContext Context
  88. {
  89. get { return m_tlsClientContext; }
  90. }
  91. internal override AbstractTlsContext ContextAdmin
  92. {
  93. get { return m_tlsClientContext; }
  94. }
  95. protected override TlsPeer Peer
  96. {
  97. get { return m_tlsClient; }
  98. }
  99. /// <exception cref="IOException"/>
  100. protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInput buf)
  101. {
  102. if (!IsTlsV13ConnectionState() || m_resumedSession)
  103. throw new TlsFatalAlert(AlertDescription.internal_error);
  104. switch (type)
  105. {
  106. case HandshakeType.certificate:
  107. {
  108. switch (m_connectionState)
  109. {
  110. case CS_SERVER_ENCRYPTED_EXTENSIONS:
  111. case CS_SERVER_CERTIFICATE_REQUEST:
  112. {
  113. if (m_connectionState != CS_SERVER_CERTIFICATE_REQUEST)
  114. {
  115. Skip13CertificateRequest();
  116. }
  117. Receive13ServerCertificate(buf);
  118. this.m_connectionState = CS_SERVER_CERTIFICATE;
  119. break;
  120. }
  121. default:
  122. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  123. }
  124. break;
  125. }
  126. case HandshakeType.certificate_request:
  127. {
  128. switch (m_connectionState)
  129. {
  130. case CS_END:
  131. {
  132. // TODO[tls13] Permit post-handshake authentication if we sent post_handshake_auth extension
  133. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  134. }
  135. case CS_SERVER_ENCRYPTED_EXTENSIONS:
  136. {
  137. Receive13CertificateRequest(buf, false);
  138. this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
  139. break;
  140. }
  141. default:
  142. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  143. }
  144. break;
  145. }
  146. case HandshakeType.certificate_verify:
  147. {
  148. switch (m_connectionState)
  149. {
  150. case CS_SERVER_CERTIFICATE:
  151. {
  152. Receive13ServerCertificateVerify(buf);
  153. buf.UpdateHash(m_handshakeHash);
  154. this.m_connectionState = CS_SERVER_CERTIFICATE_VERIFY;
  155. break;
  156. }
  157. default:
  158. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  159. }
  160. break;
  161. }
  162. case HandshakeType.encrypted_extensions:
  163. {
  164. switch (m_connectionState)
  165. {
  166. case CS_SERVER_HELLO:
  167. {
  168. Receive13EncryptedExtensions(buf);
  169. this.m_connectionState = CS_SERVER_ENCRYPTED_EXTENSIONS;
  170. break;
  171. }
  172. default:
  173. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  174. }
  175. break;
  176. }
  177. case HandshakeType.finished:
  178. {
  179. switch (m_connectionState)
  180. {
  181. case CS_SERVER_ENCRYPTED_EXTENSIONS:
  182. case CS_SERVER_CERTIFICATE_REQUEST:
  183. case CS_SERVER_CERTIFICATE_VERIFY:
  184. {
  185. if (m_connectionState == CS_SERVER_ENCRYPTED_EXTENSIONS)
  186. {
  187. Skip13CertificateRequest();
  188. }
  189. if (m_connectionState != CS_SERVER_CERTIFICATE_VERIFY)
  190. {
  191. Skip13ServerCertificate();
  192. }
  193. Receive13ServerFinished(buf);
  194. buf.UpdateHash(m_handshakeHash);
  195. this.m_connectionState = CS_SERVER_FINISHED;
  196. byte[] serverFinishedTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  197. // See RFC 8446 D.4.
  198. m_recordStream.SetIgnoreChangeCipherSpec(false);
  199. /*
  200. * TODO[tls13] After receiving the server's Finished message, if the server has accepted early
  201. * data, an EndOfEarlyData message will be sent to indicate the key change. This message will
  202. * be encrypted with the 0-RTT traffic keys.
  203. */
  204. if (null != m_certificateRequest)
  205. {
  206. TlsCredentialedSigner clientCredentials = TlsUtilities.Establish13ClientCredentials(
  207. m_authentication, m_certificateRequest);
  208. Certificate clientCertificate = null;
  209. if (null != clientCredentials)
  210. {
  211. clientCertificate = clientCredentials.Certificate;
  212. }
  213. if (null == clientCertificate)
  214. {
  215. // In this calling context, certificate_request_context is length 0
  216. clientCertificate = Certificate.EmptyChainTls13;
  217. }
  218. Send13CertificateMessage(clientCertificate);
  219. this.m_connectionState = CS_CLIENT_CERTIFICATE;
  220. if (null != clientCredentials)
  221. {
  222. DigitallySigned certificateVerify = TlsUtilities.Generate13CertificateVerify(
  223. m_tlsClientContext, clientCredentials, m_handshakeHash);
  224. Send13CertificateVerifyMessage(certificateVerify);
  225. this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
  226. }
  227. }
  228. Send13FinishedMessage();
  229. this.m_connectionState = CS_CLIENT_FINISHED;
  230. TlsUtilities.Establish13PhaseApplication(m_tlsClientContext, serverFinishedTranscriptHash,
  231. m_recordStream);
  232. m_recordStream.EnablePendingCipherWrite();
  233. m_recordStream.EnablePendingCipherRead(false);
  234. CompleteHandshake();
  235. break;
  236. }
  237. default:
  238. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  239. }
  240. break;
  241. }
  242. case HandshakeType.key_update:
  243. {
  244. Receive13KeyUpdate(buf);
  245. break;
  246. }
  247. case HandshakeType.new_session_ticket:
  248. {
  249. Receive13NewSessionTicket(buf);
  250. break;
  251. }
  252. case HandshakeType.server_hello:
  253. {
  254. switch (m_connectionState)
  255. {
  256. case CS_CLIENT_HELLO:
  257. {
  258. // NOTE: Legacy handler should be dispatching initial ServerHello/HelloRetryRequest.
  259. throw new TlsFatalAlert(AlertDescription.internal_error);
  260. }
  261. case CS_CLIENT_HELLO_RETRY:
  262. {
  263. ServerHello serverHello = ReceiveServerHelloMessage(buf);
  264. if (serverHello.IsHelloRetryRequest())
  265. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  266. Process13ServerHello(serverHello, true);
  267. buf.UpdateHash(m_handshakeHash);
  268. this.m_connectionState = CS_SERVER_HELLO;
  269. Process13ServerHelloCoda(serverHello, true);
  270. break;
  271. }
  272. default:
  273. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  274. }
  275. break;
  276. }
  277. case HandshakeType.certificate_status:
  278. case HandshakeType.certificate_url:
  279. case HandshakeType.client_hello:
  280. case HandshakeType.client_key_exchange:
  281. case HandshakeType.end_of_early_data:
  282. case HandshakeType.hello_request:
  283. case HandshakeType.hello_verify_request:
  284. case HandshakeType.message_hash:
  285. case HandshakeType.server_hello_done:
  286. case HandshakeType.server_key_exchange:
  287. case HandshakeType.supplemental_data:
  288. default:
  289. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  290. }
  291. }
  292. protected override void HandleHandshakeMessage(short type, HandshakeMessageInput buf)
  293. {
  294. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  295. if (m_connectionState > CS_CLIENT_HELLO
  296. && TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
  297. {
  298. Handle13HandshakeMessage(type, buf);
  299. return;
  300. }
  301. if (!IsLegacyConnectionState())
  302. throw new TlsFatalAlert(AlertDescription.internal_error);
  303. if (m_resumedSession)
  304. {
  305. if (type != HandshakeType.finished || m_connectionState != CS_SERVER_HELLO)
  306. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  307. ProcessFinishedMessage(buf);
  308. buf.UpdateHash(m_handshakeHash);
  309. this.m_connectionState = CS_SERVER_FINISHED;
  310. SendChangeCipherSpec();
  311. SendFinishedMessage();
  312. this.m_connectionState = CS_CLIENT_FINISHED;
  313. CompleteHandshake();
  314. return;
  315. }
  316. switch (type)
  317. {
  318. case HandshakeType.certificate:
  319. {
  320. switch (m_connectionState)
  321. {
  322. case CS_SERVER_HELLO:
  323. case CS_SERVER_SUPPLEMENTAL_DATA:
  324. {
  325. if (m_connectionState != CS_SERVER_SUPPLEMENTAL_DATA)
  326. {
  327. HandleSupplementalData(null);
  328. }
  329. /*
  330. * NOTE: Certificate processing (including authentication) is delayed to allow for a
  331. * possible CertificateStatus message.
  332. */
  333. this.m_authentication = TlsUtilities.ReceiveServerCertificate(m_tlsClientContext, m_tlsClient,
  334. buf);
  335. break;
  336. }
  337. default:
  338. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  339. }
  340. this.m_connectionState = CS_SERVER_CERTIFICATE;
  341. break;
  342. }
  343. case HandshakeType.certificate_status:
  344. {
  345. switch (m_connectionState)
  346. {
  347. case CS_SERVER_CERTIFICATE:
  348. {
  349. if (securityParameters.StatusRequestVersion < 1)
  350. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  351. this.m_certificateStatus = CertificateStatus.Parse(m_tlsClientContext, buf);
  352. AssertEmpty(buf);
  353. this.m_connectionState = CS_SERVER_CERTIFICATE_STATUS;
  354. break;
  355. }
  356. default:
  357. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  358. }
  359. break;
  360. }
  361. case HandshakeType.finished:
  362. {
  363. switch (m_connectionState)
  364. {
  365. case CS_CLIENT_FINISHED:
  366. case CS_SERVER_SESSION_TICKET:
  367. {
  368. if (m_connectionState != CS_SERVER_SESSION_TICKET)
  369. {
  370. /*
  371. * RFC 5077 3.3. This message MUST be sent if the server included a
  372. * SessionTicket extension in the ServerHello.
  373. */
  374. if (m_expectSessionTicket)
  375. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  376. }
  377. ProcessFinishedMessage(buf);
  378. this.m_connectionState = CS_SERVER_FINISHED;
  379. CompleteHandshake();
  380. break;
  381. }
  382. default:
  383. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  384. }
  385. break;
  386. }
  387. case HandshakeType.server_hello:
  388. {
  389. switch (m_connectionState)
  390. {
  391. case CS_CLIENT_HELLO:
  392. {
  393. ServerHello serverHello = ReceiveServerHelloMessage(buf);
  394. // TODO[tls13] Only treat as HRR if it's TLS 1.3??
  395. if (serverHello.IsHelloRetryRequest())
  396. {
  397. Process13HelloRetryRequest(serverHello);
  398. m_handshakeHash.NotifyPrfDetermined();
  399. TlsUtilities.AdjustTranscriptForRetry(m_handshakeHash);
  400. buf.UpdateHash(m_handshakeHash);
  401. this.m_connectionState = CS_SERVER_HELLO_RETRY_REQUEST;
  402. Send13ClientHelloRetry();
  403. m_handshakeHash.SealHashAlgorithms();
  404. this.m_connectionState = CS_CLIENT_HELLO_RETRY;
  405. }
  406. else
  407. {
  408. ProcessServerHello(serverHello);
  409. m_handshakeHash.NotifyPrfDetermined();
  410. buf.UpdateHash(m_handshakeHash);
  411. this.m_connectionState = CS_SERVER_HELLO;
  412. if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion))
  413. {
  414. m_handshakeHash.SealHashAlgorithms();
  415. Process13ServerHelloCoda(serverHello, false);
  416. }
  417. }
  418. break;
  419. }
  420. default:
  421. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  422. }
  423. break;
  424. }
  425. case HandshakeType.supplemental_data:
  426. {
  427. switch (m_connectionState)
  428. {
  429. case CS_SERVER_HELLO:
  430. {
  431. HandleSupplementalData(ReadSupplementalDataMessage(buf));
  432. break;
  433. }
  434. default:
  435. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  436. }
  437. break;
  438. }
  439. case HandshakeType.server_hello_done:
  440. {
  441. switch (m_connectionState)
  442. {
  443. case CS_SERVER_HELLO:
  444. case CS_SERVER_SUPPLEMENTAL_DATA:
  445. case CS_SERVER_CERTIFICATE:
  446. case CS_SERVER_CERTIFICATE_STATUS:
  447. case CS_SERVER_KEY_EXCHANGE:
  448. case CS_SERVER_CERTIFICATE_REQUEST:
  449. {
  450. if (m_connectionState == CS_SERVER_HELLO)
  451. {
  452. HandleSupplementalData(null);
  453. }
  454. if (m_connectionState == CS_SERVER_HELLO ||
  455. m_connectionState == CS_SERVER_SUPPLEMENTAL_DATA)
  456. {
  457. this.m_authentication = null;
  458. }
  459. if (m_connectionState != CS_SERVER_KEY_EXCHANGE &&
  460. m_connectionState != CS_SERVER_CERTIFICATE_REQUEST)
  461. {
  462. HandleServerCertificate();
  463. // There was no server key exchange message; check it's OK
  464. m_keyExchange.SkipServerKeyExchange();
  465. }
  466. AssertEmpty(buf);
  467. this.m_connectionState = CS_SERVER_HELLO_DONE;
  468. IList clientSupplementalData = m_tlsClient.GetClientSupplementalData();
  469. if (clientSupplementalData != null)
  470. {
  471. SendSupplementalDataMessage(clientSupplementalData);
  472. this.m_connectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
  473. }
  474. TlsCredentialedSigner credentialedSigner = null;
  475. TlsStreamSigner streamSigner = null;
  476. if (m_certificateRequest == null)
  477. {
  478. m_keyExchange.SkipClientCredentials();
  479. }
  480. else
  481. {
  482. Certificate clientCertificate = null;
  483. TlsCredentials clientCredentials = TlsUtilities.EstablishClientCredentials(m_authentication,
  484. m_certificateRequest);
  485. if (null == clientCredentials)
  486. {
  487. m_keyExchange.SkipClientCredentials();
  488. /*
  489. * RFC 5246 If no suitable certificate is available, the client MUST send a
  490. * certificate message containing no certificates.
  491. *
  492. * NOTE: In previous RFCs, this was SHOULD instead of MUST.
  493. */
  494. }
  495. else
  496. {
  497. m_keyExchange.ProcessClientCredentials(clientCredentials);
  498. clientCertificate = clientCredentials.Certificate;
  499. if (clientCredentials is TlsCredentialedSigner)
  500. {
  501. credentialedSigner = (TlsCredentialedSigner)clientCredentials;
  502. streamSigner = credentialedSigner.GetStreamSigner();
  503. }
  504. }
  505. SendCertificateMessage(clientCertificate, null);
  506. this.m_connectionState = CS_CLIENT_CERTIFICATE;
  507. }
  508. bool forceBuffering = streamSigner != null;
  509. TlsUtilities.SealHandshakeHash(m_tlsClientContext, m_handshakeHash, forceBuffering);
  510. /*
  511. * Send the client key exchange message, depending on the key exchange we are using
  512. * in our CipherSuite.
  513. */
  514. SendClientKeyExchange();
  515. this.m_connectionState = CS_CLIENT_KEY_EXCHANGE;
  516. bool isSsl = TlsUtilities.IsSsl(m_tlsClientContext);
  517. if (isSsl)
  518. {
  519. // NOTE: For SSLv3 (only), master_secret needed to calculate session hash
  520. EstablishMasterSecret(m_tlsClientContext, m_keyExchange);
  521. }
  522. securityParameters.m_sessionHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  523. if (!isSsl)
  524. {
  525. // NOTE: For (D)TLS, session hash potentially needed for extended_master_secret
  526. EstablishMasterSecret(m_tlsClientContext, m_keyExchange);
  527. }
  528. m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext));
  529. if (credentialedSigner != null)
  530. {
  531. DigitallySigned certificateVerify = TlsUtilities.GenerateCertificateVerifyClient(
  532. m_tlsClientContext, credentialedSigner, streamSigner, m_handshakeHash);
  533. SendCertificateVerifyMessage(certificateVerify);
  534. this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY;
  535. }
  536. this.m_handshakeHash = m_handshakeHash.StopTracking();
  537. SendChangeCipherSpec();
  538. SendFinishedMessage();
  539. break;
  540. }
  541. default:
  542. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  543. }
  544. this.m_connectionState = CS_CLIENT_FINISHED;
  545. break;
  546. }
  547. case HandshakeType.server_key_exchange:
  548. {
  549. switch (m_connectionState)
  550. {
  551. case CS_SERVER_HELLO:
  552. case CS_SERVER_SUPPLEMENTAL_DATA:
  553. case CS_SERVER_CERTIFICATE:
  554. case CS_SERVER_CERTIFICATE_STATUS:
  555. {
  556. if (m_connectionState == CS_SERVER_HELLO)
  557. {
  558. HandleSupplementalData(null);
  559. }
  560. if (m_connectionState != CS_SERVER_CERTIFICATE &&
  561. m_connectionState != CS_SERVER_CERTIFICATE_STATUS)
  562. {
  563. this.m_authentication = null;
  564. }
  565. HandleServerCertificate();
  566. m_keyExchange.ProcessServerKeyExchange(buf);
  567. AssertEmpty(buf);
  568. break;
  569. }
  570. default:
  571. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  572. }
  573. this.m_connectionState = CS_SERVER_KEY_EXCHANGE;
  574. break;
  575. }
  576. case HandshakeType.certificate_request:
  577. {
  578. switch (m_connectionState)
  579. {
  580. case CS_SERVER_CERTIFICATE:
  581. case CS_SERVER_CERTIFICATE_STATUS:
  582. case CS_SERVER_KEY_EXCHANGE:
  583. {
  584. if (m_connectionState != CS_SERVER_KEY_EXCHANGE)
  585. {
  586. HandleServerCertificate();
  587. // There was no server key exchange message; check it's OK
  588. m_keyExchange.SkipServerKeyExchange();
  589. }
  590. ReceiveCertificateRequest(buf);
  591. TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest);
  592. /*
  593. * TODO Give the client a chance to immediately select the CertificateVerify hash
  594. * algorithm here to avoid tracking the other hash algorithms unnecessarily?
  595. */
  596. TlsUtilities.TrackHashAlgorithms(m_handshakeHash, securityParameters.ServerSigAlgs);
  597. break;
  598. }
  599. default:
  600. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  601. }
  602. this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST;
  603. break;
  604. }
  605. case HandshakeType.new_session_ticket:
  606. {
  607. switch (m_connectionState)
  608. {
  609. case CS_CLIENT_FINISHED:
  610. {
  611. if (!m_expectSessionTicket)
  612. {
  613. /*
  614. * RFC 5077 3.3. This message MUST NOT be sent if the server did not include a
  615. * SessionTicket extension in the ServerHello.
  616. */
  617. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  618. }
  619. /*
  620. * RFC 5077 3.4. If the client receives a session ticket from the server, then it
  621. * discards any Session ID that was sent in the ServerHello.
  622. */
  623. securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
  624. InvalidateSession();
  625. this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);
  626. ReceiveNewSessionTicket(buf);
  627. break;
  628. }
  629. default:
  630. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  631. }
  632. this.m_connectionState = CS_SERVER_SESSION_TICKET;
  633. break;
  634. }
  635. case HandshakeType.hello_request:
  636. {
  637. AssertEmpty(buf);
  638. /*
  639. * RFC 2246 7.4.1.1 Hello request This message will be ignored by the client if the
  640. * client is currently negotiating a session. This message may be ignored by the client
  641. * if it does not wish to renegotiate a session, or the client may, if it wishes,
  642. * respond with a no_renegotiation alert.
  643. */
  644. if (IsApplicationDataReady)
  645. {
  646. //RefuseRenegotiation();
  647. handleRenegotiation();
  648. }
  649. break;
  650. }
  651. case HandshakeType.certificate_url:
  652. case HandshakeType.certificate_verify:
  653. case HandshakeType.client_hello:
  654. case HandshakeType.client_key_exchange:
  655. case HandshakeType.encrypted_extensions:
  656. case HandshakeType.end_of_early_data:
  657. case HandshakeType.hello_verify_request:
  658. case HandshakeType.key_update:
  659. case HandshakeType.message_hash:
  660. default:
  661. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  662. }
  663. }
  664. /// <exception cref="IOException"/>
  665. protected virtual void HandleServerCertificate()
  666. {
  667. TlsUtilities.ProcessServerCertificate(m_tlsClientContext, m_certificateStatus, m_keyExchange,
  668. m_authentication, m_clientExtensions, m_serverExtensions);
  669. }
  670. /// <exception cref="IOException"/>
  671. protected virtual void HandleSupplementalData(IList serverSupplementalData)
  672. {
  673. m_tlsClient.ProcessServerSupplementalData(serverSupplementalData);
  674. this.m_connectionState = CS_SERVER_SUPPLEMENTAL_DATA;
  675. this.m_keyExchange = TlsUtilities.InitKeyExchangeClient(m_tlsClientContext, m_tlsClient);
  676. }
  677. /// <exception cref="IOException"/>
  678. protected virtual void Process13HelloRetryRequest(ServerHello helloRetryRequest)
  679. {
  680. ProtocolVersion legacy_record_version = ProtocolVersion.TLSv12;
  681. m_recordStream.SetWriteVersion(legacy_record_version);
  682. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  683. if (securityParameters.IsRenegotiating)
  684. {
  685. throw new TlsFatalAlert(AlertDescription.internal_error);
  686. }
  687. /*
  688. * RFC 8446 4.1.4. Upon receipt of a HelloRetryRequest, the client MUST check the
  689. * legacy_version, legacy_session_id_echo, cipher_suite, and legacy_compression_method as
  690. * specified in Section 4.1.3 and then process the extensions, starting with determining the
  691. * version using "supported_versions".
  692. */
  693. ProtocolVersion legacy_version = helloRetryRequest.Version;
  694. byte[] legacy_session_id_echo = helloRetryRequest.SessionID;
  695. int cipherSuite = helloRetryRequest.CipherSuite;
  696. // NOTE: legacy_compression_method checked during ServerHello parsing
  697. if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
  698. !Arrays.AreEqual(m_clientHello.SessionID, legacy_session_id_echo) ||
  699. !TlsUtilities.IsValidCipherSuiteSelection(m_clientHello.CipherSuites, cipherSuite))
  700. {
  701. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  702. }
  703. IDictionary extensions = helloRetryRequest.Extensions;
  704. if (null == extensions)
  705. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  706. TlsUtilities.CheckExtensionData13(extensions, HandshakeType.hello_retry_request,
  707. AlertDescription.illegal_parameter);
  708. {
  709. /*
  710. * RFC 8446 4.2. Implementations MUST NOT send extension responses if the remote
  711. * endpoint did not send the corresponding extension requests, with the exception of the
  712. * "cookie" extension in the HelloRetryRequest. Upon receiving such an extension, an
  713. * endpoint MUST abort the handshake with an "unsupported_extension" alert.
  714. */
  715. foreach (int extType in extensions.Keys)
  716. {
  717. if (ExtensionType.cookie == extType)
  718. continue;
  719. if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
  720. throw new TlsFatalAlert(AlertDescription.unsupported_extension);
  721. }
  722. }
  723. ProtocolVersion server_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(extensions);
  724. if (null == server_version)
  725. throw new TlsFatalAlert(AlertDescription.missing_extension);
  726. if (!ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(server_version) ||
  727. !ProtocolVersion.Contains(m_tlsClientContext.ClientSupportedVersions, server_version) ||
  728. !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, server_version))
  729. {
  730. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  731. }
  732. if (null != m_clientBinders)
  733. {
  734. if (!Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_dhe_ke))
  735. {
  736. this.m_clientBinders = null;
  737. m_tlsClient.NotifySelectedPsk(null);
  738. }
  739. }
  740. /*
  741. * RFC 8446 4.2.8. Upon receipt of this [Key Share] extension in a HelloRetryRequest, the
  742. * client MUST verify that (1) the selected_group field corresponds to a group which was
  743. * provided in the "supported_groups" extension in the original ClientHello and (2) the
  744. * selected_group field does not correspond to a group which was provided in the "key_share"
  745. * extension in the original ClientHello. If either of these checks fails, then the client
  746. * MUST abort the handshake with an "illegal_parameter" alert.
  747. */
  748. int selected_group = TlsExtensionsUtilities.GetKeyShareHelloRetryRequest(extensions);
  749. if (!TlsUtilities.IsValidKeyShareSelection(server_version, securityParameters.ClientSupportedGroups,
  750. m_clientAgreements, selected_group))
  751. {
  752. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  753. }
  754. byte[] cookie = TlsExtensionsUtilities.GetCookieExtension(extensions);
  755. securityParameters.m_negotiatedVersion = server_version;
  756. TlsUtilities.NegotiatedVersionTlsClient(m_tlsClientContext, m_tlsClient);
  757. this.m_resumedSession = false;
  758. securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
  759. m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes);
  760. TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
  761. m_tlsClient.NotifySelectedCipherSuite(cipherSuite);
  762. this.m_clientAgreements = null;
  763. this.m_retryCookie = cookie;
  764. this.m_retryGroup = selected_group;
  765. }
  766. /// <exception cref="IOException"/>
  767. protected virtual void Process13ServerHello(ServerHello serverHello, bool afterHelloRetryRequest)
  768. {
  769. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  770. ProtocolVersion legacy_version = serverHello.Version;
  771. byte[] legacy_session_id_echo = serverHello.SessionID;
  772. int cipherSuite = serverHello.CipherSuite;
  773. // NOTE: legacy_compression_method checked during ServerHello parsing
  774. if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
  775. !Arrays.AreEqual(m_clientHello.SessionID, legacy_session_id_echo))
  776. {
  777. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  778. }
  779. IDictionary extensions = serverHello.Extensions;
  780. if (null == extensions)
  781. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  782. TlsUtilities.CheckExtensionData13(extensions, HandshakeType.server_hello,
  783. AlertDescription.illegal_parameter);
  784. if (afterHelloRetryRequest)
  785. {
  786. ProtocolVersion server_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(extensions);
  787. if (null == server_version)
  788. throw new TlsFatalAlert(AlertDescription.missing_extension);
  789. if (!securityParameters.NegotiatedVersion.Equals(server_version) ||
  790. securityParameters.CipherSuite != cipherSuite)
  791. {
  792. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  793. }
  794. }
  795. else
  796. {
  797. if (!TlsUtilities.IsValidCipherSuiteSelection(m_clientHello.CipherSuites, cipherSuite) ||
  798. !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, securityParameters.NegotiatedVersion))
  799. {
  800. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  801. }
  802. this.m_resumedSession = false;
  803. securityParameters.m_sessionID = TlsUtilities.EmptyBytes;
  804. m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes);
  805. TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
  806. m_tlsClient.NotifySelectedCipherSuite(cipherSuite);
  807. }
  808. this.m_clientHello = null;
  809. // NOTE: Apparently downgrade marker mechanism not used for TLS 1.3+?
  810. securityParameters.m_serverRandom = serverHello.Random;
  811. securityParameters.m_secureRenegotiation = false;
  812. /*
  813. * RFC 8446 Appendix D. Because TLS 1.3 always hashes in the transcript up to the server
  814. * Finished, implementations which support both TLS 1.3 and earlier versions SHOULD indicate
  815. * the use of the Extended Master Secret extension in their APIs whenever TLS 1.3 is used.
  816. */
  817. securityParameters.m_extendedMasterSecret = true;
  818. /*
  819. * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
  820. *
  821. * OCSP information is carried in an extension for a CertificateEntry.
  822. */
  823. securityParameters.m_statusRequestVersion = m_clientExtensions.Contains(ExtensionType.status_request) ? 1 : 0;
  824. TlsSecret pskEarlySecret = null;
  825. {
  826. int selected_identity = TlsExtensionsUtilities.GetPreSharedKeyServerHello(extensions);
  827. TlsPsk selectedPsk = null;
  828. if (selected_identity >= 0)
  829. {
  830. if (null == m_clientBinders || selected_identity >= m_clientBinders.m_psks.Length)
  831. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  832. selectedPsk = m_clientBinders.m_psks[selected_identity];
  833. if (selectedPsk.PrfAlgorithm != securityParameters.PrfAlgorithm)
  834. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  835. pskEarlySecret = m_clientBinders.m_earlySecrets[selected_identity];
  836. this.m_selectedPsk13 = true;
  837. }
  838. m_tlsClient.NotifySelectedPsk(selectedPsk);
  839. }
  840. TlsSecret sharedSecret = null;
  841. {
  842. KeyShareEntry keyShareEntry = TlsExtensionsUtilities.GetKeyShareServerHello(extensions);
  843. if (null == keyShareEntry)
  844. {
  845. if (afterHelloRetryRequest
  846. || null == pskEarlySecret
  847. || !Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_ke))
  848. {
  849. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  850. }
  851. }
  852. else
  853. {
  854. if (null != pskEarlySecret
  855. && !Arrays.Contains(m_clientBinders.m_pskKeyExchangeModes, PskKeyExchangeMode.psk_dhe_ke))
  856. {
  857. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  858. }
  859. TlsAgreement agreement = (TlsAgreement)m_clientAgreements[keyShareEntry.NamedGroup];
  860. if (null == agreement)
  861. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  862. agreement.ReceivePeerValue(keyShareEntry.KeyExchange);
  863. sharedSecret = agreement.CalculateSecret();
  864. }
  865. }
  866. this.m_clientAgreements = null;
  867. this.m_clientBinders = null;
  868. TlsUtilities.Establish13PhaseSecrets(m_tlsClientContext, pskEarlySecret, sharedSecret);
  869. InvalidateSession();
  870. this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);
  871. }
  872. /// <exception cref="IOException"/>
  873. protected virtual void Process13ServerHelloCoda(ServerHello serverHello, bool afterHelloRetryRequest)
  874. {
  875. byte[] serverHelloTranscriptHash = TlsUtilities.GetCurrentPrfHash(m_handshakeHash);
  876. TlsUtilities.Establish13PhaseHandshake(m_tlsClientContext, serverHelloTranscriptHash, m_recordStream);
  877. // See RFC 8446 D.4.
  878. if (!afterHelloRetryRequest)
  879. {
  880. m_recordStream.SetIgnoreChangeCipherSpec(true);
  881. /*
  882. * TODO[tls13] If offering early_data, the record is placed immediately after the first
  883. * ClientHello.
  884. */
  885. /*
  886. * TODO[tls13] Ideally wait until just after Server Finished received, but then we'd need to defer
  887. * the enabling of the pending write cipher
  888. */
  889. SendChangeCipherSpecMessage();
  890. }
  891. m_recordStream.EnablePendingCipherWrite();
  892. m_recordStream.EnablePendingCipherRead(false);
  893. }
  894. /// <exception cref="IOException"/>
  895. protected virtual void ProcessServerHello(ServerHello serverHello)
  896. {
  897. IDictionary serverHelloExtensions = serverHello.Extensions;
  898. ProtocolVersion legacy_version = serverHello.Version;
  899. ProtocolVersion supported_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer(
  900. serverHelloExtensions);
  901. ProtocolVersion server_version;
  902. if (null == supported_version)
  903. {
  904. server_version = legacy_version;
  905. }
  906. else
  907. {
  908. if (!ProtocolVersion.TLSv12.Equals(legacy_version) ||
  909. !ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(supported_version))
  910. {
  911. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  912. }
  913. server_version = supported_version;
  914. }
  915. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  916. if (securityParameters.IsRenegotiating)
  917. {
  918. // Check that this matches the negotiated version from the initial handshake
  919. if (!server_version.Equals(securityParameters.NegotiatedVersion))
  920. {
  921. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  922. }
  923. }
  924. else
  925. {
  926. if (!ProtocolVersion.Contains(m_tlsClientContext.ClientSupportedVersions, server_version))
  927. throw new TlsFatalAlert(AlertDescription.protocol_version);
  928. ProtocolVersion legacy_record_version = server_version.IsLaterVersionOf(ProtocolVersion.TLSv12)
  929. ? ProtocolVersion.TLSv12
  930. : server_version;
  931. m_recordStream.SetWriteVersion(legacy_record_version);
  932. securityParameters.m_negotiatedVersion = server_version;
  933. }
  934. TlsUtilities.NegotiatedVersionTlsClient(m_tlsClientContext, m_tlsClient);
  935. if (ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(server_version))
  936. {
  937. Process13ServerHello(serverHello, false);
  938. return;
  939. }
  940. int[] offeredCipherSuites = m_clientHello.CipherSuites;
  941. this.m_clientHello = null;
  942. this.m_retryCookie = null;
  943. this.m_retryGroup = -1;
  944. securityParameters.m_serverRandom = serverHello.Random;
  945. if (!m_tlsClientContext.ClientVersion.Equals(server_version))
  946. {
  947. TlsUtilities.CheckDowngradeMarker(server_version, securityParameters.ServerRandom);
  948. }
  949. {
  950. byte[] selectedSessionID = serverHello.SessionID;
  951. securityParameters.m_sessionID = selectedSessionID;
  952. m_tlsClient.NotifySessionID(selectedSessionID);
  953. this.m_resumedSession = selectedSessionID.Length > 0 && m_tlsSession != null
  954. && Arrays.AreEqual(selectedSessionID, m_tlsSession.SessionID);
  955. }
  956. /*
  957. * Find out which CipherSuite the server has chosen and check that it was one of the offered
  958. * ones, and is a valid selection for the negotiated version.
  959. */
  960. {
  961. int cipherSuite = serverHello.CipherSuite;
  962. if (!TlsUtilities.IsValidCipherSuiteSelection(offeredCipherSuites, cipherSuite) ||
  963. !TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, securityParameters.NegotiatedVersion))
  964. {
  965. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  966. }
  967. TlsUtilities.NegotiatedCipherSuite(securityParameters, cipherSuite);
  968. m_tlsClient.NotifySelectedCipherSuite(cipherSuite);
  969. }
  970. /*
  971. * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
  972. * extended client hello message.
  973. *
  974. * However, see RFC 5746 exception below. We always include the SCSV, so an Extended Server
  975. * Hello is always allowed.
  976. */
  977. this.m_serverExtensions = serverHelloExtensions;
  978. if (m_serverExtensions != null)
  979. {
  980. foreach (int extType in m_serverExtensions.Keys)
  981. {
  982. /*
  983. * RFC 5746 3.6. Note that sending a "renegotiation_info" extension in response to a
  984. * ClientHello containing only the SCSV is an explicit exception to the prohibition
  985. * in RFC 5246, Section 7.4.1.4, on the server sending unsolicited extensions and is
  986. * only allowed because the client is signaling its willingness to receive the
  987. * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
  988. */
  989. if (ExtensionType.renegotiation_info == extType)
  990. continue;
  991. /*
  992. * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
  993. * same extension type appeared in the corresponding ClientHello. If a client
  994. * receives an extension type in ServerHello that it did not request in the
  995. * associated ClientHello, it MUST abort the handshake with an unsupported_extension
  996. * fatal alert.
  997. */
  998. if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
  999. throw new TlsFatalAlert(AlertDescription.unsupported_extension);
  1000. /*
  1001. * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
  1002. * extensions appearing in the client hello, and send a server hello containing no
  1003. * extensions[.]
  1004. */
  1005. if (m_resumedSession)
  1006. {
  1007. // TODO[compat-gnutls] GnuTLS test server sends server extensions e.g. ec_point_formats
  1008. // TODO[compat-openssl] OpenSSL test server sends server extensions e.g. ec_point_formats
  1009. // TODO[compat-polarssl] PolarSSL test server sends server extensions e.g. ec_point_formats
  1010. // throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  1011. }
  1012. }
  1013. }
  1014. byte[] renegExtData = TlsUtilities.GetExtensionData(m_serverExtensions, ExtensionType.renegotiation_info);
  1015. if (securityParameters.IsRenegotiating)
  1016. {
  1017. /*
  1018. * RFC 5746 3.5. Client Behavior: Secure Renegotiation
  1019. *
  1020. * This text applies if the connection's "secure_renegotiation" flag is set to TRUE.
  1021. */
  1022. if (!securityParameters.IsSecureRenegotiation)
  1023. {
  1024. throw new TlsFatalAlert(AlertDescription.internal_error);
  1025. }
  1026. /*
  1027. * When a ServerHello is received, the client MUST verify that the "renegotiation_info"
  1028. * extension is present; if it is not, the client MUST abort the handshake.
  1029. */
  1030. if (renegExtData == null)
  1031. {
  1032. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1033. }
  1034. /*
  1035. * The client MUST then verify that the first half of the "renegotiated_connection"
  1036. * field is equal to the saved client_verify_data value, and the second half is equal to
  1037. * the saved server_verify_data value. If they are not, the client MUST abort the
  1038. * handshake.
  1039. */
  1040. SecurityParameters saved = m_tlsClientContext.SecurityParameters;
  1041. byte[] reneg_conn_info = Arrays.Concatenate(saved.LocalVerifyData, saved.PeerVerifyData);
  1042. if (!Arrays.ConstantTimeAreEqual(renegExtData, TlsProtocol.CreateRenegotiationInfo(reneg_conn_info)))
  1043. {
  1044. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1045. }
  1046. }
  1047. else
  1048. {
  1049. /*
  1050. * RFC 5746 3.4. Client Behavior: Initial Handshake (both full and session-resumption)
  1051. */
  1052. /*
  1053. * When a ServerHello is received, the client MUST check if it includes the
  1054. * "renegotiation_info" extension:
  1055. */
  1056. if (renegExtData == null)
  1057. {
  1058. /*
  1059. * If the extension is not present, the server does not support secure
  1060. * renegotiation; set secure_renegotiation flag to FALSE. In this case, some clients
  1061. * may want to terminate the handshake instead of continuing; see Section 4.1 for
  1062. * discussion.
  1063. */
  1064. securityParameters.m_secureRenegotiation = false;
  1065. }
  1066. else
  1067. {
  1068. /*
  1069. * If the extension is present, set the secure_renegotiation flag to TRUE. The
  1070. * client MUST then verify that the length of the "renegotiated_connection"
  1071. * field is zero, and if it is not, MUST abort the handshake (by sending a fatal
  1072. * handshake_failure alert).
  1073. */
  1074. securityParameters.m_secureRenegotiation = true;
  1075. if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
  1076. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1077. }
  1078. }
  1079. // TODO[compat-gnutls] GnuTLS test server fails to send renegotiation_info extension when resuming
  1080. m_tlsClient.NotifySecureRenegotiation(securityParameters.IsSecureRenegotiation);
  1081. /*
  1082. * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended
  1083. * master secret [..]. (and see 5.2, 5.3)
  1084. *
  1085. * RFC 8446 Appendix D. Because TLS 1.3 always hashes in the transcript up to the server
  1086. * Finished, implementations which support both TLS 1.3 and earlier versions SHOULD indicate
  1087. * the use of the Extended Master Secret extension in their APIs whenever TLS 1.3 is used.
  1088. */
  1089. {
  1090. bool acceptedExtendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(
  1091. m_serverExtensions);
  1092. if (acceptedExtendedMasterSecret)
  1093. {
  1094. if (server_version.IsSsl
  1095. || (!m_resumedSession && !m_tlsClient.ShouldUseExtendedMasterSecret()))
  1096. {
  1097. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1098. }
  1099. }
  1100. else
  1101. {
  1102. if (m_tlsClient.RequiresExtendedMasterSecret()
  1103. || (m_resumedSession && !m_tlsClient.AllowLegacyResumption()))
  1104. {
  1105. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1106. }
  1107. }
  1108. securityParameters.m_extendedMasterSecret = acceptedExtendedMasterSecret;
  1109. }
  1110. /*
  1111. * RFC 7301 3.1. When session resumption or session tickets [...] are used, the previous
  1112. * contents of this extension are irrelevant, and only the values in the new handshake
  1113. * messages are considered.
  1114. */
  1115. securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(
  1116. m_serverExtensions);
  1117. securityParameters.m_applicationProtocolSet = true;
  1118. IDictionary sessionClientExtensions = m_clientExtensions, sessionServerExtensions = m_serverExtensions;
  1119. if (m_resumedSession)
  1120. {
  1121. if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite
  1122. || !server_version.Equals(m_sessionParameters.NegotiatedVersion))
  1123. {
  1124. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  1125. }
  1126. sessionClientExtensions = null;
  1127. sessionServerExtensions = m_sessionParameters.ReadServerExtensions();
  1128. }
  1129. if (sessionServerExtensions != null && sessionServerExtensions.Count > 0)
  1130. {
  1131. {
  1132. /*
  1133. * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
  1134. * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
  1135. * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
  1136. * client.
  1137. */
  1138. bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(
  1139. sessionServerExtensions);
  1140. if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(securityParameters.CipherSuite))
  1141. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  1142. securityParameters.m_encryptThenMac = serverSentEncryptThenMAC;
  1143. }
  1144. securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(sessionClientExtensions,
  1145. sessionServerExtensions, AlertDescription.illegal_parameter);
  1146. securityParameters.m_truncatedHmac = TlsExtensionsUtilities.HasTruncatedHmacExtension(
  1147. sessionServerExtensions);
  1148. /*
  1149. * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
  1150. * a session resumption handshake.
  1151. */
  1152. if (!m_resumedSession)
  1153. {
  1154. // TODO[tls13] See RFC 8446 4.4.2.1
  1155. if (TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
  1156. ExtensionType.status_request_v2, AlertDescription.illegal_parameter))
  1157. {
  1158. securityParameters.m_statusRequestVersion = 2;
  1159. }
  1160. else if (TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
  1161. ExtensionType.status_request, AlertDescription.illegal_parameter))
  1162. {
  1163. securityParameters.m_statusRequestVersion = 1;
  1164. }
  1165. this.m_expectSessionTicket = TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions,
  1166. ExtensionType.session_ticket, AlertDescription.illegal_parameter);
  1167. }
  1168. }
  1169. if (sessionClientExtensions != null)
  1170. {
  1171. m_tlsClient.ProcessServerExtensions(sessionServerExtensions);
  1172. }
  1173. ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);
  1174. if (m_resumedSession)
  1175. {
  1176. securityParameters.m_masterSecret = m_sessionMasterSecret;
  1177. m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext));
  1178. }
  1179. else
  1180. {
  1181. InvalidateSession();
  1182. this.m_tlsSession = TlsUtilities.ImportSession(securityParameters.SessionID, null);
  1183. }
  1184. }
  1185. /// <exception cref="IOException"/>
  1186. protected virtual void Receive13CertificateRequest(MemoryStream buf, bool postHandshakeAuth)
  1187. {
  1188. // TODO[tls13] Support for post_handshake_auth
  1189. if (postHandshakeAuth)
  1190. throw new TlsFatalAlert(AlertDescription.internal_error);
  1191. /*
  1192. * RFC 8446 4.3.2. A server which is authenticating with a certificate MAY optionally
  1193. * request a certificate from the client.
  1194. */
  1195. if (m_selectedPsk13)
  1196. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1197. CertificateRequest certificateRequest = CertificateRequest.Parse(m_tlsClientContext, buf);
  1198. AssertEmpty(buf);
  1199. if (!certificateRequest.HasCertificateRequestContext(TlsUtilities.EmptyBytes))
  1200. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  1201. this.m_certificateRequest = certificateRequest;
  1202. TlsUtilities.EstablishServerSigAlgs(m_tlsClientContext.SecurityParameters, certificateRequest);
  1203. }
  1204. /// <exception cref="IOException"/>
  1205. protected virtual void Receive13EncryptedExtensions(MemoryStream buf)
  1206. {
  1207. byte[] extBytes = TlsUtilities.ReadOpaque16(buf);
  1208. AssertEmpty(buf);
  1209. this.m_serverExtensions = ReadExtensionsData13(HandshakeType.encrypted_extensions, extBytes);
  1210. {
  1211. /*
  1212. * RFC 8446 4.2. Implementations MUST NOT send extension responses if the remote
  1213. * endpoint did not send the corresponding extension requests, with the exception of the
  1214. * "cookie" extension in the HelloRetryRequest. Upon receiving such an extension, an
  1215. * endpoint MUST abort the handshake with an "unsupported_extension" alert.
  1216. */
  1217. foreach (int extType in m_serverExtensions.Keys)
  1218. {
  1219. if (null == TlsUtilities.GetExtensionData(m_clientExtensions, extType))
  1220. throw new TlsFatalAlert(AlertDescription.unsupported_extension);
  1221. }
  1222. }
  1223. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  1224. ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion;
  1225. securityParameters.m_applicationProtocol = TlsExtensionsUtilities.GetAlpnExtensionServer(
  1226. m_serverExtensions);
  1227. securityParameters.m_applicationProtocolSet = true;
  1228. IDictionary sessionClientExtensions = m_clientExtensions, sessionServerExtensions = m_serverExtensions;
  1229. if (m_resumedSession)
  1230. {
  1231. if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite
  1232. || !negotiatedVersion.Equals(m_sessionParameters.NegotiatedVersion))
  1233. {
  1234. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  1235. }
  1236. sessionClientExtensions = null;
  1237. sessionServerExtensions = m_sessionParameters.ReadServerExtensions();
  1238. }
  1239. securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(sessionClientExtensions,
  1240. sessionServerExtensions, AlertDescription.illegal_parameter);
  1241. securityParameters.m_encryptThenMac = false;
  1242. securityParameters.m_truncatedHmac = false;
  1243. /*
  1244. * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
  1245. *
  1246. * OCSP information is carried in an extension for a CertificateEntry.
  1247. */
  1248. securityParameters.m_statusRequestVersion = m_clientExtensions.Contains(ExtensionType.status_request)
  1249. ? 1 : 0;
  1250. this.m_expectSessionTicket = false;
  1251. if (null != sessionClientExtensions)
  1252. {
  1253. m_tlsClient.ProcessServerExtensions(m_serverExtensions);
  1254. }
  1255. ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength);
  1256. }
  1257. /// <exception cref="IOException"/>
  1258. protected virtual void Receive13NewSessionTicket(MemoryStream buf)
  1259. {
  1260. if (!IsApplicationDataReady)
  1261. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1262. // TODO[tls13] Do something more than just ignore them
  1263. // struct {
  1264. // uint32 ticket_lifetime;
  1265. // uint32 ticket_age_add;
  1266. // opaque ticket_nonce<0..255>;
  1267. // opaque ticket<1..2^16-1>;
  1268. // Extension extensions<0..2^16-2>;
  1269. // } NewSessionTicket;
  1270. TlsUtilities.ReadUint32(buf);
  1271. TlsUtilities.ReadUint32(buf);
  1272. TlsUtilities.ReadOpaque8(buf);
  1273. TlsUtilities.ReadOpaque16(buf);
  1274. TlsUtilities.ReadOpaque16(buf);
  1275. AssertEmpty(buf);
  1276. }
  1277. /// <exception cref="IOException"/>
  1278. protected virtual void Receive13ServerCertificate(MemoryStream buf)
  1279. {
  1280. if (m_selectedPsk13)
  1281. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1282. this.m_authentication = TlsUtilities.Receive13ServerCertificate(m_tlsClientContext, m_tlsClient, buf);
  1283. // NOTE: In TLS 1.3 we don't have to wait for a possible CertificateStatus message.
  1284. HandleServerCertificate();
  1285. }
  1286. /// <exception cref="IOException"/>
  1287. protected virtual void Receive13ServerCertificateVerify(MemoryStream buf)
  1288. {
  1289. Certificate serverCertificate = m_tlsClientContext.SecurityParameters.PeerCertificate;
  1290. if (null == serverCertificate || serverCertificate.IsEmpty)
  1291. throw new TlsFatalAlert(AlertDescription.internal_error);
  1292. // TODO[tls13] Actual structure is 'CertificateVerify' in RFC 8446, consider adding for clarity
  1293. DigitallySigned certificateVerify = DigitallySigned.Parse(m_tlsClientContext, buf);
  1294. AssertEmpty(buf);
  1295. TlsUtilities.Verify13CertificateVerifyServer(m_tlsClientContext, certificateVerify, m_handshakeHash);
  1296. }
  1297. /// <exception cref="IOException"/>
  1298. protected virtual void Receive13ServerFinished(MemoryStream buf)
  1299. {
  1300. Process13FinishedMessage(buf);
  1301. }
  1302. /// <exception cref="IOException"/>
  1303. protected virtual void ReceiveCertificateRequest(MemoryStream buf)
  1304. {
  1305. if (null == m_authentication)
  1306. {
  1307. /*
  1308. * RFC 2246 7.4.4. It is a fatal handshake_failure alert for an anonymous server to
  1309. * request client identification.
  1310. */
  1311. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  1312. }
  1313. CertificateRequest certificateRequest = CertificateRequest.Parse(m_tlsClientContext, buf);
  1314. AssertEmpty(buf);
  1315. this.m_certificateRequest = TlsUtilities.ValidateCertificateRequest(certificateRequest, m_keyExchange);
  1316. }
  1317. /// <exception cref="IOException"/>
  1318. protected virtual void ReceiveNewSessionTicket(MemoryStream buf)
  1319. {
  1320. NewSessionTicket newSessionTicket = NewSessionTicket.Parse(buf);
  1321. AssertEmpty(buf);
  1322. m_tlsClient.NotifyNewSessionTicket(newSessionTicket);
  1323. }
  1324. /// <exception cref="IOException"/>
  1325. protected virtual ServerHello ReceiveServerHelloMessage(MemoryStream buf)
  1326. {
  1327. return ServerHello.Parse(buf);
  1328. }
  1329. /// <exception cref="IOException"/>
  1330. protected virtual void Send13ClientHelloRetry()
  1331. {
  1332. IDictionary clientHelloExtensions = m_clientHello.Extensions;
  1333. clientHelloExtensions.Remove(ExtensionType.cookie);
  1334. clientHelloExtensions.Remove(ExtensionType.early_data);
  1335. clientHelloExtensions.Remove(ExtensionType.key_share);
  1336. clientHelloExtensions.Remove(ExtensionType.pre_shared_key);
  1337. /*
  1338. * RFC 4.2.2. When sending the new ClientHello, the client MUST copy the contents of the
  1339. * extension received in the HelloRetryRequest into a "cookie" extension in the new
  1340. * ClientHello.
  1341. */
  1342. if (null != m_retryCookie)
  1343. {
  1344. /*
  1345. * - Including a "cookie" extension if one was provided in the HelloRetryRequest.
  1346. */
  1347. TlsExtensionsUtilities.AddCookieExtension(clientHelloExtensions, m_retryCookie);
  1348. this.m_retryCookie = null;
  1349. }
  1350. /*
  1351. * - Updating the "pre_shared_key" extension if present by recomputing the "obfuscated_ticket_age"
  1352. * and binder values and (optionally) removing any PSKs which are incompatible with the server's
  1353. * indicated cipher suite.
  1354. */
  1355. if (null != m_clientBinders)
  1356. {
  1357. this.m_clientBinders = TlsUtilities.AddPreSharedKeyToClientHelloRetry(m_tlsClientContext,
  1358. m_clientBinders, clientHelloExtensions);
  1359. if (null == m_clientBinders)
  1360. {
  1361. m_tlsClient.NotifySelectedPsk(null);
  1362. }
  1363. }
  1364. /*
  1365. * RFC 8446 4.2.8. [..] when sending the new ClientHello, the client MUST replace the
  1366. * original "key_share" extension with one containing only a new KeyShareEntry for the group
  1367. * indicated in the selected_group field of the triggering HelloRetryRequest.
  1368. */
  1369. if (m_retryGroup < 0)
  1370. throw new TlsFatalAlert(AlertDescription.internal_error);
  1371. /*
  1372. * - If a "key_share" extension was supplied in the HelloRetryRequest, replacing the list of shares
  1373. * with a list containing a single KeyShareEntry from the indicated group
  1374. */
  1375. this.m_clientAgreements = TlsUtilities.AddKeyShareToClientHelloRetry(m_tlsClientContext,
  1376. clientHelloExtensions, m_retryGroup);
  1377. /*
  1378. * TODO[tls13] Optionally adding, removing, or changing the length of the "padding"
  1379. * extension [RFC7685].
  1380. */
  1381. // See RFC 8446 D.4.
  1382. {
  1383. m_recordStream.SetIgnoreChangeCipherSpec(true);
  1384. /*
  1385. * TODO[tls13] If offering early_data, the record is placed immediately after the first
  1386. * ClientHello.
  1387. */
  1388. SendChangeCipherSpecMessage();
  1389. }
  1390. SendClientHelloMessage();
  1391. }
  1392. /// <exception cref="IOException"/>
  1393. protected virtual void SendCertificateVerifyMessage(DigitallySigned certificateVerify)
  1394. {
  1395. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.certificate_verify);
  1396. certificateVerify.Encode(message);
  1397. message.Send(this);
  1398. }
  1399. /// <exception cref="IOException"/>
  1400. protected virtual void SendClientHello()
  1401. {
  1402. SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters;
  1403. ProtocolVersion[] supportedVersions = m_tlsClient.GetProtocolVersions();
  1404. ProtocolVersion earliestVersion = ProtocolVersion.GetEarliestTls(supportedVersions),
  1405. latestVersion = ProtocolVersion.GetLatestTls(supportedVersions);
  1406. if (securityParameters.IsRenegotiating)
  1407. {
  1408. latestVersion = m_tlsClientContext.ClientVersion;
  1409. }
  1410. else
  1411. {
  1412. m_tlsClientContext.SetClientSupportedVersions(supportedVersions);
  1413. if (ProtocolVersion.Contains(supportedVersions, ProtocolVersion.SSLv3))
  1414. {
  1415. // TODO[tls13] Prevent offering SSLv3 AND TLSv13?
  1416. m_recordStream.SetWriteVersion(ProtocolVersion.SSLv3);
  1417. }
  1418. else
  1419. {
  1420. m_recordStream.SetWriteVersion(ProtocolVersion.TLSv10);
  1421. }
  1422. //earliestVersion = ProtocolVersion.GetEarliestTls(supportedVersions);
  1423. //latestVersion = ProtocolVersion.GetLatestTls(supportedVersions);
  1424. if (!ProtocolVersion.IsSupportedTlsVersionClient(latestVersion))
  1425. throw new TlsFatalAlert(AlertDescription.internal_error);
  1426. m_tlsClientContext.SetClientVersion(latestVersion);
  1427. }
  1428. bool offeringTlsV12Minus = ProtocolVersion.TLSv12.IsEqualOrLaterVersionOf(earliestVersion);
  1429. bool offeringTlsV13Plus = ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(latestVersion);
  1430. EstablishSession(offeringTlsV12Minus ? m_tlsClient.GetSessionToResume() : null);
  1431. m_tlsClient.NotifySessionToResume(m_tlsSession);
  1432. /*
  1433. * TODO RFC 5077 3.4. When presenting a ticket, the client MAY generate and include a
  1434. * Session ID in the TLS ClientHello.
  1435. */
  1436. byte[] legacy_session_id = TlsUtilities.GetSessionID(m_tlsSession);
  1437. bool fallback = m_tlsClient.IsFallback();
  1438. int[] offeredCipherSuites = m_tlsClient.GetCipherSuites();
  1439. if (legacy_session_id.Length > 0 && m_sessionParameters != null)
  1440. {
  1441. if (!Arrays.Contains(offeredCipherSuites, m_sessionParameters.CipherSuite))
  1442. {
  1443. legacy_session_id = TlsUtilities.EmptyBytes;
  1444. }
  1445. }
  1446. this.m_clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(
  1447. m_tlsClient.GetClientExtensions());
  1448. ProtocolVersion legacy_version = latestVersion;
  1449. if (offeringTlsV13Plus)
  1450. {
  1451. legacy_version = ProtocolVersion.TLSv12;
  1452. TlsExtensionsUtilities.AddSupportedVersionsExtensionClient(m_clientExtensions, supportedVersions);
  1453. /*
  1454. * RFC 8446 4.2.1. In compatibility mode [..], this field MUST be non-empty, so a client
  1455. * not offering a pre-TLS 1.3 session MUST generate a new 32-byte value.
  1456. */
  1457. if (legacy_session_id.Length < 1)
  1458. {
  1459. legacy_session_id = m_tlsClientContext.NonceGenerator.GenerateNonce(32);
  1460. }
  1461. }
  1462. m_tlsClientContext.SetRsaPreMasterSecretVersion(legacy_version);
  1463. securityParameters.m_clientServerNames = TlsExtensionsUtilities.GetServerNameExtensionClient(
  1464. m_clientExtensions);
  1465. if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(latestVersion))
  1466. {
  1467. TlsUtilities.EstablishClientSigAlgs(securityParameters, m_clientExtensions);
  1468. }
  1469. securityParameters.m_clientSupportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(
  1470. m_clientExtensions);
  1471. this.m_clientBinders = TlsUtilities.AddPreSharedKeyToClientHello(m_tlsClientContext, m_tlsClient,
  1472. m_clientExtensions, offeredCipherSuites);
  1473. // TODO[tls13-psk] Perhaps don't add key_share if external PSK(s) offered and 'psk_dhe_ke' not offered
  1474. this.m_clientAgreements = TlsUtilities.AddKeyShareToClientHello(m_tlsClientContext, m_tlsClient,
  1475. m_clientExtensions);
  1476. if (TlsUtilities.IsExtendedMasterSecretOptionalTls(supportedVersions)
  1477. && (m_tlsClient.ShouldUseExtendedMasterSecret() ||
  1478. (null != m_sessionParameters && m_sessionParameters.IsExtendedMasterSecret)))
  1479. {
  1480. TlsExtensionsUtilities.AddExtendedMasterSecretExtension(m_clientExtensions);
  1481. }
  1482. else if (!offeringTlsV13Plus && m_tlsClient.RequiresExtendedMasterSecret())
  1483. {
  1484. throw new TlsFatalAlert(AlertDescription.internal_error);
  1485. }
  1486. {
  1487. bool useGmtUnixTime = !offeringTlsV13Plus && m_tlsClient.ShouldUseGmtUnixTime();
  1488. securityParameters.m_clientRandom = CreateRandomBlock(useGmtUnixTime, m_tlsClientContext);
  1489. }
  1490. if (securityParameters.IsRenegotiating)
  1491. {
  1492. /*
  1493. * RFC 5746 3.5. Client Behavior: Secure Renegotiation
  1494. *
  1495. * This text applies if the connection's "secure_renegotiation" flag is set to TRUE.
  1496. */
  1497. if (!securityParameters.IsSecureRenegotiation)
  1498. {
  1499. throw new TlsFatalAlert(AlertDescription.internal_error);
  1500. }
  1501. /*
  1502. * The client MUST include the "renegotiation_info" extension in the ClientHello,
  1503. * containing the saved client_verify_data. The SCSV MUST NOT be included.
  1504. */
  1505. SecurityParameters saved = m_tlsClientContext.SecurityParameters;
  1506. m_clientExtensions[ExtensionType.renegotiation_info] = TlsProtocol.CreateRenegotiationInfo(saved.LocalVerifyData);
  1507. }
  1508. else
  1509. {
  1510. /*
  1511. * RFC 5746 3.4. Client Behavior: Initial Handshake (both full and session-resumption)
  1512. */
  1513. /*
  1514. * The client MUST include either an empty "renegotiation_info" extension, or the
  1515. * TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the ClientHello.
  1516. * Including both is NOT RECOMMENDED.
  1517. */
  1518. bool noRenegExt = (null == TlsUtilities.GetExtensionData(m_clientExtensions,
  1519. ExtensionType.renegotiation_info));
  1520. bool noRenegScsv = !Arrays.Contains(offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
  1521. if (noRenegExt && noRenegScsv)
  1522. {
  1523. // TODO[tls13] Probably want to not add this if no pre-TLSv13 versions offered?
  1524. offeredCipherSuites = Arrays.Append(offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
  1525. }
  1526. }
  1527. /*
  1528. * (Fallback SCSV)
  1529. * RFC 7507 4. If a client sends a ClientHello.client_version containing a lower value
  1530. * than the latest (highest-valued) version supported by the client, it SHOULD include
  1531. * the TLS_FALLBACK_SCSV cipher suite value in ClientHello.cipher_suites [..]. (The
  1532. * client SHOULD put TLS_FALLBACK_SCSV after all cipher suites that it actually intends
  1533. * to negotiate.)
  1534. */
  1535. if (fallback && !Arrays.Contains(offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV))
  1536. {
  1537. offeredCipherSuites = Arrays.Append(offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV);
  1538. }
  1539. int bindersSize = null == m_clientBinders ? 0 : m_clientBinders.m_bindersSize;
  1540. this.m_clientHello = new ClientHello(legacy_version, securityParameters.ClientRandom, legacy_session_id,
  1541. null, offeredCipherSuites, m_clientExtensions, bindersSize);
  1542. SendClientHelloMessage();
  1543. }
  1544. /// <exception cref="IOException"/>
  1545. protected virtual void SendClientHelloMessage()
  1546. {
  1547. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.client_hello);
  1548. m_clientHello.Encode(m_tlsClientContext, message);
  1549. message.PrepareClientHello(m_handshakeHash, m_clientHello.BindersSize);
  1550. if (null != m_clientBinders)
  1551. {
  1552. OfferedPsks.EncodeBinders(message, m_tlsClientContext.Crypto, m_handshakeHash, m_clientBinders);
  1553. }
  1554. message.SendClientHello(this, m_handshakeHash, m_clientHello.BindersSize);
  1555. }
  1556. /// <exception cref="IOException"/>
  1557. protected virtual void SendClientKeyExchange()
  1558. {
  1559. HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.client_key_exchange);
  1560. m_keyExchange.GenerateClientKeyExchange(message);
  1561. message.Send(this);
  1562. }
  1563. /// <exception cref="IOException"/>
  1564. protected virtual void Skip13CertificateRequest()
  1565. {
  1566. this.m_certificateRequest = null;
  1567. }
  1568. /// <exception cref="IOException"/>
  1569. protected virtual void Skip13ServerCertificate()
  1570. {
  1571. if (!m_selectedPsk13)
  1572. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  1573. this.m_authentication = TlsUtilities.Skip13ServerCertificate(m_tlsClientContext);
  1574. }
  1575. }
  1576. }
  1577. #pragma warning restore
  1578. #endif