AbstractTlsServer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls
  9. {
  10. /// <summary>Base class for a TLS server.</summary>
  11. public abstract class AbstractTlsServer
  12. : AbstractTlsPeer, TlsServer
  13. {
  14. protected TlsServerContext m_context;
  15. protected ProtocolVersion[] m_protocolVersions;
  16. protected int[] m_cipherSuites;
  17. protected int[] m_offeredCipherSuites;
  18. protected IDictionary m_clientExtensions;
  19. protected bool m_encryptThenMACOffered;
  20. protected short m_maxFragmentLengthOffered;
  21. protected bool m_truncatedHMacOffered;
  22. protected bool m_clientSentECPointFormats;
  23. protected CertificateStatusRequest m_certificateStatusRequest;
  24. protected IList m_statusRequestV2;
  25. protected IList m_trustedCAKeys;
  26. protected int m_selectedCipherSuite;
  27. protected IList m_clientProtocolNames;
  28. protected ProtocolName m_selectedProtocolName;
  29. protected readonly IDictionary m_serverExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  30. public AbstractTlsServer(TlsCrypto crypto)
  31. : base(crypto)
  32. {
  33. }
  34. protected virtual bool AllowCertificateStatus()
  35. {
  36. return true;
  37. }
  38. protected virtual bool AllowEncryptThenMac()
  39. {
  40. return true;
  41. }
  42. protected virtual bool AllowMultiCertStatus()
  43. {
  44. return false;
  45. }
  46. protected virtual bool AllowTruncatedHmac()
  47. {
  48. return false;
  49. }
  50. protected virtual bool AllowTrustedCAIndication()
  51. {
  52. return false;
  53. }
  54. protected virtual int GetMaximumNegotiableCurveBits()
  55. {
  56. int[] clientSupportedGroups = m_context.SecurityParameters.ClientSupportedGroups;
  57. if (clientSupportedGroups == null)
  58. {
  59. /*
  60. * RFC 4492 4. A client that proposes ECC cipher suites may choose not to include these
  61. * extensions. In this case, the server is free to choose any one of the elliptic curves
  62. * or point formats [...].
  63. */
  64. return NamedGroup.GetMaximumCurveBits();
  65. }
  66. int maxBits = 0;
  67. for (int i = 0; i < clientSupportedGroups.Length; ++i)
  68. {
  69. maxBits = System.Math.Max(maxBits, NamedGroup.GetCurveBits(clientSupportedGroups[i]));
  70. }
  71. return maxBits;
  72. }
  73. protected virtual int GetMaximumNegotiableFiniteFieldBits()
  74. {
  75. int[] clientSupportedGroups = m_context.SecurityParameters.ClientSupportedGroups;
  76. if (clientSupportedGroups == null)
  77. {
  78. return NamedGroup.GetMaximumFiniteFieldBits();
  79. }
  80. int maxBits = 0;
  81. for (int i = 0; i < clientSupportedGroups.Length; ++i)
  82. {
  83. maxBits = System.Math.Max(maxBits, NamedGroup.GetFiniteFieldBits(clientSupportedGroups[i]));
  84. }
  85. return maxBits;
  86. }
  87. protected virtual IList GetProtocolNames()
  88. {
  89. return null;
  90. }
  91. protected virtual bool IsSelectableCipherSuite(int cipherSuite, int availCurveBits, int availFiniteFieldBits,
  92. IList sigAlgs)
  93. {
  94. // TODO[tls13] The version check should be separated out (eventually select ciphersuite before version)
  95. return TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, m_context.ServerVersion)
  96. && availCurveBits >= TlsEccUtilities.GetMinimumCurveBits(cipherSuite)
  97. && availFiniteFieldBits >= TlsDHUtilities.GetMinimumFiniteFieldBits(cipherSuite)
  98. && TlsUtilities.IsValidCipherSuiteForSignatureAlgorithms(cipherSuite, sigAlgs);
  99. }
  100. protected virtual bool PreferLocalCipherSuites()
  101. {
  102. return false;
  103. }
  104. /// <exception cref="IOException"/>
  105. protected virtual bool SelectCipherSuite(int cipherSuite)
  106. {
  107. this.m_selectedCipherSuite = cipherSuite;
  108. return true;
  109. }
  110. protected virtual int SelectDH(int minimumFiniteFieldBits)
  111. {
  112. int[] clientSupportedGroups = m_context.SecurityParameters.ClientSupportedGroups;
  113. if (clientSupportedGroups == null)
  114. return SelectDHDefault(minimumFiniteFieldBits);
  115. // Try to find a supported named group of the required size from the client's list.
  116. for (int i = 0; i < clientSupportedGroups.Length; ++i)
  117. {
  118. int namedGroup = clientSupportedGroups[i];
  119. if (NamedGroup.GetFiniteFieldBits(namedGroup) >= minimumFiniteFieldBits)
  120. return namedGroup;
  121. }
  122. return -1;
  123. }
  124. protected virtual int SelectDHDefault(int minimumFiniteFieldBits)
  125. {
  126. return minimumFiniteFieldBits <= 2048 ? NamedGroup.ffdhe2048
  127. : minimumFiniteFieldBits <= 3072 ? NamedGroup.ffdhe3072
  128. : minimumFiniteFieldBits <= 4096 ? NamedGroup.ffdhe4096
  129. : minimumFiniteFieldBits <= 6144 ? NamedGroup.ffdhe6144
  130. : minimumFiniteFieldBits <= 8192 ? NamedGroup.ffdhe8192
  131. : -1;
  132. }
  133. protected virtual int SelectECDH(int minimumCurveBits)
  134. {
  135. int[] clientSupportedGroups = m_context.SecurityParameters.ClientSupportedGroups;
  136. if (clientSupportedGroups == null)
  137. return SelectECDHDefault(minimumCurveBits);
  138. // Try to find a supported named group of the required size from the client's list.
  139. for (int i = 0; i < clientSupportedGroups.Length; ++i)
  140. {
  141. int namedGroup = clientSupportedGroups[i];
  142. if (NamedGroup.GetCurveBits(namedGroup) >= minimumCurveBits)
  143. return namedGroup;
  144. }
  145. return -1;
  146. }
  147. protected virtual int SelectECDHDefault(int minimumCurveBits)
  148. {
  149. return minimumCurveBits <= 256 ? NamedGroup.secp256r1
  150. : minimumCurveBits <= 384 ? NamedGroup.secp384r1
  151. : minimumCurveBits <= 521 ? NamedGroup.secp521r1
  152. : -1;
  153. }
  154. protected virtual ProtocolName SelectProtocolName()
  155. {
  156. IList serverProtocolNames = GetProtocolNames();
  157. if (null == serverProtocolNames || serverProtocolNames.Count < 1)
  158. return null;
  159. ProtocolName result = SelectProtocolName(m_clientProtocolNames, serverProtocolNames);
  160. if (null == result)
  161. throw new TlsFatalAlert(AlertDescription.no_application_protocol);
  162. return result;
  163. }
  164. protected virtual ProtocolName SelectProtocolName(IList clientProtocolNames, IList serverProtocolNames)
  165. {
  166. foreach (ProtocolName serverProtocolName in serverProtocolNames)
  167. {
  168. if (clientProtocolNames.Contains(serverProtocolName))
  169. return serverProtocolName;
  170. }
  171. return null;
  172. }
  173. protected virtual bool ShouldSelectProtocolNameEarly()
  174. {
  175. return true;
  176. }
  177. public virtual void Init(TlsServerContext context)
  178. {
  179. this.m_context = context;
  180. this.m_protocolVersions = GetSupportedVersions();
  181. this.m_cipherSuites = GetSupportedCipherSuites();
  182. }
  183. public override ProtocolVersion[] GetProtocolVersions()
  184. {
  185. return m_protocolVersions;
  186. }
  187. public override int[] GetCipherSuites()
  188. {
  189. return m_cipherSuites;
  190. }
  191. public override void NotifyHandshakeBeginning()
  192. {
  193. base.NotifyHandshakeBeginning();
  194. this.m_offeredCipherSuites = null;
  195. this.m_clientExtensions = null;
  196. this.m_encryptThenMACOffered = false;
  197. this.m_maxFragmentLengthOffered = 0;
  198. this.m_truncatedHMacOffered = false;
  199. this.m_clientSentECPointFormats = false;
  200. this.m_certificateStatusRequest = null;
  201. this.m_selectedCipherSuite = -1;
  202. this.m_selectedProtocolName = null;
  203. this.m_serverExtensions.Clear();
  204. }
  205. public virtual TlsSession GetSessionToResume(byte[] sessionID)
  206. {
  207. return null;
  208. }
  209. public virtual byte[] GetNewSessionID()
  210. {
  211. return null;
  212. }
  213. public virtual TlsPskExternal GetExternalPsk(IList identities)
  214. {
  215. return null;
  216. }
  217. public virtual void NotifySession(TlsSession session)
  218. {
  219. }
  220. public virtual void NotifyClientVersion(ProtocolVersion clientVersion)
  221. {
  222. }
  223. public virtual void NotifyFallback(bool isFallback)
  224. {
  225. /*
  226. * RFC 7507 3. If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest
  227. * protocol version supported by the server is higher than the version indicated in
  228. * ClientHello.client_version, the server MUST respond with a fatal inappropriate_fallback
  229. * alert [..].
  230. */
  231. if (isFallback)
  232. {
  233. ProtocolVersion[] serverVersions = GetProtocolVersions();
  234. ProtocolVersion clientVersion = m_context.ClientVersion;
  235. ProtocolVersion latestServerVersion;
  236. if (clientVersion.IsTls)
  237. {
  238. latestServerVersion = ProtocolVersion.GetLatestTls(serverVersions);
  239. }
  240. else if (clientVersion.IsDtls)
  241. {
  242. latestServerVersion = ProtocolVersion.GetLatestDtls(serverVersions);
  243. }
  244. else
  245. {
  246. throw new TlsFatalAlert(AlertDescription.internal_error);
  247. }
  248. if (null != latestServerVersion && latestServerVersion.IsLaterVersionOf(clientVersion))
  249. {
  250. throw new TlsFatalAlert(AlertDescription.inappropriate_fallback);
  251. }
  252. }
  253. }
  254. public virtual void NotifyOfferedCipherSuites(int[] offeredCipherSuites)
  255. {
  256. this.m_offeredCipherSuites = offeredCipherSuites;
  257. }
  258. public virtual void ProcessClientExtensions(IDictionary clientExtensions)
  259. {
  260. this.m_clientExtensions = clientExtensions;
  261. if (null != clientExtensions)
  262. {
  263. this.m_clientProtocolNames = TlsExtensionsUtilities.GetAlpnExtensionClient(clientExtensions);
  264. if (ShouldSelectProtocolNameEarly())
  265. {
  266. if (null != m_clientProtocolNames && m_clientProtocolNames.Count > 0)
  267. {
  268. this.m_selectedProtocolName = SelectProtocolName();
  269. }
  270. }
  271. // TODO[tls13] Don't need these if we have negotiated (D)TLS 1.3+
  272. {
  273. this.m_encryptThenMACOffered = TlsExtensionsUtilities.HasEncryptThenMacExtension(clientExtensions);
  274. this.m_truncatedHMacOffered = TlsExtensionsUtilities.HasTruncatedHmacExtension(clientExtensions);
  275. this.m_statusRequestV2 = TlsExtensionsUtilities.GetStatusRequestV2Extension(clientExtensions);
  276. this.m_trustedCAKeys = TlsExtensionsUtilities.GetTrustedCAKeysExtensionClient(clientExtensions);
  277. // We only support uncompressed format, this is just to validate the extension, and note its presence.
  278. this.m_clientSentECPointFormats =
  279. null != TlsExtensionsUtilities.GetSupportedPointFormatsExtension(clientExtensions);
  280. }
  281. this.m_certificateStatusRequest = TlsExtensionsUtilities.GetStatusRequestExtension(clientExtensions);
  282. this.m_maxFragmentLengthOffered = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(clientExtensions);
  283. if (m_maxFragmentLengthOffered >= 0 && !MaxFragmentLength.IsValid(m_maxFragmentLengthOffered))
  284. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  285. }
  286. }
  287. public virtual ProtocolVersion GetServerVersion()
  288. {
  289. ProtocolVersion[] serverVersions = GetProtocolVersions();
  290. ProtocolVersion[] clientVersions = m_context.ClientSupportedVersions;
  291. foreach (ProtocolVersion clientVersion in clientVersions)
  292. {
  293. if (ProtocolVersion.Contains(serverVersions, clientVersion))
  294. return clientVersion;
  295. }
  296. throw new TlsFatalAlert(AlertDescription.protocol_version);
  297. }
  298. public virtual int[] GetSupportedGroups()
  299. {
  300. // TODO[tls13] The rest of this class assumes all named groups are supported
  301. return new int[]{ NamedGroup.x25519, NamedGroup.x448, NamedGroup.secp256r1, NamedGroup.secp384r1,
  302. NamedGroup.ffdhe2048, NamedGroup.ffdhe3072, NamedGroup.ffdhe4096 };
  303. }
  304. public virtual int GetSelectedCipherSuite()
  305. {
  306. SecurityParameters securityParameters = m_context.SecurityParameters;
  307. ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion;
  308. if (TlsUtilities.IsTlsV13(negotiatedVersion))
  309. {
  310. int commonCipherSuite13 = TlsUtilities.GetCommonCipherSuite13(negotiatedVersion, m_offeredCipherSuites,
  311. GetCipherSuites(), PreferLocalCipherSuites());
  312. if (commonCipherSuite13 >= 0 && SelectCipherSuite(commonCipherSuite13))
  313. {
  314. return commonCipherSuite13;
  315. }
  316. }
  317. else
  318. {
  319. /*
  320. * RFC 5246 7.4.3. In order to negotiate correctly, the server MUST check any candidate
  321. * cipher suites against the "signature_algorithms" extension before selecting them. This is
  322. * somewhat inelegant but is a compromise designed to minimize changes to the original
  323. * cipher suite design.
  324. */
  325. IList sigAlgs = TlsUtilities.GetUsableSignatureAlgorithms(securityParameters.ClientSigAlgs);
  326. /*
  327. * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these
  328. * extensions MUST use the client's enumerated capabilities to guide its selection of an
  329. * appropriate cipher suite. One of the proposed ECC cipher suites must be negotiated only
  330. * if the server can successfully complete the handshake while using the curves and point
  331. * formats supported by the client [...].
  332. */
  333. int availCurveBits = GetMaximumNegotiableCurveBits();
  334. int availFiniteFieldBits = GetMaximumNegotiableFiniteFieldBits();
  335. int[] cipherSuites = TlsUtilities.GetCommonCipherSuites(m_offeredCipherSuites, GetCipherSuites(),
  336. PreferLocalCipherSuites());
  337. for (int i = 0; i < cipherSuites.Length; ++i)
  338. {
  339. int cipherSuite = cipherSuites[i];
  340. if (IsSelectableCipherSuite(cipherSuite, availCurveBits, availFiniteFieldBits, sigAlgs)
  341. && SelectCipherSuite(cipherSuite))
  342. {
  343. return cipherSuite;
  344. }
  345. }
  346. }
  347. throw new TlsFatalAlert(AlertDescription.handshake_failure, "No selectable cipher suite");
  348. }
  349. // IDictionary is (Int32 -> byte[])
  350. public virtual IDictionary GetServerExtensions()
  351. {
  352. bool isTlsV13 = TlsUtilities.IsTlsV13(m_context);
  353. if (isTlsV13)
  354. {
  355. if (null != m_certificateStatusRequest && AllowCertificateStatus())
  356. {
  357. /*
  358. * TODO[tls13] RFC 8446 4.4.2.1. OCSP Status and SCT Extensions.
  359. *
  360. * OCSP information is carried in an extension for a CertificateEntry.
  361. */
  362. }
  363. }
  364. else
  365. {
  366. if (m_encryptThenMACOffered && AllowEncryptThenMac())
  367. {
  368. /*
  369. * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
  370. * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
  371. * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
  372. * client.
  373. */
  374. if (TlsUtilities.IsBlockCipherSuite(m_selectedCipherSuite))
  375. {
  376. TlsExtensionsUtilities.AddEncryptThenMacExtension(m_serverExtensions);
  377. }
  378. }
  379. if (m_truncatedHMacOffered && AllowTruncatedHmac())
  380. {
  381. TlsExtensionsUtilities.AddTruncatedHmacExtension(m_serverExtensions);
  382. }
  383. if (m_clientSentECPointFormats && TlsEccUtilities.IsEccCipherSuite(m_selectedCipherSuite))
  384. {
  385. /*
  386. * RFC 4492 5.2. A server that selects an ECC cipher suite in response to a ClientHello
  387. * message including a Supported Point Formats Extension appends this extension (along
  388. * with others) to its ServerHello message, enumerating the point formats it can parse.
  389. */
  390. TlsExtensionsUtilities.AddSupportedPointFormatsExtension(m_serverExtensions,
  391. new short[]{ ECPointFormat.uncompressed });
  392. }
  393. // TODO[tls13] See RFC 8446 4.4.2.1
  394. if (null != m_statusRequestV2 && AllowMultiCertStatus())
  395. {
  396. /*
  397. * RFC 6961 2.2. If a server returns a "CertificateStatus" message in response to a
  398. * "status_request_v2" request, then the server MUST have included an extension of type
  399. * "status_request_v2" with empty "extension_data" in the extended server hello..
  400. */
  401. TlsExtensionsUtilities.AddEmptyExtensionData(m_serverExtensions, ExtensionType.status_request_v2);
  402. }
  403. else if (null != this.m_certificateStatusRequest && AllowCertificateStatus())
  404. {
  405. /*
  406. * RFC 6066 8. If a server returns a "CertificateStatus" message, then the server MUST
  407. * have included an extension of type "status_request" with empty "extension_data" in
  408. * the extended server hello.
  409. */
  410. TlsExtensionsUtilities.AddEmptyExtensionData(m_serverExtensions, ExtensionType.status_request);
  411. }
  412. if (null != m_trustedCAKeys && AllowTrustedCAIndication())
  413. {
  414. TlsExtensionsUtilities.AddTrustedCAKeysExtensionServer(m_serverExtensions);
  415. }
  416. }
  417. if (m_maxFragmentLengthOffered >= 0 && MaxFragmentLength.IsValid(m_maxFragmentLengthOffered))
  418. {
  419. TlsExtensionsUtilities.AddMaxFragmentLengthExtension(m_serverExtensions, m_maxFragmentLengthOffered);
  420. }
  421. return m_serverExtensions;
  422. }
  423. public virtual void GetServerExtensionsForConnection(IDictionary serverExtensions)
  424. {
  425. if (!ShouldSelectProtocolNameEarly())
  426. {
  427. if (null != m_clientProtocolNames && m_clientProtocolNames.Count > 0)
  428. {
  429. this.m_selectedProtocolName = SelectProtocolName();
  430. }
  431. }
  432. /*
  433. * RFC 7301 3.1. When session resumption or session tickets [...] are used, the previous
  434. * contents of this extension are irrelevant, and only the values in the new handshake
  435. * messages are considered.
  436. */
  437. if (null == m_selectedProtocolName)
  438. {
  439. serverExtensions.Remove(ExtensionType.application_layer_protocol_negotiation);
  440. }
  441. else
  442. {
  443. TlsExtensionsUtilities.AddAlpnExtensionServer(serverExtensions, m_selectedProtocolName);
  444. }
  445. }
  446. public virtual IList GetServerSupplementalData()
  447. {
  448. return null;
  449. }
  450. public abstract TlsCredentials GetCredentials();
  451. public virtual CertificateStatus GetCertificateStatus()
  452. {
  453. return null;
  454. }
  455. public virtual CertificateRequest GetCertificateRequest()
  456. {
  457. return null;
  458. }
  459. public virtual TlsPskIdentityManager GetPskIdentityManager()
  460. {
  461. return null;
  462. }
  463. public virtual TlsSrpLoginParameters GetSrpLoginParameters()
  464. {
  465. return null;
  466. }
  467. public virtual TlsDHConfig GetDHConfig()
  468. {
  469. int minimumFiniteFieldBits = TlsDHUtilities.GetMinimumFiniteFieldBits(m_selectedCipherSuite);
  470. int namedGroup = SelectDH(minimumFiniteFieldBits);
  471. return TlsDHUtilities.CreateNamedDHConfig(m_context, namedGroup);
  472. }
  473. public virtual TlsECConfig GetECDHConfig()
  474. {
  475. int minimumCurveBits = TlsEccUtilities.GetMinimumCurveBits(m_selectedCipherSuite);
  476. int namedGroup = SelectECDH(minimumCurveBits);
  477. return TlsEccUtilities.CreateNamedECConfig(m_context, namedGroup);
  478. }
  479. public virtual void ProcessClientSupplementalData(IList clientSupplementalData)
  480. {
  481. if (clientSupplementalData != null)
  482. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  483. }
  484. public virtual void NotifyClientCertificate(Certificate clientCertificate)
  485. {
  486. throw new TlsFatalAlert(AlertDescription.internal_error);
  487. }
  488. public virtual NewSessionTicket GetNewSessionTicket()
  489. {
  490. /*
  491. * RFC 5077 3.3. If the server determines that it does not want to include a ticket after it
  492. * has included the SessionTicket extension in the ServerHello, then it sends a zero-length
  493. * ticket in the NewSessionTicket handshake message.
  494. */
  495. return new NewSessionTicket(0L, TlsUtilities.EmptyBytes);
  496. }
  497. }
  498. }
  499. #pragma warning restore
  500. #endif