TlsClientProtocol.cs 80 KB

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