AbstractTlsServer.cs 14 KB

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