CredentialsCache.cs 14 KB

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