AbstractTlsServer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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.Utilities;
  7. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  8. {
  9. public abstract class AbstractTlsServer
  10. : AbstractTlsPeer, TlsServer
  11. {
  12. protected TlsCipherFactory mCipherFactory;
  13. protected TlsServerContext mContext;
  14. protected ProtocolVersion mClientVersion;
  15. protected int[] mOfferedCipherSuites;
  16. protected byte[] mOfferedCompressionMethods;
  17. protected IDictionary mClientExtensions;
  18. protected bool mEncryptThenMacOffered;
  19. protected short mMaxFragmentLengthOffered;
  20. protected bool mTruncatedHMacOffered;
  21. protected IList mSupportedSignatureAlgorithms;
  22. protected bool mEccCipherSuitesOffered;
  23. protected int[] mNamedCurves;
  24. protected byte[] mClientECPointFormats, mServerECPointFormats;
  25. protected ProtocolVersion mServerVersion;
  26. protected int mSelectedCipherSuite;
  27. protected byte mSelectedCompressionMethod;
  28. protected IDictionary mServerExtensions;
  29. public AbstractTlsServer()
  30. : this(new DefaultTlsCipherFactory())
  31. {
  32. }
  33. public AbstractTlsServer(TlsCipherFactory cipherFactory)
  34. {
  35. this.mCipherFactory = cipherFactory;
  36. }
  37. protected virtual bool AllowEncryptThenMac
  38. {
  39. get { return true; }
  40. }
  41. protected virtual bool AllowTruncatedHMac
  42. {
  43. get { return false; }
  44. }
  45. protected virtual IDictionary CheckServerExtensions()
  46. {
  47. return this.mServerExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(this.mServerExtensions);
  48. }
  49. protected abstract int[] GetCipherSuites();
  50. protected byte[] GetCompressionMethods()
  51. {
  52. return new byte[] { CompressionMethod.cls_null };
  53. }
  54. protected virtual ProtocolVersion MaximumVersion
  55. {
  56. get { return ProtocolVersion.TLSv11; }
  57. }
  58. protected virtual ProtocolVersion MinimumVersion
  59. {
  60. get { return ProtocolVersion.TLSv10; }
  61. }
  62. protected virtual bool SupportsClientEccCapabilities(int[] namedCurves, byte[] ecPointFormats)
  63. {
  64. // NOTE: BC supports all the current set of point formats so we don't check them here
  65. if (namedCurves == null)
  66. {
  67. /*
  68. * RFC 4492 4. A client that proposes ECC cipher suites may choose not to include these
  69. * extensions. In this case, the server is free to choose any one of the elliptic curves
  70. * or point formats [...].
  71. */
  72. return TlsEccUtilities.HasAnySupportedNamedCurves();
  73. }
  74. for (int i = 0; i < namedCurves.Length; ++i)
  75. {
  76. int namedCurve = namedCurves[i];
  77. if (NamedCurve.IsValid(namedCurve)
  78. && (!NamedCurve.RefersToASpecificNamedCurve(namedCurve) || TlsEccUtilities.IsSupportedNamedCurve(namedCurve)))
  79. {
  80. return true;
  81. }
  82. }
  83. return false;
  84. }
  85. public virtual void Init(TlsServerContext context)
  86. {
  87. this.mContext = context;
  88. }
  89. public virtual void NotifyClientVersion(ProtocolVersion clientVersion)
  90. {
  91. this.mClientVersion = clientVersion;
  92. }
  93. public virtual void NotifyFallback(bool isFallback)
  94. {
  95. /*
  96. * RFC 7507 3. If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest
  97. * protocol version supported by the server is higher than the version indicated in
  98. * ClientHello.client_version, the server MUST respond with a fatal inappropriate_fallback
  99. * alert [..].
  100. */
  101. if (isFallback && MaximumVersion.IsLaterVersionOf(mClientVersion))
  102. throw new TlsFatalAlert(AlertDescription.inappropriate_fallback);
  103. }
  104. public virtual void NotifyOfferedCipherSuites(int[] offeredCipherSuites)
  105. {
  106. this.mOfferedCipherSuites = offeredCipherSuites;
  107. this.mEccCipherSuitesOffered = TlsEccUtilities.ContainsEccCipherSuites(this.mOfferedCipherSuites);
  108. }
  109. public virtual void NotifyOfferedCompressionMethods(byte[] offeredCompressionMethods)
  110. {
  111. this.mOfferedCompressionMethods = offeredCompressionMethods;
  112. }
  113. public virtual void ProcessClientExtensions(IDictionary clientExtensions)
  114. {
  115. this.mClientExtensions = clientExtensions;
  116. if (clientExtensions != null)
  117. {
  118. this.mEncryptThenMacOffered = TlsExtensionsUtilities.HasEncryptThenMacExtension(clientExtensions);
  119. this.mMaxFragmentLengthOffered = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(clientExtensions);
  120. if (mMaxFragmentLengthOffered >= 0 && !MaxFragmentLength.IsValid((byte)mMaxFragmentLengthOffered))
  121. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  122. this.mTruncatedHMacOffered = TlsExtensionsUtilities.HasTruncatedHMacExtension(clientExtensions);
  123. this.mSupportedSignatureAlgorithms = TlsUtilities.GetSignatureAlgorithmsExtension(clientExtensions);
  124. if (this.mSupportedSignatureAlgorithms != null)
  125. {
  126. /*
  127. * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior
  128. * to 1.2. Clients MUST NOT offer it if they are offering prior versions.
  129. */
  130. if (!TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mClientVersion))
  131. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  132. }
  133. this.mNamedCurves = TlsEccUtilities.GetSupportedEllipticCurvesExtension(clientExtensions);
  134. this.mClientECPointFormats = TlsEccUtilities.GetSupportedPointFormatsExtension(clientExtensions);
  135. }
  136. /*
  137. * RFC 4429 4. The client MUST NOT include these extensions in the ClientHello message if it
  138. * does not propose any ECC cipher suites.
  139. *
  140. * NOTE: This was overly strict as there may be ECC cipher suites that we don't recognize.
  141. * Also, draft-ietf-tls-negotiated-ff-dhe will be overloading the 'elliptic_curves'
  142. * extension to explicitly allow FFDHE (i.e. non-ECC) groups.
  143. */
  144. //if (!this.mEccCipherSuitesOffered && (this.mNamedCurves != null || this.mClientECPointFormats != null))
  145. // throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  146. }
  147. public virtual ProtocolVersion GetServerVersion()
  148. {
  149. if (MinimumVersion.IsEqualOrEarlierVersionOf(mClientVersion))
  150. {
  151. ProtocolVersion maximumVersion = MaximumVersion;
  152. if (mClientVersion.IsEqualOrEarlierVersionOf(maximumVersion))
  153. {
  154. return mServerVersion = mClientVersion;
  155. }
  156. if (mClientVersion.IsLaterVersionOf(maximumVersion))
  157. {
  158. return mServerVersion = maximumVersion;
  159. }
  160. }
  161. throw new TlsFatalAlert(AlertDescription.protocol_version);
  162. }
  163. public virtual int GetSelectedCipherSuite()
  164. {
  165. /*
  166. * RFC 5246 7.4.3. In order to negotiate correctly, the server MUST check any candidate
  167. * cipher suites against the "signature_algorithms" extension before selecting them. This is
  168. * somewhat inelegant but is a compromise designed to minimize changes to the original
  169. * cipher suite design.
  170. */
  171. IList sigAlgs = TlsUtilities.GetUsableSignatureAlgorithms(this.mSupportedSignatureAlgorithms);
  172. /*
  173. * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these
  174. * extensions MUST use the client's enumerated capabilities to guide its selection of an
  175. * appropriate cipher suite. One of the proposed ECC cipher suites must be negotiated only
  176. * if the server can successfully complete the handshake while using the curves and point
  177. * formats supported by the client [...].
  178. */
  179. bool eccCipherSuitesEnabled = SupportsClientEccCapabilities(this.mNamedCurves, this.mClientECPointFormats);
  180. int[] cipherSuites = GetCipherSuites();
  181. for (int i = 0; i < cipherSuites.Length; ++i)
  182. {
  183. int cipherSuite = cipherSuites[i];
  184. if (Arrays.Contains(this.mOfferedCipherSuites, cipherSuite)
  185. && (eccCipherSuitesEnabled || !TlsEccUtilities.IsEccCipherSuite(cipherSuite))
  186. && TlsUtilities.IsValidCipherSuiteForVersion(cipherSuite, mServerVersion)
  187. && TlsUtilities.IsValidCipherSuiteForSignatureAlgorithms(cipherSuite, sigAlgs))
  188. {
  189. return this.mSelectedCipherSuite = cipherSuite;
  190. }
  191. }
  192. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  193. }
  194. public virtual byte GetSelectedCompressionMethod()
  195. {
  196. byte[] compressionMethods = GetCompressionMethods();
  197. for (int i = 0; i < compressionMethods.Length; ++i)
  198. {
  199. if (Arrays.Contains(mOfferedCompressionMethods, compressionMethods[i]))
  200. {
  201. return this.mSelectedCompressionMethod = compressionMethods[i];
  202. }
  203. }
  204. throw new TlsFatalAlert(AlertDescription.handshake_failure);
  205. }
  206. // IDictionary is (Int32 -> byte[])
  207. public virtual IDictionary GetServerExtensions()
  208. {
  209. if (this.mEncryptThenMacOffered && AllowEncryptThenMac)
  210. {
  211. /*
  212. * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
  213. * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
  214. * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
  215. * client.
  216. */
  217. if (TlsUtilities.IsBlockCipherSuite(this.mSelectedCipherSuite))
  218. {
  219. TlsExtensionsUtilities.AddEncryptThenMacExtension(CheckServerExtensions());
  220. }
  221. }
  222. if (this.mMaxFragmentLengthOffered >= 0
  223. && TlsUtilities.IsValidUint8(mMaxFragmentLengthOffered)
  224. && MaxFragmentLength.IsValid((byte)mMaxFragmentLengthOffered))
  225. {
  226. TlsExtensionsUtilities.AddMaxFragmentLengthExtension(CheckServerExtensions(), (byte)mMaxFragmentLengthOffered);
  227. }
  228. if (this.mTruncatedHMacOffered && AllowTruncatedHMac)
  229. {
  230. TlsExtensionsUtilities.AddTruncatedHMacExtension(CheckServerExtensions());
  231. }
  232. if (this.mClientECPointFormats != null && TlsEccUtilities.IsEccCipherSuite(this.mSelectedCipherSuite))
  233. {
  234. /*
  235. * RFC 4492 5.2. A server that selects an ECC cipher suite in response to a ClientHello
  236. * message including a Supported Point Formats Extension appends this extension (along
  237. * with others) to its ServerHello message, enumerating the point formats it can parse.
  238. */
  239. this.mServerECPointFormats = new byte[]{ ECPointFormat.uncompressed,
  240. ECPointFormat.ansiX962_compressed_prime, ECPointFormat.ansiX962_compressed_char2, };
  241. TlsEccUtilities.AddSupportedPointFormatsExtension(CheckServerExtensions(), mServerECPointFormats);
  242. }
  243. return mServerExtensions;
  244. }
  245. public virtual IList GetServerSupplementalData()
  246. {
  247. return null;
  248. }
  249. public abstract TlsCredentials GetCredentials();
  250. public virtual CertificateStatus GetCertificateStatus()
  251. {
  252. return null;
  253. }
  254. public abstract TlsKeyExchange GetKeyExchange();
  255. public virtual CertificateRequest GetCertificateRequest()
  256. {
  257. return null;
  258. }
  259. public virtual void ProcessClientSupplementalData(IList clientSupplementalData)
  260. {
  261. if (clientSupplementalData != null)
  262. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  263. }
  264. public virtual void NotifyClientCertificate(Certificate clientCertificate)
  265. {
  266. throw new TlsFatalAlert(AlertDescription.internal_error);
  267. }
  268. public override TlsCompression GetCompression()
  269. {
  270. switch (mSelectedCompressionMethod)
  271. {
  272. case CompressionMethod.cls_null:
  273. return new TlsNullCompression();
  274. default:
  275. /*
  276. * Note: internal error here; we selected the compression method, so if we now can't
  277. * produce an implementation, we shouldn't have chosen it!
  278. */
  279. throw new TlsFatalAlert(AlertDescription.internal_error);
  280. }
  281. }
  282. public override TlsCipher GetCipher()
  283. {
  284. int encryptionAlgorithm = TlsUtilities.GetEncryptionAlgorithm(mSelectedCipherSuite);
  285. int macAlgorithm = TlsUtilities.GetMacAlgorithm(mSelectedCipherSuite);
  286. return mCipherFactory.CreateCipher(mContext, encryptionAlgorithm, macAlgorithm);
  287. }
  288. public virtual NewSessionTicket GetNewSessionTicket()
  289. {
  290. /*
  291. * RFC 5077 3.3. If the server determines that it does not want to include a ticket after it
  292. * has included the SessionTicket extension in the ServerHello, then it sends a zero-length
  293. * ticket in the NewSessionTicket handshake message.
  294. */
  295. return new NewSessionTicket(0L, TlsUtilities.EmptyBytes);
  296. }
  297. }
  298. }
  299. #pragma warning restore
  300. #endif