ClientSslHelper.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.IO;
  3. using System.Net.Security;
  4. using System.Net.Sockets;
  5. using System.Security.Cryptography.X509Certificates;
  6. namespace Mirror.SimpleWeb
  7. {
  8. internal class ClientSslHelper
  9. {
  10. internal bool TryCreateStream(Connection conn, Uri uri)
  11. {
  12. NetworkStream stream = conn.client.GetStream();
  13. if (uri.Scheme != "wss")
  14. {
  15. conn.stream = stream;
  16. return true;
  17. }
  18. try
  19. {
  20. conn.stream = CreateStream(stream, uri);
  21. return true;
  22. }
  23. catch (Exception e)
  24. {
  25. Log.Error($"Create SSLStream Failed: {e}", false);
  26. return false;
  27. }
  28. }
  29. Stream CreateStream(NetworkStream stream, Uri uri)
  30. {
  31. SslStream sslStream = new SslStream(stream, true, ValidateServerCertificate);
  32. sslStream.AuthenticateAsClient(uri.Host);
  33. return sslStream;
  34. }
  35. static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  36. {
  37. // Do not allow this client to communicate with unauthenticated servers.
  38. // only accept if no errors
  39. return sslPolicyErrors == SslPolicyErrors.None;
  40. }
  41. }
  42. }