CredentialsCache.cs 14 KB

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