TlsServerProtocol.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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.Asn1.X509;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  11. {
  12. public class TlsServerProtocol
  13. : TlsProtocol
  14. {
  15. protected TlsServer mTlsServer = null;
  16. internal TlsServerContextImpl mTlsServerContext = null;
  17. protected TlsKeyExchange mKeyExchange = null;
  18. protected TlsCredentials mServerCredentials = null;
  19. protected CertificateRequest mCertificateRequest = null;
  20. protected short mClientCertificateType = -1;
  21. protected TlsHandshakeHash mPrepareFinishHash = null;
  22. /**
  23. * Constructor for blocking mode.
  24. * @param stream The bi-directional stream of data to/from the client
  25. * @param output The stream of data to the client
  26. * @param secureRandom Random number generator for various cryptographic functions
  27. */
  28. public TlsServerProtocol(Stream stream, SecureRandom secureRandom)
  29. : base(stream, secureRandom)
  30. {
  31. }
  32. /**
  33. * Constructor for blocking mode.
  34. * @param input The stream of data from the client
  35. * @param output The stream of data to the client
  36. * @param secureRandom Random number generator for various cryptographic functions
  37. */
  38. public TlsServerProtocol(Stream input, Stream output, SecureRandom secureRandom)
  39. : base(input, output, secureRandom)
  40. {
  41. }
  42. /**
  43. * Constructor for non-blocking mode.<br/>
  44. * <br/>
  45. * When data is received, use {@link #offerInput(java.nio.ByteBuffer)} to
  46. * provide the received ciphertext, then use
  47. * {@link #readInput(byte[], int, int)} to read the corresponding cleartext.<br/>
  48. * <br/>
  49. * Similarly, when data needs to be sent, use
  50. * {@link #offerOutput(byte[], int, int)} to provide the cleartext, then use
  51. * {@link #readOutput(byte[], int, int)} to get the corresponding
  52. * ciphertext.
  53. *
  54. * @param secureRandom
  55. * Random number generator for various cryptographic functions
  56. */
  57. public TlsServerProtocol(SecureRandom secureRandom)
  58. : base(secureRandom)
  59. {
  60. }
  61. /**
  62. * Receives a TLS handshake in the role of server.<br/>
  63. * <br/>
  64. * In blocking mode, this will not return until the handshake is complete.
  65. * In non-blocking mode, use {@link TlsPeer#notifyHandshakeComplete()} to
  66. * receive a callback when the handshake is complete.
  67. *
  68. * @param tlsServer
  69. * @throws IOException If in blocking mode and handshake was not successful.
  70. */
  71. public virtual void Accept(TlsServer tlsServer)
  72. {
  73. if (tlsServer == null)
  74. throw new ArgumentNullException("tlsServer");
  75. if (this.mTlsServer != null)
  76. throw new InvalidOperationException("'Accept' can only be called once");
  77. this.mTlsServer = tlsServer;
  78. this.mSecurityParameters = new SecurityParameters();
  79. this.mSecurityParameters.entity = ConnectionEnd.server;
  80. this.mTlsServerContext = new TlsServerContextImpl(mSecureRandom, mSecurityParameters);
  81. this.mSecurityParameters.serverRandom = CreateRandomBlock(tlsServer.ShouldUseGmtUnixTime(),
  82. mTlsServerContext.NonceRandomGenerator);
  83. this.mTlsServer.Init(mTlsServerContext);
  84. this.mRecordStream.Init(mTlsServerContext);
  85. this.mRecordStream.SetRestrictReadVersion(false);
  86. BlockForHandshake();
  87. }
  88. protected override void CleanupHandshake()
  89. {
  90. base.CleanupHandshake();
  91. this.mKeyExchange = null;
  92. this.mServerCredentials = null;
  93. this.mCertificateRequest = null;
  94. this.mPrepareFinishHash = null;
  95. }
  96. protected override TlsContext Context
  97. {
  98. get { return mTlsServerContext; }
  99. }
  100. internal override AbstractTlsContext ContextAdmin
  101. {
  102. get { return mTlsServerContext; }
  103. }
  104. protected override TlsPeer Peer
  105. {
  106. get { return mTlsServer; }
  107. }
  108. protected override void HandleHandshakeMessage(byte type, MemoryStream buf)
  109. {
  110. switch (type)
  111. {
  112. case HandshakeType.client_hello:
  113. {
  114. switch (this.mConnectionState)
  115. {
  116. case CS_START:
  117. {
  118. ReceiveClientHelloMessage(buf);
  119. this.mConnectionState = CS_CLIENT_HELLO;
  120. SendServerHelloMessage();
  121. this.mConnectionState = CS_SERVER_HELLO;
  122. mRecordStream.NotifyHelloComplete();
  123. IList serverSupplementalData = mTlsServer.GetServerSupplementalData();
  124. if (serverSupplementalData != null)
  125. {
  126. SendSupplementalDataMessage(serverSupplementalData);
  127. }
  128. this.mConnectionState = CS_SERVER_SUPPLEMENTAL_DATA;
  129. this.mKeyExchange = mTlsServer.GetKeyExchange();
  130. this.mKeyExchange.Init(Context);
  131. this.mServerCredentials = mTlsServer.GetCredentials();
  132. Certificate serverCertificate = null;
  133. if (this.mServerCredentials == null)
  134. {
  135. this.mKeyExchange.SkipServerCredentials();
  136. }
  137. else
  138. {
  139. this.mKeyExchange.ProcessServerCredentials(this.mServerCredentials);
  140. serverCertificate = this.mServerCredentials.Certificate;
  141. SendCertificateMessage(serverCertificate);
  142. }
  143. this.mConnectionState = CS_SERVER_CERTIFICATE;
  144. // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
  145. if (serverCertificate == null || serverCertificate.IsEmpty)
  146. {
  147. this.mAllowCertificateStatus = false;
  148. }
  149. if (this.mAllowCertificateStatus)
  150. {
  151. CertificateStatus certificateStatus = mTlsServer.GetCertificateStatus();
  152. if (certificateStatus != null)
  153. {
  154. SendCertificateStatusMessage(certificateStatus);
  155. }
  156. }
  157. this.mConnectionState = CS_CERTIFICATE_STATUS;
  158. byte[] serverKeyExchange = this.mKeyExchange.GenerateServerKeyExchange();
  159. if (serverKeyExchange != null)
  160. {
  161. SendServerKeyExchangeMessage(serverKeyExchange);
  162. }
  163. this.mConnectionState = CS_SERVER_KEY_EXCHANGE;
  164. if (this.mServerCredentials != null)
  165. {
  166. this.mCertificateRequest = mTlsServer.GetCertificateRequest();
  167. if (this.mCertificateRequest != null)
  168. {
  169. if (TlsUtilities.IsTlsV12(Context) != (mCertificateRequest.SupportedSignatureAlgorithms != null))
  170. throw new TlsFatalAlert(AlertDescription.internal_error);
  171. this.mKeyExchange.ValidateCertificateRequest(mCertificateRequest);
  172. SendCertificateRequestMessage(mCertificateRequest);
  173. TlsUtilities.TrackHashAlgorithms(this.mRecordStream.HandshakeHash,
  174. this.mCertificateRequest.SupportedSignatureAlgorithms);
  175. }
  176. }
  177. this.mConnectionState = CS_CERTIFICATE_REQUEST;
  178. SendServerHelloDoneMessage();
  179. this.mConnectionState = CS_SERVER_HELLO_DONE;
  180. this.mRecordStream.HandshakeHash.SealHashAlgorithms();
  181. break;
  182. }
  183. case CS_END:
  184. {
  185. RefuseRenegotiation();
  186. break;
  187. }
  188. default:
  189. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  190. }
  191. break;
  192. }
  193. case HandshakeType.supplemental_data:
  194. {
  195. switch (this.mConnectionState)
  196. {
  197. case CS_SERVER_HELLO_DONE:
  198. {
  199. mTlsServer.ProcessClientSupplementalData(ReadSupplementalDataMessage(buf));
  200. this.mConnectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
  201. break;
  202. }
  203. default:
  204. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  205. }
  206. break;
  207. }
  208. case HandshakeType.certificate:
  209. {
  210. switch (this.mConnectionState)
  211. {
  212. case CS_SERVER_HELLO_DONE:
  213. case CS_CLIENT_SUPPLEMENTAL_DATA:
  214. {
  215. if (mConnectionState < CS_CLIENT_SUPPLEMENTAL_DATA)
  216. {
  217. mTlsServer.ProcessClientSupplementalData(null);
  218. }
  219. if (this.mCertificateRequest == null)
  220. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  221. ReceiveCertificateMessage(buf);
  222. this.mConnectionState = CS_CLIENT_CERTIFICATE;
  223. break;
  224. }
  225. default:
  226. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  227. }
  228. break;
  229. }
  230. case HandshakeType.client_key_exchange:
  231. {
  232. switch (this.mConnectionState)
  233. {
  234. case CS_SERVER_HELLO_DONE:
  235. case CS_CLIENT_SUPPLEMENTAL_DATA:
  236. case CS_CLIENT_CERTIFICATE:
  237. {
  238. if (mConnectionState < CS_CLIENT_SUPPLEMENTAL_DATA)
  239. {
  240. mTlsServer.ProcessClientSupplementalData(null);
  241. }
  242. if (mConnectionState < CS_CLIENT_CERTIFICATE)
  243. {
  244. if (this.mCertificateRequest == null)
  245. {
  246. this.mKeyExchange.SkipClientCredentials();
  247. }
  248. else
  249. {
  250. if (TlsUtilities.IsTlsV12(Context))
  251. {
  252. /*
  253. * RFC 5246 If no suitable certificate is available, the client MUST Send a
  254. * certificate message containing no certificates.
  255. *
  256. * NOTE: In previous RFCs, this was SHOULD instead of MUST.
  257. */
  258. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  259. }
  260. else if (TlsUtilities.IsSsl(Context))
  261. {
  262. if (this.mPeerCertificate == null)
  263. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  264. }
  265. else
  266. {
  267. NotifyClientCertificate(Certificate.EmptyChain);
  268. }
  269. }
  270. }
  271. ReceiveClientKeyExchangeMessage(buf);
  272. this.mConnectionState = CS_CLIENT_KEY_EXCHANGE;
  273. break;
  274. }
  275. default:
  276. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  277. }
  278. break;
  279. }
  280. case HandshakeType.certificate_verify:
  281. {
  282. switch (this.mConnectionState)
  283. {
  284. case CS_CLIENT_KEY_EXCHANGE:
  285. {
  286. /*
  287. * RFC 5246 7.4.8 This message is only sent following a client certificate that has
  288. * signing capability (i.e., all certificates except those containing fixed
  289. * Diffie-Hellman parameters).
  290. */
  291. if (!ExpectCertificateVerifyMessage())
  292. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  293. ReceiveCertificateVerifyMessage(buf);
  294. this.mConnectionState = CS_CERTIFICATE_VERIFY;
  295. break;
  296. }
  297. default:
  298. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  299. }
  300. break;
  301. }
  302. case HandshakeType.finished:
  303. {
  304. switch (this.mConnectionState)
  305. {
  306. case CS_CLIENT_KEY_EXCHANGE:
  307. case CS_CERTIFICATE_VERIFY:
  308. {
  309. if (mConnectionState < CS_CERTIFICATE_VERIFY && ExpectCertificateVerifyMessage())
  310. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  311. ProcessFinishedMessage(buf);
  312. this.mConnectionState = CS_CLIENT_FINISHED;
  313. if (this.mExpectSessionTicket)
  314. {
  315. SendNewSessionTicketMessage(mTlsServer.GetNewSessionTicket());
  316. }
  317. this.mConnectionState = CS_SERVER_SESSION_TICKET;
  318. SendChangeCipherSpecMessage();
  319. SendFinishedMessage();
  320. this.mConnectionState = CS_SERVER_FINISHED;
  321. CompleteHandshake();
  322. break;
  323. }
  324. default:
  325. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  326. }
  327. break;
  328. }
  329. case HandshakeType.hello_request:
  330. case HandshakeType.hello_verify_request:
  331. case HandshakeType.server_hello:
  332. case HandshakeType.server_key_exchange:
  333. case HandshakeType.certificate_request:
  334. case HandshakeType.server_hello_done:
  335. case HandshakeType.session_ticket:
  336. default:
  337. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  338. }
  339. }
  340. protected override void HandleAlertWarningMessage(byte alertDescription)
  341. {
  342. base.HandleAlertWarningMessage(alertDescription);
  343. switch (alertDescription)
  344. {
  345. case AlertDescription.no_certificate:
  346. {
  347. /*
  348. * SSL 3.0 If the server has sent a certificate request Message, the client must send
  349. * either the certificate message or a no_certificate alert.
  350. */
  351. if (TlsUtilities.IsSsl(Context) && this.mCertificateRequest != null)
  352. {
  353. switch (this.mConnectionState)
  354. {
  355. case CS_SERVER_HELLO_DONE:
  356. case CS_CLIENT_SUPPLEMENTAL_DATA:
  357. {
  358. if (mConnectionState < CS_CLIENT_SUPPLEMENTAL_DATA)
  359. {
  360. mTlsServer.ProcessClientSupplementalData(null);
  361. }
  362. NotifyClientCertificate(Certificate.EmptyChain);
  363. this.mConnectionState = CS_CLIENT_CERTIFICATE;
  364. return;
  365. }
  366. }
  367. }
  368. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  369. }
  370. }
  371. }
  372. protected virtual void NotifyClientCertificate(Certificate clientCertificate)
  373. {
  374. if (mCertificateRequest == null)
  375. throw new InvalidOperationException();
  376. if (mPeerCertificate != null)
  377. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  378. this.mPeerCertificate = clientCertificate;
  379. if (clientCertificate.IsEmpty)
  380. {
  381. this.mKeyExchange.SkipClientCredentials();
  382. }
  383. else
  384. {
  385. /*
  386. * TODO RFC 5246 7.4.6. If the certificate_authorities list in the certificate request
  387. * message was non-empty, one of the certificates in the certificate chain SHOULD be
  388. * issued by one of the listed CAs.
  389. */
  390. this.mClientCertificateType = TlsUtilities.GetClientCertificateType(clientCertificate,
  391. this.mServerCredentials.Certificate);
  392. this.mKeyExchange.ProcessClientCertificate(clientCertificate);
  393. }
  394. /*
  395. * RFC 5246 7.4.6. If the client does not Send any certificates, the server MAY at its
  396. * discretion either continue the handshake without client authentication, or respond with a
  397. * fatal handshake_failure alert. Also, if some aspect of the certificate chain was
  398. * unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its
  399. * discretion either continue the handshake (considering the client unauthenticated) or Send
  400. * a fatal alert.
  401. */
  402. this.mTlsServer.NotifyClientCertificate(clientCertificate);
  403. }
  404. protected virtual void ReceiveCertificateMessage(MemoryStream buf)
  405. {
  406. Certificate clientCertificate = Certificate.Parse(buf);
  407. AssertEmpty(buf);
  408. NotifyClientCertificate(clientCertificate);
  409. }
  410. protected virtual void ReceiveCertificateVerifyMessage(MemoryStream buf)
  411. {
  412. if (mCertificateRequest == null)
  413. throw new InvalidOperationException();
  414. DigitallySigned clientCertificateVerify = DigitallySigned.Parse(Context, buf);
  415. AssertEmpty(buf);
  416. // Verify the CertificateVerify message contains a correct signature.
  417. try
  418. {
  419. SignatureAndHashAlgorithm signatureAlgorithm = clientCertificateVerify.Algorithm;
  420. byte[] hash;
  421. if (TlsUtilities.IsTlsV12(Context))
  422. {
  423. TlsUtilities.VerifySupportedSignatureAlgorithm(mCertificateRequest.SupportedSignatureAlgorithms, signatureAlgorithm);
  424. hash = mPrepareFinishHash.GetFinalHash(signatureAlgorithm.Hash);
  425. }
  426. else
  427. {
  428. hash = mSecurityParameters.SessionHash;
  429. }
  430. X509CertificateStructure x509Cert = mPeerCertificate.GetCertificateAt(0);
  431. SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
  432. AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(keyInfo);
  433. TlsSigner tlsSigner = TlsUtilities.CreateTlsSigner((byte)mClientCertificateType);
  434. tlsSigner.Init(Context);
  435. if (!tlsSigner.VerifyRawSignature(signatureAlgorithm, clientCertificateVerify.Signature, publicKey, hash))
  436. throw new TlsFatalAlert(AlertDescription.decrypt_error);
  437. }
  438. catch (TlsFatalAlert e)
  439. {
  440. throw e;
  441. }
  442. catch (Exception e)
  443. {
  444. throw new TlsFatalAlert(AlertDescription.decrypt_error, e);
  445. }
  446. }
  447. protected virtual void ReceiveClientHelloMessage(MemoryStream buf)
  448. {
  449. ProtocolVersion client_version = TlsUtilities.ReadVersion(buf);
  450. mRecordStream.SetWriteVersion(client_version);
  451. if (client_version.IsDtls)
  452. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  453. byte[] client_random = TlsUtilities.ReadFully(32, buf);
  454. /*
  455. * TODO RFC 5077 3.4. If a ticket is presented by the client, the server MUST NOT attempt to
  456. * use the Session ID in the ClientHello for stateful session resumption.
  457. */
  458. byte[] sessionID = TlsUtilities.ReadOpaque8(buf);
  459. if (sessionID.Length > 32)
  460. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  461. /*
  462. * TODO RFC 5246 7.4.1.2. If the session_id field is not empty (implying a session
  463. * resumption request), this vector MUST include at least the cipher_suite from that
  464. * session.
  465. */
  466. int cipher_suites_length = TlsUtilities.ReadUint16(buf);
  467. if (cipher_suites_length < 2 || (cipher_suites_length & 1) != 0)
  468. throw new TlsFatalAlert(AlertDescription.decode_error);
  469. this.mOfferedCipherSuites = TlsUtilities.ReadUint16Array(cipher_suites_length / 2, buf);
  470. /*
  471. * TODO RFC 5246 7.4.1.2. If the session_id field is not empty (implying a session
  472. * resumption request), it MUST include the compression_method from that session.
  473. */
  474. int compression_methods_length = TlsUtilities.ReadUint8(buf);
  475. if (compression_methods_length < 1)
  476. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  477. this.mOfferedCompressionMethods = TlsUtilities.ReadUint8Array(compression_methods_length, buf);
  478. /*
  479. * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
  480. * extensions appearing in the client hello, and Send a server hello containing no
  481. * extensions.
  482. */
  483. this.mClientExtensions = ReadExtensions(buf);
  484. /*
  485. * TODO[resumption] Check RFC 7627 5.4. for required behaviour
  486. */
  487. /*
  488. * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended
  489. * master secret [..]. (and see 5.2, 5.3)
  490. */
  491. this.mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mClientExtensions);
  492. if (!mSecurityParameters.IsExtendedMasterSecret && mTlsServer.RequiresExtendedMasterSecret())
  493. {
  494. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  495. }
  496. ContextAdmin.SetClientVersion(client_version);
  497. mTlsServer.NotifyClientVersion(client_version);
  498. mTlsServer.NotifyFallback(Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV));
  499. mSecurityParameters.clientRandom = client_random;
  500. mTlsServer.NotifyOfferedCipherSuites(mOfferedCipherSuites);
  501. mTlsServer.NotifyOfferedCompressionMethods(mOfferedCompressionMethods);
  502. /*
  503. * RFC 5746 3.6. Server Behavior: Initial Handshake
  504. */
  505. {
  506. /*
  507. * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
  508. * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
  509. * ClientHello. Including both is NOT RECOMMENDED.
  510. */
  511. /*
  512. * When a ClientHello is received, the server MUST check if it includes the
  513. * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If it does, set the secure_renegotiation flag
  514. * to TRUE.
  515. */
  516. if (Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV))
  517. {
  518. this.mSecureRenegotiation = true;
  519. }
  520. /*
  521. * The server MUST check if the "renegotiation_info" extension is included in the
  522. * ClientHello.
  523. */
  524. byte[] renegExtData = TlsUtilities.GetExtensionData(mClientExtensions, ExtensionType.renegotiation_info);
  525. if (renegExtData != null)
  526. {
  527. /*
  528. * If the extension is present, set secure_renegotiation flag to TRUE. The
  529. * server MUST then verify that the length of the "renegotiated_connection"
  530. * field is zero, and if it is not, MUST abort the handshake.
  531. */
  532. this.mSecureRenegotiation = true;
  533. if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
  534. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  535. }
  536. }
  537. mTlsServer.NotifySecureRenegotiation(this.mSecureRenegotiation);
  538. if (mClientExtensions != null)
  539. {
  540. // NOTE: Validates the padding extension data, if present
  541. TlsExtensionsUtilities.GetPaddingExtension(mClientExtensions);
  542. mTlsServer.ProcessClientExtensions(mClientExtensions);
  543. }
  544. }
  545. protected virtual void ReceiveClientKeyExchangeMessage(MemoryStream buf)
  546. {
  547. mKeyExchange.ProcessClientKeyExchange(buf);
  548. AssertEmpty(buf);
  549. if (TlsUtilities.IsSsl(Context))
  550. {
  551. EstablishMasterSecret(Context, mKeyExchange);
  552. }
  553. this.mPrepareFinishHash = mRecordStream.PrepareToFinish();
  554. this.mSecurityParameters.sessionHash = GetCurrentPrfHash(Context, mPrepareFinishHash, null);
  555. if (!TlsUtilities.IsSsl(Context))
  556. {
  557. EstablishMasterSecret(Context, mKeyExchange);
  558. }
  559. mRecordStream.SetPendingConnectionState(Peer.GetCompression(), Peer.GetCipher());
  560. }
  561. protected virtual void SendCertificateRequestMessage(CertificateRequest certificateRequest)
  562. {
  563. HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate_request);
  564. certificateRequest.Encode(message);
  565. message.WriteToRecordStream(this);
  566. }
  567. protected virtual void SendCertificateStatusMessage(CertificateStatus certificateStatus)
  568. {
  569. HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate_status);
  570. certificateStatus.Encode(message);
  571. message.WriteToRecordStream(this);
  572. }
  573. protected virtual void SendNewSessionTicketMessage(NewSessionTicket newSessionTicket)
  574. {
  575. if (newSessionTicket == null)
  576. throw new TlsFatalAlert(AlertDescription.internal_error);
  577. HandshakeMessage message = new HandshakeMessage(HandshakeType.session_ticket);
  578. newSessionTicket.Encode(message);
  579. message.WriteToRecordStream(this);
  580. }
  581. protected virtual void SendServerHelloMessage()
  582. {
  583. HandshakeMessage message = new HandshakeMessage(HandshakeType.server_hello);
  584. {
  585. ProtocolVersion server_version = mTlsServer.GetServerVersion();
  586. if (!server_version.IsEqualOrEarlierVersionOf(Context.ClientVersion))
  587. throw new TlsFatalAlert(AlertDescription.internal_error);
  588. mRecordStream.ReadVersion = server_version;
  589. mRecordStream.SetWriteVersion(server_version);
  590. mRecordStream.SetRestrictReadVersion(true);
  591. ContextAdmin.SetServerVersion(server_version);
  592. TlsUtilities.WriteVersion(server_version, message);
  593. }
  594. message.Write(this.mSecurityParameters.serverRandom);
  595. /*
  596. * The server may return an empty session_id to indicate that the session will not be cached
  597. * and therefore cannot be resumed.
  598. */
  599. TlsUtilities.WriteOpaque8(TlsUtilities.EmptyBytes, message);
  600. int selectedCipherSuite = mTlsServer.GetSelectedCipherSuite();
  601. if (!Arrays.Contains(mOfferedCipherSuites, selectedCipherSuite)
  602. || selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL
  603. || CipherSuite.IsScsv(selectedCipherSuite)
  604. || !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, Context.ServerVersion))
  605. {
  606. throw new TlsFatalAlert(AlertDescription.internal_error);
  607. }
  608. mSecurityParameters.cipherSuite = selectedCipherSuite;
  609. byte selectedCompressionMethod = mTlsServer.GetSelectedCompressionMethod();
  610. if (!Arrays.Contains(mOfferedCompressionMethods, selectedCompressionMethod))
  611. {
  612. throw new TlsFatalAlert(AlertDescription.internal_error);
  613. }
  614. mSecurityParameters.compressionAlgorithm = selectedCompressionMethod;
  615. TlsUtilities.WriteUint16(selectedCipherSuite, message);
  616. TlsUtilities.WriteUint8(selectedCompressionMethod, message);
  617. this.mServerExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(mTlsServer.GetServerExtensions());
  618. /*
  619. * RFC 5746 3.6. Server Behavior: Initial Handshake
  620. */
  621. if (this.mSecureRenegotiation)
  622. {
  623. byte[] renegExtData = TlsUtilities.GetExtensionData(this.mServerExtensions, ExtensionType.renegotiation_info);
  624. bool noRenegExt = (null == renegExtData);
  625. if (noRenegExt)
  626. {
  627. /*
  628. * Note that Sending a "renegotiation_info" extension in response to a ClientHello
  629. * containing only the SCSV is an explicit exception to the prohibition in RFC 5246,
  630. * Section 7.4.1.4, on the server Sending unsolicited extensions and is only allowed
  631. * because the client is signaling its willingness to receive the extension via the
  632. * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
  633. */
  634. /*
  635. * If the secure_renegotiation flag is set to TRUE, the server MUST include an empty
  636. * "renegotiation_info" extension in the ServerHello message.
  637. */
  638. this.mServerExtensions[ExtensionType.renegotiation_info] = CreateRenegotiationInfo(TlsUtilities.EmptyBytes);
  639. }
  640. }
  641. if (TlsUtilities.IsSsl(mTlsServerContext))
  642. {
  643. mSecurityParameters.extendedMasterSecret = false;
  644. }
  645. else if (mSecurityParameters.IsExtendedMasterSecret)
  646. {
  647. TlsExtensionsUtilities.AddExtendedMasterSecretExtension(mServerExtensions);
  648. }
  649. /*
  650. * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
  651. * extensions appearing in the client hello, and Send a server hello containing no
  652. * extensions.
  653. */
  654. if (this.mServerExtensions.Count > 0)
  655. {
  656. this.mSecurityParameters.encryptThenMac = TlsExtensionsUtilities.HasEncryptThenMacExtension(mServerExtensions);
  657. this.mSecurityParameters.maxFragmentLength = ProcessMaxFragmentLengthExtension(mClientExtensions,
  658. mServerExtensions, AlertDescription.internal_error);
  659. this.mSecurityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(mServerExtensions);
  660. /*
  661. * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
  662. * a session resumption handshake.
  663. */
  664. this.mAllowCertificateStatus = !mResumedSession
  665. && TlsUtilities.HasExpectedEmptyExtensionData(mServerExtensions, ExtensionType.status_request,
  666. AlertDescription.internal_error);
  667. this.mExpectSessionTicket = !mResumedSession
  668. && TlsUtilities.HasExpectedEmptyExtensionData(mServerExtensions, ExtensionType.session_ticket,
  669. AlertDescription.internal_error);
  670. WriteExtensions(message, this.mServerExtensions);
  671. }
  672. mSecurityParameters.prfAlgorithm = GetPrfAlgorithm(Context, mSecurityParameters.CipherSuite);
  673. /*
  674. * RFC 5246 7.4.9. Any cipher suite which does not explicitly specify verify_data_length has
  675. * a verify_data_length equal to 12. This includes all existing cipher suites.
  676. */
  677. mSecurityParameters.verifyDataLength = 12;
  678. ApplyMaxFragmentLengthExtension();
  679. message.WriteToRecordStream(this);
  680. }
  681. protected virtual void SendServerHelloDoneMessage()
  682. {
  683. byte[] message = new byte[4];
  684. TlsUtilities.WriteUint8(HandshakeType.server_hello_done, message, 0);
  685. TlsUtilities.WriteUint24(0, message, 1);
  686. WriteHandshakeMessage(message, 0, message.Length);
  687. }
  688. protected virtual void SendServerKeyExchangeMessage(byte[] serverKeyExchange)
  689. {
  690. HandshakeMessage message = new HandshakeMessage(HandshakeType.server_key_exchange, serverKeyExchange.Length);
  691. message.Write(serverKeyExchange);
  692. message.WriteToRecordStream(this);
  693. }
  694. protected virtual bool ExpectCertificateVerifyMessage()
  695. {
  696. return mClientCertificateType >= 0 && TlsUtilities.HasSigningCapability((byte)mClientCertificateType);
  697. }
  698. }
  699. }
  700. #pragma warning restore
  701. #endif