AbstractTlsClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 client.</summary>
  11. public abstract class AbstractTlsClient
  12. : AbstractTlsPeer, TlsClient
  13. {
  14. protected TlsClientContext m_context;
  15. protected ProtocolVersion[] m_protocolVersions;
  16. protected int[] m_cipherSuites;
  17. protected IList m_supportedGroups;
  18. protected IList m_supportedSignatureAlgorithms;
  19. protected IList m_supportedSignatureAlgorithmsCert;
  20. protected AbstractTlsClient(TlsCrypto crypto)
  21. : base(crypto)
  22. {
  23. }
  24. /// <exception cref="IOException"/>
  25. protected virtual bool AllowUnexpectedServerExtension(int extensionType, byte[] extensionData)
  26. {
  27. switch (extensionType)
  28. {
  29. case ExtensionType.supported_groups:
  30. /*
  31. * Exception added based on field reports that some servers do send this, although the
  32. * Supported Elliptic Curves Extension is clearly intended to be client-only. If
  33. * present, we still require that it is a valid EllipticCurveList.
  34. */
  35. TlsExtensionsUtilities.ReadSupportedGroupsExtension(extensionData);
  36. return true;
  37. case ExtensionType.ec_point_formats:
  38. /*
  39. * Exception added based on field reports that some servers send this even when they
  40. * didn't negotiate an ECC cipher suite. If present, we still require that it is a valid
  41. * ECPointFormatList.
  42. */
  43. TlsExtensionsUtilities.ReadSupportedPointFormatsExtension(extensionData);
  44. return true;
  45. default:
  46. return false;
  47. }
  48. }
  49. protected virtual IList GetNamedGroupRoles()
  50. {
  51. IList namedGroupRoles = TlsUtilities.GetNamedGroupRoles(GetCipherSuites());
  52. IList sigAlgs = m_supportedSignatureAlgorithms, sigAlgsCert = m_supportedSignatureAlgorithmsCert;
  53. if ((null == sigAlgs || TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgs, SignatureAlgorithm.ecdsa))
  54. || (null != sigAlgsCert
  55. && TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgsCert, SignatureAlgorithm.ecdsa)))
  56. {
  57. TlsUtilities.AddToSet(namedGroupRoles, NamedGroupRole.ecdsa);
  58. }
  59. return namedGroupRoles;
  60. }
  61. /// <exception cref="IOException"/>
  62. protected virtual void CheckForUnexpectedServerExtension(IDictionary serverExtensions, int extensionType)
  63. {
  64. byte[] extensionData = TlsUtilities.GetExtensionData(serverExtensions, extensionType);
  65. if (extensionData != null && !AllowUnexpectedServerExtension(extensionType, extensionData))
  66. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  67. }
  68. /// <exception cref="IOException"/>
  69. public virtual TlsPskIdentity GetPskIdentity()
  70. {
  71. return null;
  72. }
  73. /// <exception cref="IOException"/>
  74. public virtual TlsSrpIdentity GetSrpIdentity()
  75. {
  76. return null;
  77. }
  78. public virtual TlsDHGroupVerifier GetDHGroupVerifier()
  79. {
  80. return new DefaultTlsDHGroupVerifier();
  81. }
  82. public virtual TlsSrpConfigVerifier GetSrpConfigVerifier()
  83. {
  84. return new DefaultTlsSrpConfigVerifier();
  85. }
  86. protected virtual IList GetCertificateAuthorities()
  87. {
  88. return null;
  89. }
  90. protected virtual IList GetProtocolNames()
  91. {
  92. return null;
  93. }
  94. protected virtual CertificateStatusRequest GetCertificateStatusRequest()
  95. {
  96. return new CertificateStatusRequest(CertificateStatusType.ocsp, new OcspStatusRequest(null, null));
  97. }
  98. /// <returns>an <see cref="IList"/> of <see cref="CertificateStatusRequestItemV2"/> (or null).</returns>
  99. protected virtual IList GetMultiCertStatusRequest()
  100. {
  101. return null;
  102. }
  103. protected virtual IList GetSniServerNames()
  104. {
  105. return null;
  106. }
  107. /// <summary>The default <see cref="GetClientExtensions"/> implementation calls this to determine which named
  108. /// groups to include in the supported_groups extension for the ClientHello.</summary>
  109. /// <param name="namedGroupRoles">The <see cref="NamedGroupRole">named group roles</see> for which there should
  110. /// be at least one supported group. By default this is inferred from the offered cipher suites and signature
  111. /// algorithms.</param>
  112. /// <returns>an <see cref="IList"/> of <see cref="Int32"/>. See <see cref="NamedGroup"/> for group constants.
  113. /// </returns>
  114. protected virtual IList GetSupportedGroups(IList namedGroupRoles)
  115. {
  116. TlsCrypto crypto = Crypto;
  117. IList supportedGroups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  118. if (namedGroupRoles.Contains(NamedGroupRole.ecdh))
  119. {
  120. TlsUtilities.AddIfSupported(supportedGroups, crypto,
  121. new int[]{ NamedGroup.x25519, NamedGroup.x448 });
  122. }
  123. if (namedGroupRoles.Contains(NamedGroupRole.ecdh) ||
  124. namedGroupRoles.Contains(NamedGroupRole.ecdsa))
  125. {
  126. TlsUtilities.AddIfSupported(supportedGroups, crypto,
  127. new int[]{ NamedGroup.secp256r1, NamedGroup.secp384r1 });
  128. }
  129. if (namedGroupRoles.Contains(NamedGroupRole.dh))
  130. {
  131. TlsUtilities.AddIfSupported(supportedGroups, crypto,
  132. new int[]{ NamedGroup.ffdhe2048, NamedGroup.ffdhe3072, NamedGroup.ffdhe4096 });
  133. }
  134. return supportedGroups;
  135. }
  136. protected virtual IList GetSupportedSignatureAlgorithms()
  137. {
  138. return TlsUtilities.GetDefaultSupportedSignatureAlgorithms(m_context);
  139. }
  140. protected virtual IList GetSupportedSignatureAlgorithmsCert()
  141. {
  142. return null;
  143. }
  144. protected virtual IList GetTrustedCAIndication()
  145. {
  146. return null;
  147. }
  148. public virtual void Init(TlsClientContext context)
  149. {
  150. this.m_context = context;
  151. this.m_protocolVersions = GetSupportedVersions();
  152. this.m_cipherSuites = GetSupportedCipherSuites();
  153. }
  154. public override ProtocolVersion[] GetProtocolVersions()
  155. {
  156. return m_protocolVersions;
  157. }
  158. public override int[] GetCipherSuites()
  159. {
  160. return m_cipherSuites;
  161. }
  162. /// <exception cref="IOException"/>
  163. public override void NotifyHandshakeBeginning()
  164. {
  165. base.NotifyHandshakeBeginning();
  166. this.m_supportedGroups = null;
  167. this.m_supportedSignatureAlgorithms = null;
  168. this.m_supportedSignatureAlgorithmsCert = null;
  169. }
  170. public virtual TlsSession GetSessionToResume()
  171. {
  172. return null;
  173. }
  174. public virtual IList GetExternalPsks()
  175. {
  176. return null;
  177. }
  178. public virtual bool IsFallback()
  179. {
  180. /*
  181. * RFC 7507 4. The TLS_FALLBACK_SCSV cipher suite value is meant for use by clients that
  182. * repeat a connection attempt with a downgraded protocol (perform a "fallback retry") in
  183. * order to work around interoperability problems with legacy servers.
  184. */
  185. return false;
  186. }
  187. /// <exception cref="IOException"/>
  188. public virtual IDictionary GetClientExtensions()
  189. {
  190. IDictionary clientExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  191. bool offeringTlsV13Plus = false;
  192. bool offeringPreTlsV13 = false;
  193. {
  194. ProtocolVersion[] supportedVersions = GetProtocolVersions();
  195. for (int i = 0; i < supportedVersions.Length; ++i)
  196. {
  197. if (TlsUtilities.IsTlsV13(supportedVersions[i]))
  198. {
  199. offeringTlsV13Plus = true;
  200. }
  201. else
  202. {
  203. offeringPreTlsV13 = true;
  204. }
  205. }
  206. }
  207. IList protocolNames = GetProtocolNames();
  208. if (protocolNames != null)
  209. {
  210. TlsExtensionsUtilities.AddAlpnExtensionClient(clientExtensions, protocolNames);
  211. }
  212. IList sniServerNames = GetSniServerNames();
  213. if (sniServerNames != null)
  214. {
  215. TlsExtensionsUtilities.AddServerNameExtensionClient(clientExtensions, sniServerNames);
  216. }
  217. CertificateStatusRequest statusRequest = GetCertificateStatusRequest();
  218. if (statusRequest != null)
  219. {
  220. TlsExtensionsUtilities.AddStatusRequestExtension(clientExtensions, statusRequest);
  221. }
  222. if (offeringTlsV13Plus)
  223. {
  224. IList certificateAuthorities = GetCertificateAuthorities();
  225. if (certificateAuthorities != null)
  226. {
  227. TlsExtensionsUtilities.AddCertificateAuthoritiesExtension(clientExtensions, certificateAuthorities);
  228. }
  229. }
  230. if (offeringPreTlsV13)
  231. {
  232. // TODO Shouldn't add if no offered cipher suite uses a block cipher?
  233. TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions);
  234. IList statusRequestV2 = GetMultiCertStatusRequest();
  235. if (statusRequestV2 != null)
  236. {
  237. TlsExtensionsUtilities.AddStatusRequestV2Extension(clientExtensions, statusRequestV2);
  238. }
  239. IList trustedCAKeys = GetTrustedCAIndication();
  240. if (trustedCAKeys != null)
  241. {
  242. TlsExtensionsUtilities.AddTrustedCAKeysExtensionClient(clientExtensions, trustedCAKeys);
  243. }
  244. }
  245. ProtocolVersion clientVersion = m_context.ClientVersion;
  246. /*
  247. * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior to 1.2.
  248. * Clients MUST NOT offer it if they are offering prior versions.
  249. */
  250. if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion))
  251. {
  252. IList supportedSigAlgs = GetSupportedSignatureAlgorithms();
  253. if (null != supportedSigAlgs && supportedSigAlgs.Count > 0)
  254. {
  255. this.m_supportedSignatureAlgorithms = supportedSigAlgs;
  256. TlsExtensionsUtilities.AddSignatureAlgorithmsExtension(clientExtensions, supportedSigAlgs);
  257. }
  258. IList supportedSigAlgsCert = GetSupportedSignatureAlgorithmsCert();
  259. if (null != supportedSigAlgsCert && supportedSigAlgsCert.Count > 0)
  260. {
  261. this.m_supportedSignatureAlgorithmsCert = supportedSigAlgsCert;
  262. TlsExtensionsUtilities.AddSignatureAlgorithmsCertExtension(clientExtensions, supportedSigAlgsCert);
  263. }
  264. }
  265. IList namedGroupRoles = GetNamedGroupRoles();
  266. IList supportedGroups = GetSupportedGroups(namedGroupRoles);
  267. if (supportedGroups != null && supportedGroups.Count > 0)
  268. {
  269. this.m_supportedGroups = supportedGroups;
  270. TlsExtensionsUtilities.AddSupportedGroupsExtension(clientExtensions, supportedGroups);
  271. }
  272. if (offeringPreTlsV13)
  273. {
  274. if (namedGroupRoles.Contains(NamedGroupRole.ecdh) ||
  275. namedGroupRoles.Contains(NamedGroupRole.ecdsa))
  276. {
  277. TlsExtensionsUtilities.AddSupportedPointFormatsExtension(clientExtensions,
  278. new short[]{ ECPointFormat.uncompressed });
  279. }
  280. }
  281. return clientExtensions;
  282. }
  283. public virtual IList GetEarlyKeyShareGroups()
  284. {
  285. /*
  286. * RFC 8446 4.2.8. Each KeyShareEntry value MUST correspond to a group offered in the
  287. * "supported_groups" extension and MUST appear in the same order. However, the values MAY
  288. * be a non-contiguous subset of the "supported_groups" extension and MAY omit the most
  289. * preferred groups.
  290. */
  291. if (null == m_supportedGroups || m_supportedGroups.Count < 1)
  292. return null;
  293. if (m_supportedGroups.Contains(NamedGroup.x25519))
  294. return TlsUtilities.VectorOfOne(NamedGroup.x25519);
  295. if (m_supportedGroups.Contains(NamedGroup.secp256r1))
  296. return TlsUtilities.VectorOfOne(NamedGroup.secp256r1);
  297. return TlsUtilities.VectorOfOne(m_supportedGroups[0]);
  298. }
  299. /// <exception cref="IOException"/>
  300. public virtual void NotifyServerVersion(ProtocolVersion serverVersion)
  301. {
  302. }
  303. public virtual void NotifySessionToResume(TlsSession session)
  304. {
  305. }
  306. public virtual void NotifySessionID(byte[] sessionID)
  307. {
  308. }
  309. public virtual void NotifySelectedCipherSuite(int selectedCipherSuite)
  310. {
  311. }
  312. /// <exception cref="IOException"/>
  313. public virtual void NotifySelectedPsk(TlsPsk selectedPsk)
  314. {
  315. }
  316. /// <exception cref="IOException"/>
  317. public virtual void ProcessServerExtensions(IDictionary serverExtensions)
  318. {
  319. if (null == serverExtensions)
  320. return;
  321. SecurityParameters securityParameters = m_context.SecurityParameters;
  322. bool isTlsV13 = TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion);
  323. if (isTlsV13)
  324. {
  325. /*
  326. * NOTE: From TLS 1.3 the protocol classes are strict about what extensions can appear.
  327. */
  328. }
  329. else
  330. {
  331. /*
  332. * RFC 5246 7.4.1.4.1. Servers MUST NOT send this extension.
  333. */
  334. CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.signature_algorithms);
  335. CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.signature_algorithms_cert);
  336. CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.supported_groups);
  337. int selectedCipherSuite = securityParameters.CipherSuite;
  338. if (TlsEccUtilities.IsEccCipherSuite(selectedCipherSuite))
  339. {
  340. // We only support uncompressed format, this is just to validate the extension, if present.
  341. TlsExtensionsUtilities.GetSupportedPointFormatsExtension(serverExtensions);
  342. }
  343. else
  344. {
  345. CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.ec_point_formats);
  346. }
  347. /*
  348. * RFC 7685 3. The server MUST NOT echo the extension.
  349. */
  350. CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.padding);
  351. }
  352. }
  353. /// <exception cref="IOException"/>
  354. public virtual void ProcessServerSupplementalData(IList serverSupplementalData)
  355. {
  356. if (serverSupplementalData != null)
  357. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  358. }
  359. public abstract TlsAuthentication GetAuthentication();
  360. /// <exception cref="IOException"/>
  361. public virtual IList GetClientSupplementalData()
  362. {
  363. return null;
  364. }
  365. /// <exception cref="IOException"/>
  366. public virtual void NotifyNewSessionTicket(NewSessionTicket newSessionTicket)
  367. {
  368. }
  369. }
  370. }
  371. #pragma warning restore
  372. #endif