clsSSLCertMonitor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Security.Cryptography.X509Certificates;
  6. using System.Threading.Tasks;
  7. using DiscordBot;
  8. namespace TFABot
  9. {
  10. public class clsSSLCertMonitor
  11. {
  12. static public DateTime? LastTest = null;
  13. public clsSSLCertMonitor()
  14. {
  15. }
  16. internal static void HeartbeatCheck()
  17. {
  18. if (!LastTest.HasValue || (DateTime.UtcNow - LastTest.Value).Hours >= 24)
  19. {
  20. Console.WriteLine("clsSSLCertMonitor: HeartbeatCheck");
  21. LastTest = DateTime.UtcNow;
  22. Task.Run(() =>
  23. {
  24. foreach (var ssl in Program.SSLCertsList.Values)
  25. {
  26. CheckSSL(ssl);
  27. }
  28. });
  29. }
  30. }
  31. private static async void CheckSSL(clsSSLCerts ssl)
  32. {
  33. try
  34. {
  35. var url = ssl.URL.Trim();
  36. if (!url.StartsWith("https://")) url = $"https://{url}";
  37. var uri = new Uri(url);
  38. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  39. HttpWebResponse response;
  40. try
  41. {
  42. response = (HttpWebResponse)request.GetResponse();
  43. response.Close();
  44. }
  45. catch { }
  46. var cert = request.ServicePoint.Certificate;
  47. var cert2 = new X509Certificate2(cert);
  48. ssl.CertExpiry = DateTime.Parse(cert2.GetExpirationDateString());
  49. var days = (ssl.CertExpiry - DateTime.UtcNow).Days;
  50. if (days <= 7) SendMessage(ssl, $"{ssl.URL} certificate expires in {days} days");
  51. }
  52. catch (Exception ex)
  53. {
  54. SendMessage(ssl, $"{ssl.URL} certificate read error");
  55. }
  56. }
  57. private static void SendMessage(clsSSLCerts ssl, string messageText)
  58. {
  59. foreach (var user in ssl.Contacts.Split(';'))
  60. {
  61. if (user.StartsWith("@"))
  62. {
  63. var hashsplit = user.Split('#');
  64. if (hashsplit.Length == 2)
  65. {
  66. try
  67. {
  68. var discordUser = clsBotClient.Instance.Our_BotAlert.Guild.Members.FirstOrDefault(x => x.Discriminator == hashsplit[1]);
  69. discordUser.SendMessageAsync(messageText);
  70. }
  71. catch (Exception ex)
  72. {
  73. Console.WriteLine($"Error {ex.Message}");
  74. }
  75. }
  76. }
  77. else if (user.Contains("@"))
  78. {
  79. clsEmail.SendEmail(user,"SSL Certificate",messageText);
  80. }
  81. }
  82. }
  83. }
  84. }