The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Program.cs 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Mail;
  9. using System.Reflection;
  10. using System.Text;
  11. using Teknik.Areas.Transparency.Models;
  12. using Teknik.Areas.Upload.Models;
  13. using Teknik.Areas.Users.Models;
  14. using Teknik.Areas.Users.Utility;
  15. using Teknik.Configuration;
  16. using Teknik.Helpers;
  17. using Teknik.Models;
  18. namespace ServerMaint
  19. {
  20. public class Program
  21. {
  22. private static string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
  23. private static string virusFile = Path.Combine(currentPath, "virusLogs.txt");
  24. private static string errorFile = Path.Combine(currentPath, "errorLogs.txt");
  25. private static string configPath = currentPath;
  26. private const string TAKEDOWN_REPORTER = "Teknik Automated System";
  27. public static event Action<string> OutputEvent;
  28. public static int Main(string[] args)
  29. {
  30. try
  31. {
  32. ArgumentOptions options = new ArgumentOptions();
  33. var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out);
  34. if (parser.ParseArguments(args, options))
  35. {
  36. if (!string.IsNullOrEmpty(options.Config))
  37. configPath = options.Config;
  38. if (Directory.Exists(configPath))
  39. {
  40. Config config = Config.Load(configPath);
  41. TeknikEntities db = new TeknikEntities();
  42. Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
  43. // Scan all the uploads for viruses, and remove the bad ones
  44. if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
  45. {
  46. ScanUploads(config, db);
  47. }
  48. // Cleans all inactive users
  49. if (options.CleanUsers)
  50. {
  51. CleanUsers(config, db, options.DaysBeforeDeletion);
  52. }
  53. // Cleans the email for unused accounts
  54. if (options.CleanEmails)
  55. {
  56. CleanEmail(config, db);
  57. }
  58. // Cleans all the git accounts that are unused
  59. if (options.CleanGit)
  60. {
  61. CleanGit(config, db);
  62. }
  63. // Generates a file for all of the user's last seen dates
  64. if (options.GenerateLastSeen)
  65. {
  66. GenerateLastSeen(config, db, options.LastSeenFile);
  67. }
  68. Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));
  69. return 0;
  70. }
  71. else
  72. {
  73. string msg = string.Format("[{0}] Config File does not exist.", DateTime.Now);
  74. File.AppendAllLines(errorFile, new List<string> { msg });
  75. Output(msg);
  76. }
  77. }
  78. else
  79. {
  80. Output(options.GetUsage());
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.GetFullMessage(true));
  86. File.AppendAllLines(errorFile, new List<string> { msg });
  87. Output(msg);
  88. }
  89. return -1;
  90. }
  91. public static void ScanUploads(Config config, TeknikEntities db)
  92. {
  93. Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now));
  94. List<Upload> uploads = db.Uploads.ToList();
  95. // Initialize ClamAV
  96. ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
  97. clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;
  98. int totalCount = uploads.Count();
  99. int totalScans = 0;
  100. int totalClean = 0;
  101. int totalViruses = 0;
  102. foreach (Upload upload in uploads)
  103. {
  104. totalScans++;
  105. string subDir = upload.FileName[0].ToString();
  106. string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  107. if (File.Exists(filePath))
  108. {
  109. // Read in the file
  110. byte[] data = File.ReadAllBytes(filePath);
  111. // If the IV is set, and Key is set, then decrypt it
  112. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  113. {
  114. // Decrypt the data
  115. data = AES.Decrypt(data, upload.Key, upload.IV);
  116. }
  117. // We have the data, let's scan it
  118. ClamScanResult scanResult = clam.SendAndScanFile(data);
  119. switch (scanResult.Result)
  120. {
  121. case ClamScanResults.Clean:
  122. totalClean++;
  123. string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, totalScans, totalCount, upload.Url, upload.FileName);
  124. Output(cleanMsg);
  125. break;
  126. case ClamScanResults.VirusDetected:
  127. totalViruses++;
  128. string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
  129. File.AppendAllLines(virusFile, new List<string> { msg });
  130. Output(msg);
  131. // Delete from the DB
  132. db.Uploads.Remove(upload);
  133. db.SaveChanges();
  134. // Delete the File
  135. if (File.Exists(filePath))
  136. {
  137. File.Delete(filePath);
  138. }
  139. break;
  140. case ClamScanResults.Error:
  141. string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
  142. File.AppendAllLines(errorFile, new List<string> { errorMsg });
  143. Output(errorMsg);
  144. break;
  145. case ClamScanResults.Unknown:
  146. string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
  147. File.AppendAllLines(errorFile, new List<string> { unkMsg });
  148. Output(unkMsg);
  149. break;
  150. }
  151. }
  152. }
  153. if (totalViruses > 0)
  154. {
  155. // Add to transparency report if any were found
  156. Takedown report = db.Takedowns.Create();
  157. report.Requester = TAKEDOWN_REPORTER;
  158. report.RequesterContact = config.SupportEmail;
  159. report.DateRequested = DateTime.Now;
  160. report.Reason = "Malware Found";
  161. report.ActionTaken = string.Format("{0} Uploads removed", totalViruses);
  162. report.DateActionTaken = DateTime.Now;
  163. db.Takedowns.Add(report);
  164. db.SaveChanges();
  165. }
  166. Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
  167. }
  168. public static void CleanUsers(Config config, TeknikEntities db, int maxDays)
  169. {
  170. int totalUsers = 0;
  171. Output(string.Format("[{0}] Started Cleaning of Inactive Users.", DateTime.Now));
  172. List<User> curUsers = db.Users.ToList();
  173. foreach (User user in curUsers)
  174. {
  175. // If the username isn't valid, don't clean it (Reserved, not formatted correctly, etc)
  176. if (!UserHelper.ValidUsername(db, config, user.Username))
  177. {
  178. continue;
  179. }
  180. #region Inactivity Cleaning
  181. DateTime lastActivity = UserHelper.GetLastActivity(db, config, user);
  182. TimeSpan inactiveTime = DateTime.Now.Subtract(lastActivity);
  183. // If older than max days, check their current usage
  184. if (inactiveTime >= new TimeSpan(maxDays, 0, 0, 0, 0))
  185. {
  186. // Check the user's usage of the service.
  187. bool noData = true;
  188. // Any blog comments?
  189. var blogCom = db.BlogComments.Include("Users").Where(c => c.UserId == user.UserId);
  190. noData &= !(blogCom != null && blogCom.Any());
  191. // Any blog posts?
  192. var blogPosts = db.BlogPosts.Include("Blog").Include("Blog.Users").Where(p => p.Blog.UserId == user.UserId);
  193. noData &= !(blogPosts != null && blogPosts.Any());
  194. // Any podcast comments?
  195. var podCom = db.PodcastComments.Include("Users").Where(p => p.UserId == user.UserId);
  196. noData &= !(podCom != null && podCom.Any());
  197. // Any email?
  198. if (config.EmailConfig.Enabled)
  199. {
  200. var app = new hMailServer.Application();
  201. app.Connect();
  202. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  203. try
  204. {
  205. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  206. var account = domain.Accounts.ItemByAddress[UserHelper.GetUserEmailAddress(config, user.Username)];
  207. noData &= ((account.Messages.Count == 0) && ((int)account.Size == 0));
  208. }
  209. catch { }
  210. }
  211. // Any git repos?
  212. if (config.GitConfig.Enabled)
  213. {
  214. string email = UserHelper.GetUserEmailAddress(config, user.Username);
  215. // We need to check the actual git database
  216. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database);
  217. string sql = @"SELECT * FROM gogs.repository
  218. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  219. WHERE gogs.user.login_name = {0}";
  220. var results = mySQL.Query(sql, new object[] { email });
  221. noData &= !(results != null && results.Any());
  222. }
  223. if (noData)
  224. {
  225. // They have no data, so safe to delete them.
  226. UserHelper.DeleteUser(db, config, UserHelper.GetUser(db, user.Username));
  227. totalUsers++;
  228. }
  229. continue;
  230. }
  231. #endregion
  232. }
  233. if (totalUsers > 0)
  234. {
  235. // Add to transparency report if any users were removed
  236. Takedown report = db.Takedowns.Create();
  237. report.Requester = TAKEDOWN_REPORTER;
  238. report.RequesterContact = config.SupportEmail;
  239. report.DateRequested = DateTime.Now;
  240. report.Reason = "User Inactive";
  241. report.ActionTaken = string.Format("{0} Users Removed", totalUsers);
  242. report.DateActionTaken = DateTime.Now;
  243. db.Takedowns.Add(report);
  244. db.SaveChanges();
  245. }
  246. Output(string.Format("[{0}] Finished Cleaning of Inactive Users. {1} Users Removed.", DateTime.Now, totalUsers));
  247. }
  248. public static void CleanEmail(Config config, TeknikEntities db)
  249. {
  250. if (config.EmailConfig.Enabled)
  251. {
  252. Output(string.Format("[{0}] Started Cleaning of Orphaned Email Accounts.", DateTime.Now));
  253. List<User> curUsers = db.Users.ToList();
  254. int totalAccounts = 0;
  255. // Connect to hmailserver COM
  256. var app = new hMailServer.Application();
  257. app.Connect();
  258. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  259. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  260. var accounts = domain.Accounts;
  261. for (int i = 0; i < accounts.Count; i++)
  262. {
  263. var account = accounts[i];
  264. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username) == account.Address);
  265. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r).ToLower() == account.Address.ToLower());
  266. if (!userExists && !isReserved)
  267. {
  268. // User doesn't exist, and it isn't reserved. Let's nuke it.
  269. UserHelper.DeleteUserEmail(config, account.Address);
  270. totalAccounts++;
  271. }
  272. }
  273. if (totalAccounts > 0)
  274. {
  275. // Add to transparency report if any users were removed
  276. Takedown report = db.Takedowns.Create();
  277. report.Requester = TAKEDOWN_REPORTER;
  278. report.RequesterContact = config.SupportEmail;
  279. report.DateRequested = DateTime.Now;
  280. report.Reason = "Orphaned Email Account";
  281. report.ActionTaken = string.Format("{0} Accounts Removed", totalAccounts);
  282. report.DateActionTaken = DateTime.Now;
  283. db.Takedowns.Add(report);
  284. db.SaveChanges();
  285. }
  286. Output(string.Format("[{0}] Finished Cleaning of Orphaned Email Accounts. {1} Accounts Removed.", DateTime.Now, totalAccounts));
  287. }
  288. }
  289. public static void CleanGit(Config config, TeknikEntities db)
  290. {
  291. if (config.GitConfig.Enabled)
  292. {
  293. Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now));
  294. List<User> curUsers = db.Users.ToList();
  295. int totalAccounts = 0;
  296. // We need to check the actual git database
  297. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database);
  298. string sql = @"SELECT gogs.user.login_name AS login_name, gogs.user.lower_name AS username FROM gogs.user";
  299. var results = mySQL.Query(sql);
  300. if (results != null && results.Any())
  301. {
  302. foreach (var account in results)
  303. {
  304. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username).ToLower() == account["login_name"].ToString().ToLower());
  305. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r) == account["login_name"].ToString().ToLower());
  306. if (!userExists && !isReserved)
  307. {
  308. UserHelper.DeleteUserGit(config, account["username"].ToString());
  309. totalAccounts++;
  310. }
  311. }
  312. }
  313. if (totalAccounts > 0)
  314. {
  315. // Add to transparency report if any users were removed
  316. Takedown report = db.Takedowns.Create();
  317. report.Requester = TAKEDOWN_REPORTER;
  318. report.RequesterContact = config.SupportEmail;
  319. report.DateRequested = DateTime.Now;
  320. report.Reason = "Orphaned Git Account";
  321. report.ActionTaken = string.Format("{0} Accounts Removed", totalAccounts);
  322. report.DateActionTaken = DateTime.Now;
  323. db.Takedowns.Add(report);
  324. db.SaveChanges();
  325. }
  326. Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts. {1} Accounts Removed.", DateTime.Now, totalAccounts));
  327. }
  328. }
  329. public static void GenerateLastSeen(Config config, TeknikEntities db, string fileName)
  330. {
  331. Output(string.Format("[{0}] Started Generation of Last Activity List.", DateTime.Now));
  332. List<User> curUsers = db.Users.ToList();
  333. StringBuilder sb = new StringBuilder();
  334. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  335. foreach (User user in curUsers)
  336. {
  337. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  338. user.Username,
  339. UserHelper.GetLastActivity(db, config, user).ToString("g"),
  340. user.JoinDate.ToString("g"),
  341. user.LastSeen.ToString("g"),
  342. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  343. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  344. }
  345. string dir = Path.GetDirectoryName(fileName);
  346. if (!Directory.Exists(dir))
  347. Directory.CreateDirectory(dir);
  348. File.WriteAllText(fileName, sb.ToString());
  349. Output(string.Format("[{0}] Finished Generating Last Activity List.", DateTime.Now));
  350. }
  351. public static void Output(string message)
  352. {
  353. Console.WriteLine(message);
  354. if (OutputEvent != null)
  355. {
  356. OutputEvent(message);
  357. }
  358. }
  359. }
  360. }