CredentialsCache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using System.Collections.Concurrent;
  2. using System.Security.Cryptography;
  3. using InABox.API;
  4. using InABox.Core;
  5. using InABox.Database;
  6. using Microsoft.Exchange.WebServices.Data;
  7. namespace InABox.API
  8. {
  9. public static class CredentialsCache
  10. {
  11. private static ConcurrentBag<User> _cache;
  12. private static void EnsureCache(bool force)
  13. {
  14. if (_cache == null || force)
  15. {
  16. var table = DbFactory.Provider.Query(
  17. null,
  18. new Columns<User>(
  19. x => x.ID,
  20. x => x.UserID,
  21. x => x.Password,
  22. x => x.Use2FA,
  23. x => x.Recipient2FA,
  24. x => x.TwoFactorAuthenticationType,
  25. x => x.AuthenticatorToken,
  26. x => x.PIN,
  27. x => x.SecurityGroup.ID,
  28. x => x.PasswordExpiration
  29. )
  30. );
  31. _cache = new ConcurrentBag<User>();
  32. foreach (var row in table.Rows)
  33. _cache.Add(row.ToObject<User>());
  34. }
  35. }
  36. public static bool IsBypassed(string userid, string password)
  37. {
  38. //if ((userid == "FROGSOFTWARE") && (password == "FROGSOFTWARE"))
  39. // return true;
  40. if (userid.IsBase64String() && password.IsBase64String())
  41. try
  42. {
  43. if (Encryption.Decrypt(userid, "wCq9rryEJEuHIifYrxRjxg", out var sUserTicks) &&
  44. Encryption.Decrypt(password, "7mhvLnqMwkCAzN+zNGlyyg", out var sPassTicks))
  45. if (long.TryParse(sUserTicks, out var userticks) && long.TryParse(sPassTicks, out var passticks))
  46. if (userticks == passticks)
  47. {
  48. var remotedate = new DateTime(userticks);
  49. var localdate = DateTime.Now.ToUniversalTime();
  50. if (remotedate >= localdate.AddDays(-1) && remotedate <= localdate.AddDays(1))
  51. return true;
  52. }
  53. }
  54. catch (Exception e)
  55. {
  56. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  57. }
  58. return false;
  59. }
  60. public static Guid Validate(Guid sessionID, out string? userID)
  61. {
  62. EnsureCache(false);
  63. if(!sessions.TryGetValue(sessionID, out var session) || !session.Valid)
  64. {
  65. userID = null;
  66. return Guid.Empty;
  67. }
  68. if(session.Expiry < DateTime.Now)
  69. {
  70. sessions.Remove(sessionID);
  71. userID = null;
  72. return Guid.Empty;
  73. }
  74. userID = session.UserID;
  75. return session.User;
  76. }
  77. public static User? Validate(Guid sessionID)
  78. {
  79. EnsureCache(false);
  80. if (!sessions.TryGetValue(sessionID, out var session) || !session.Valid)
  81. {
  82. return null;
  83. }
  84. if (session.Expiry < DateTime.Now)
  85. {
  86. sessions.Remove(sessionID);
  87. return null;
  88. }
  89. return _cache.FirstOrDefault(x => x.ID == session.User);
  90. }
  91. /// <summary>
  92. /// Validate a given session, and refresh the session expiry if valid; use for database queries that need to refresh the user's expiry time.
  93. /// </summary>
  94. /// <param name="sessionID"></param>
  95. /// <returns></returns>
  96. public static User? ValidateAndRefresh(Guid sessionID)
  97. {
  98. var user = Validate(sessionID);
  99. if(user is not null)
  100. {
  101. RefreshSessionExpiry(sessionID);
  102. }
  103. return user;
  104. }
  105. public static User? ValidateUser(string? pin)
  106. {
  107. if (String.IsNullOrWhiteSpace(pin))
  108. return null;
  109. EnsureCache(false);
  110. return _cache.FirstOrDefault(x => string.Equals(x.PIN, pin));
  111. }
  112. public static User? ValidateUser(string? userId, string? password)
  113. {
  114. if (String.IsNullOrWhiteSpace(userId) || String.IsNullOrWhiteSpace(password))
  115. return null;
  116. if (IsBypassed(userId, password))
  117. return new User() { ID = CoreUtils.FullGuid };
  118. EnsureCache(false);
  119. return _cache.FirstOrDefault(x => string.Equals(x.UserID, userId) && string.Equals(x.Password, password));
  120. }
  121. public static void LogoutUser(Guid userGuid)
  122. {
  123. sessions.Remove(userGuid);
  124. }
  125. public static void Refresh(bool force)
  126. {
  127. EnsureCache(force);
  128. }
  129. #region Sessions
  130. private class Session
  131. {
  132. public Guid User { get; init; }
  133. public string UserID { get; init; }
  134. public bool Valid { get; set; }
  135. public DateTime Expiry { get; set; }
  136. }
  137. // SessionID => Session
  138. private static Dictionary<Guid, Session> sessions = new();
  139. public static TimeSpan SessionExpiry = TimeSpan.FromHours(8);
  140. public static string? CacheFile { get; set; }
  141. public static IEnumerable<Guid> GetUserSessions(Guid userID)
  142. {
  143. return sessions.Where(x => x.Value.User == userID).Select(x => x.Key);
  144. }
  145. private static void CheckSessionExpiries()
  146. {
  147. var now = DateTime.Now;
  148. sessions = sessions
  149. .Where(x => x.Value.Expiry >= now)
  150. .ToDictionary(x => x.Key, x => x.Value);
  151. }
  152. public static void SetSessionExpiryTime(TimeSpan expiry)
  153. {
  154. SessionExpiry = expiry;
  155. }
  156. public static void RefreshSessionExpiry(Guid sessionID)
  157. {
  158. if (sessions.TryGetValue(sessionID, out var session))
  159. {
  160. if (session.Expiry != DateTime.MaxValue)
  161. {
  162. session.Expiry = DateTime.Now + SessionExpiry;
  163. }
  164. }
  165. }
  166. public static void SaveSessionCache()
  167. {
  168. CheckSessionExpiries();
  169. try
  170. {
  171. if (CacheFile != null)
  172. {
  173. var json = Serialization.Serialize(sessions.Where(x => x.Value.Expiry != DateTime.MaxValue).ToDictionary(x => x.Key, x => x.Value));
  174. File.WriteAllText(CacheFile, json);
  175. }
  176. else
  177. {
  178. Logger.Send(LogType.Error, "", "Error while saving session cache: No Cache file set!");
  179. }
  180. }
  181. catch (Exception e)
  182. {
  183. Logger.Send(LogType.Error, "", $"Error while saving session cache: {e.Message}");
  184. }
  185. }
  186. public static void LoadSessionCache()
  187. {
  188. try
  189. {
  190. if (CacheFile != null)
  191. {
  192. sessions = Serialization.Deserialize<Dictionary<Guid, Session>>(new FileStream(CacheFile, FileMode.Open))
  193. .Where(x => x.Value.Expiry != DateTime.MaxValue).ToDictionary(x => x.Key, x => x.Value);
  194. CheckSessionExpiries();
  195. }
  196. else
  197. {
  198. sessions = new();
  199. }
  200. }
  201. catch (Exception)
  202. {
  203. sessions = new();
  204. }
  205. }
  206. public static void SetCacheFile(string cacheFile)
  207. {
  208. CacheFile = cacheFile;
  209. }
  210. public static Guid NewSession(User user, bool valid = true, DateTime? expiry = null)
  211. {
  212. var session = Guid.NewGuid();
  213. sessions[session] = new() { User = user.ID, Valid = valid, Expiry = expiry ?? (DateTime.Now + SessionExpiry), UserID = user.UserID };
  214. return session;
  215. }
  216. public static bool SessionExists(Guid session)
  217. {
  218. return sessions.ContainsKey(session);
  219. }
  220. #endregion
  221. #region 2FA
  222. private class AuthenticationCode
  223. {
  224. public string Code { get; set; }
  225. public DateTime Expiry { get; set; }
  226. public int TriesLeft { get; set; }
  227. public AuthenticationCode(string code, DateTime expiry)
  228. {
  229. Code = code;
  230. Expiry = expiry;
  231. TriesLeft = TwoFATries;
  232. }
  233. }
  234. private static Dictionary<Guid, AuthenticationCode> authenticationCodes = new();
  235. private static readonly int TwoFATries = 3;
  236. public static readonly int CodeLength = 6;
  237. private static readonly TimeSpan Expiry2FACodeTime = TimeSpan.FromMinutes(15);
  238. private static Dictionary<SMSProviderType, ISMSProvider> SMSProviders { get; set; } = new();
  239. public static void AddSMSProvider(ISMSProvider provider)
  240. {
  241. SMSProviders.Add(provider.ProviderType, provider);
  242. }
  243. private static string GenerateCode()
  244. {
  245. var random = new Random(DateTime.Now.Millisecond);
  246. var code = "";
  247. for (int i = 0; i < CodeLength; i++)
  248. {
  249. code += random.Next(10).ToString();
  250. }
  251. return code;
  252. }
  253. public static Guid? SendCode(Guid userGuid, out string? recipient)
  254. {
  255. EnsureCache(false);
  256. var user = _cache.FirstOrDefault(x => x.ID == userGuid);
  257. if(user == null)
  258. {
  259. Logger.Send(LogType.Error, "", "Cannot send code; user does not exist!");
  260. recipient = null;
  261. return null;
  262. }
  263. var session = NewSession(user, false);
  264. Logger.Send(LogType.Information, "", $"New login session {session} for {user.UserID}");
  265. if (user.TwoFactorAuthenticationType != TwoFactorAuthenticationType.GoogleAuthenticator)
  266. {
  267. var smsProvider = SMSProviders
  268. .Where(x => x.Value.TwoFactorAuthenticationType == user.TwoFactorAuthenticationType)
  269. .Select(x => x.Value).FirstOrDefault();
  270. if (smsProvider == null)
  271. {
  272. Logger.Send(LogType.Error, "", "Cannot send code; user requests a 2FA method which is not supported!");
  273. recipient = null;
  274. return null;
  275. }
  276. var code = GenerateCode();
  277. Logger.Send(LogType.Information, "", $"Code for session {userGuid} is {code}");
  278. authenticationCodes.Add(session, new AuthenticationCode(code, DateTime.Now + Expiry2FACodeTime));
  279. var recAddr = user.Recipient2FA;
  280. if (smsProvider.SendMessage(recAddr, $"Your authentication code is {code}. This code will expire in {Expiry2FACodeTime.Minutes} minutes."))
  281. {
  282. Logger.Send(LogType.Information, "", "Code sent!");
  283. var first = recAddr[..3];
  284. var last = recAddr[^3..];
  285. recipient = first + new string('*', recAddr.Length - 6) + last;
  286. return session;
  287. }
  288. else
  289. {
  290. Logger.Send(LogType.Information, "", "Code failed to send!");
  291. recipient = null;
  292. return null;
  293. }
  294. }
  295. else
  296. {
  297. Logger.Send(LogType.Information, "", $"Google authenticator is being used");
  298. recipient = "Google Authenticator";
  299. return session;
  300. }
  301. }
  302. private static readonly int CodeModulo = (int)Math.Pow(10, CodeLength);
  303. private static string GenerateGoogleAuthenticatorCode(long time, byte[] key)
  304. {
  305. var window = time / 30;
  306. var hex = window.ToString("x");
  307. if (hex.Length < 16)
  308. {
  309. hex = hex.PadLeft(16, '0');
  310. }
  311. var bytes = Convert.FromHexString(hex);
  312. var hash = new HMACSHA1(key).ComputeHash(bytes);
  313. var offset = hash[hash.Length - 1] & 0xf;
  314. var selected = new byte[4];
  315. Buffer.BlockCopy(hash, offset, selected, 0, 4);
  316. if (BitConverter.IsLittleEndian)
  317. {
  318. Array.Reverse(selected);
  319. }
  320. var integer = BitConverter.ToInt32(selected, 0);
  321. var truncated = integer & 0x7fffffff;
  322. return (truncated % CodeModulo).ToString().PadLeft(CodeLength, '0');
  323. }
  324. private static bool CheckAuthenticationCode(byte[] token, string code)
  325. {
  326. var time = DateTimeOffset.Now.ToUnixTimeSeconds();
  327. for (long i = time - 30; i <= time; i += 30)
  328. {
  329. if(GenerateGoogleAuthenticatorCode(i, token) == code)
  330. {
  331. return true;
  332. }
  333. }
  334. return false;
  335. }
  336. public static bool ValidateCode(Guid sessionID, string code)
  337. {
  338. if (!sessions.TryGetValue(sessionID, out var session))
  339. {
  340. return false;
  341. }
  342. bool valid;
  343. if(authenticationCodes.TryGetValue(sessionID, out var result))
  344. {
  345. if (result.Code != code)
  346. {
  347. result.TriesLeft--;
  348. if (result.TriesLeft == 0)
  349. {
  350. authenticationCodes.Remove(sessionID);
  351. }
  352. valid = false;
  353. }
  354. else if (result.Expiry < DateTime.Now)
  355. {
  356. authenticationCodes.Remove(sessionID);
  357. valid = false;
  358. }
  359. else
  360. {
  361. valid = true;
  362. }
  363. }
  364. else
  365. {
  366. var user = _cache.FirstOrDefault(x => x.ID == session.User);
  367. if(user?.TwoFactorAuthenticationType == TwoFactorAuthenticationType.GoogleAuthenticator)
  368. {
  369. valid = CheckAuthenticationCode(user.AuthenticatorToken, code);
  370. }
  371. else
  372. {
  373. valid = false;
  374. }
  375. }
  376. if (valid)
  377. {
  378. session.Valid = true;
  379. return true;
  380. }
  381. else
  382. {
  383. return false;
  384. }
  385. }
  386. #endregion
  387. }
  388. }