ServerSslHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.IO;
  3. using System.Net.Security;
  4. using System.Net.Sockets;
  5. using System.Security.Authentication;
  6. using System.Security.Cryptography.X509Certificates;
  7. namespace Mirror.SimpleWeb
  8. {
  9. public struct SslConfig
  10. {
  11. public readonly bool enabled;
  12. public readonly string certPath;
  13. public readonly string certPassword;
  14. public readonly SslProtocols sslProtocols;
  15. public SslConfig(bool enabled, string certPath, string certPassword, SslProtocols sslProtocols)
  16. {
  17. this.enabled = enabled;
  18. this.certPath = certPath;
  19. this.certPassword = certPassword;
  20. this.sslProtocols = sslProtocols;
  21. }
  22. }
  23. internal class ServerSslHelper
  24. {
  25. readonly SslConfig config;
  26. readonly X509Certificate2 certificate;
  27. public ServerSslHelper(SslConfig sslConfig)
  28. {
  29. config = sslConfig;
  30. if (config.enabled)
  31. certificate = new X509Certificate2(config.certPath, config.certPassword);
  32. }
  33. internal bool TryCreateStream(Connection conn)
  34. {
  35. NetworkStream stream = conn.client.GetStream();
  36. if (config.enabled)
  37. {
  38. try
  39. {
  40. conn.stream = CreateStream(stream);
  41. return true;
  42. }
  43. catch (Exception e)
  44. {
  45. Log.Error($"Create SSLStream Failed: {e}", false);
  46. return false;
  47. }
  48. }
  49. else
  50. {
  51. conn.stream = stream;
  52. return true;
  53. }
  54. }
  55. Stream CreateStream(NetworkStream stream)
  56. {
  57. SslStream sslStream = new SslStream(stream, true, acceptClient);
  58. sslStream.AuthenticateAsServer(certificate, false, config.sslProtocols, false);
  59. return sslStream;
  60. }
  61. bool acceptClient(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  62. {
  63. // always accept client
  64. return true;
  65. }
  66. }
  67. }