WebServiceAuthApi.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.Auth;
  16. using Microsoft.AspNetCore.Http;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Net;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. namespace DnsServerCore
  23. {
  24. sealed class WebServiceAuthApi
  25. {
  26. #region variables
  27. readonly DnsWebService _dnsWebService;
  28. #endregion
  29. #region constructor
  30. public WebServiceAuthApi(DnsWebService dnsWebService)
  31. {
  32. _dnsWebService = dnsWebService;
  33. }
  34. #endregion
  35. #region private
  36. private void WriteCurrentSessionDetails(Utf8JsonWriter jsonWriter, UserSession currentSession, bool includeInfo)
  37. {
  38. if (currentSession.Type == UserSessionType.ApiToken)
  39. {
  40. jsonWriter.WriteString("username", currentSession.User.Username);
  41. jsonWriter.WriteString("tokenName", currentSession.TokenName);
  42. jsonWriter.WriteString("token", currentSession.Token);
  43. }
  44. else
  45. {
  46. jsonWriter.WriteString("displayName", currentSession.User.DisplayName);
  47. jsonWriter.WriteString("username", currentSession.User.Username);
  48. jsonWriter.WriteString("token", currentSession.Token);
  49. }
  50. if (includeInfo)
  51. {
  52. jsonWriter.WritePropertyName("info");
  53. jsonWriter.WriteStartObject();
  54. jsonWriter.WriteString("version", _dnsWebService.GetServerVersion());
  55. jsonWriter.WriteString("dnsServerDomain", _dnsWebService.DnsServer.ServerDomain);
  56. jsonWriter.WriteNumber("defaultRecordTtl", _dnsWebService._zonesApi.DefaultRecordTtl);
  57. jsonWriter.WritePropertyName("permissions");
  58. jsonWriter.WriteStartObject();
  59. for (int i = 1; i <= 11; i++)
  60. {
  61. PermissionSection section = (PermissionSection)i;
  62. jsonWriter.WritePropertyName(section.ToString());
  63. jsonWriter.WriteStartObject();
  64. jsonWriter.WriteBoolean("canView", _dnsWebService._authManager.IsPermitted(section, currentSession.User, PermissionFlag.View));
  65. jsonWriter.WriteBoolean("canModify", _dnsWebService._authManager.IsPermitted(section, currentSession.User, PermissionFlag.Modify));
  66. jsonWriter.WriteBoolean("canDelete", _dnsWebService._authManager.IsPermitted(section, currentSession.User, PermissionFlag.Delete));
  67. jsonWriter.WriteEndObject();
  68. }
  69. jsonWriter.WriteEndObject();
  70. jsonWriter.WriteEndObject();
  71. }
  72. }
  73. private void WriteUserDetails(Utf8JsonWriter jsonWriter, User user, UserSession currentSession, bool includeMoreDetails, bool includeGroups)
  74. {
  75. jsonWriter.WriteString("displayName", user.DisplayName);
  76. jsonWriter.WriteString("username", user.Username);
  77. jsonWriter.WriteBoolean("disabled", user.Disabled);
  78. jsonWriter.WriteString("previousSessionLoggedOn", user.PreviousSessionLoggedOn);
  79. jsonWriter.WriteString("previousSessionRemoteAddress", user.PreviousSessionRemoteAddress.ToString());
  80. jsonWriter.WriteString("recentSessionLoggedOn", user.RecentSessionLoggedOn);
  81. jsonWriter.WriteString("recentSessionRemoteAddress", user.RecentSessionRemoteAddress.ToString());
  82. if (includeMoreDetails)
  83. {
  84. jsonWriter.WriteNumber("sessionTimeoutSeconds", user.SessionTimeoutSeconds);
  85. jsonWriter.WritePropertyName("memberOfGroups");
  86. jsonWriter.WriteStartArray();
  87. List<Group> memberOfGroups = new List<Group>(user.MemberOfGroups);
  88. memberOfGroups.Sort();
  89. foreach (Group group in memberOfGroups)
  90. {
  91. if (group.Name.Equals("Everyone", StringComparison.OrdinalIgnoreCase))
  92. continue;
  93. jsonWriter.WriteStringValue(group.Name);
  94. }
  95. jsonWriter.WriteEndArray();
  96. jsonWriter.WritePropertyName("sessions");
  97. jsonWriter.WriteStartArray();
  98. List<UserSession> sessions = _dnsWebService._authManager.GetSessions(user);
  99. sessions.Sort();
  100. foreach (UserSession session in sessions)
  101. WriteUserSessionDetails(jsonWriter, session, currentSession);
  102. jsonWriter.WriteEndArray();
  103. }
  104. if (includeGroups)
  105. {
  106. List<Group> groups = new List<Group>(_dnsWebService._authManager.Groups);
  107. groups.Sort();
  108. jsonWriter.WritePropertyName("groups");
  109. jsonWriter.WriteStartArray();
  110. foreach (Group group in groups)
  111. {
  112. if (group.Name.Equals("Everyone", StringComparison.OrdinalIgnoreCase))
  113. continue;
  114. jsonWriter.WriteStringValue(group.Name);
  115. }
  116. jsonWriter.WriteEndArray();
  117. }
  118. }
  119. private static void WriteUserSessionDetails(Utf8JsonWriter jsonWriter, UserSession session, UserSession currentSession)
  120. {
  121. jsonWriter.WriteStartObject();
  122. jsonWriter.WriteString("username", session.User.Username);
  123. jsonWriter.WriteBoolean("isCurrentSession", session.Equals(currentSession));
  124. jsonWriter.WriteString("partialToken", session.Token.Substring(0, 16));
  125. jsonWriter.WriteString("type", session.Type.ToString());
  126. jsonWriter.WriteString("tokenName", session.TokenName);
  127. jsonWriter.WriteString("lastSeen", session.LastSeen);
  128. jsonWriter.WriteString("lastSeenRemoteAddress", session.LastSeenRemoteAddress.ToString());
  129. jsonWriter.WriteString("lastSeenUserAgent", session.LastSeenUserAgent);
  130. jsonWriter.WriteEndObject();
  131. }
  132. private void WriteGroupDetails(Utf8JsonWriter jsonWriter, Group group, bool includeMembers, bool includeUsers)
  133. {
  134. jsonWriter.WriteString("name", group.Name);
  135. jsonWriter.WriteString("description", group.Description);
  136. if (includeMembers)
  137. {
  138. jsonWriter.WritePropertyName("members");
  139. jsonWriter.WriteStartArray();
  140. List<User> members = _dnsWebService._authManager.GetGroupMembers(group);
  141. members.Sort();
  142. foreach (User user in members)
  143. jsonWriter.WriteStringValue(user.Username);
  144. jsonWriter.WriteEndArray();
  145. }
  146. if (includeUsers)
  147. {
  148. List<User> users = new List<User>(_dnsWebService._authManager.Users);
  149. users.Sort();
  150. jsonWriter.WritePropertyName("users");
  151. jsonWriter.WriteStartArray();
  152. foreach (User user in users)
  153. jsonWriter.WriteStringValue(user.Username);
  154. jsonWriter.WriteEndArray();
  155. }
  156. }
  157. private void WritePermissionDetails(Utf8JsonWriter jsonWriter, Permission permission, string subItem, bool includeUsersAndGroups)
  158. {
  159. jsonWriter.WriteString("section", permission.Section.ToString());
  160. if (subItem is not null)
  161. jsonWriter.WriteString("subItem", subItem.Length == 0 ? "." : subItem);
  162. jsonWriter.WritePropertyName("userPermissions");
  163. jsonWriter.WriteStartArray();
  164. List<KeyValuePair<User, PermissionFlag>> userPermissions = new List<KeyValuePair<User, PermissionFlag>>(permission.UserPermissions);
  165. userPermissions.Sort(delegate (KeyValuePair<User, PermissionFlag> x, KeyValuePair<User, PermissionFlag> y)
  166. {
  167. return x.Key.Username.CompareTo(y.Key.Username);
  168. });
  169. foreach (KeyValuePair<User, PermissionFlag> userPermission in userPermissions)
  170. {
  171. jsonWriter.WriteStartObject();
  172. jsonWriter.WriteString("username", userPermission.Key.Username);
  173. jsonWriter.WriteBoolean("canView", userPermission.Value.HasFlag(PermissionFlag.View));
  174. jsonWriter.WriteBoolean("canModify", userPermission.Value.HasFlag(PermissionFlag.Modify));
  175. jsonWriter.WriteBoolean("canDelete", userPermission.Value.HasFlag(PermissionFlag.Delete));
  176. jsonWriter.WriteEndObject();
  177. }
  178. jsonWriter.WriteEndArray();
  179. jsonWriter.WritePropertyName("groupPermissions");
  180. jsonWriter.WriteStartArray();
  181. List<KeyValuePair<Group, PermissionFlag>> groupPermissions = new List<KeyValuePair<Group, PermissionFlag>>(permission.GroupPermissions);
  182. groupPermissions.Sort(delegate (KeyValuePair<Group, PermissionFlag> x, KeyValuePair<Group, PermissionFlag> y)
  183. {
  184. return x.Key.Name.CompareTo(y.Key.Name);
  185. });
  186. foreach (KeyValuePair<Group, PermissionFlag> groupPermission in groupPermissions)
  187. {
  188. jsonWriter.WriteStartObject();
  189. jsonWriter.WriteString("name", groupPermission.Key.Name);
  190. jsonWriter.WriteBoolean("canView", groupPermission.Value.HasFlag(PermissionFlag.View));
  191. jsonWriter.WriteBoolean("canModify", groupPermission.Value.HasFlag(PermissionFlag.Modify));
  192. jsonWriter.WriteBoolean("canDelete", groupPermission.Value.HasFlag(PermissionFlag.Delete));
  193. jsonWriter.WriteEndObject();
  194. }
  195. jsonWriter.WriteEndArray();
  196. if (includeUsersAndGroups)
  197. {
  198. List<User> users = new List<User>(_dnsWebService._authManager.Users);
  199. users.Sort();
  200. List<Group> groups = new List<Group>(_dnsWebService._authManager.Groups);
  201. groups.Sort();
  202. jsonWriter.WritePropertyName("users");
  203. jsonWriter.WriteStartArray();
  204. foreach (User user in users)
  205. jsonWriter.WriteStringValue(user.Username);
  206. jsonWriter.WriteEndArray();
  207. jsonWriter.WritePropertyName("groups");
  208. jsonWriter.WriteStartArray();
  209. foreach (Group group in groups)
  210. jsonWriter.WriteStringValue(group.Name);
  211. jsonWriter.WriteEndArray();
  212. }
  213. }
  214. #endregion
  215. #region public
  216. public async Task LoginAsync(HttpContext context, UserSessionType sessionType)
  217. {
  218. HttpRequest request = context.Request;
  219. string username = request.GetQueryOrForm("user");
  220. string password = request.GetQueryOrForm("pass");
  221. string tokenName = (sessionType == UserSessionType.ApiToken) ? request.GetQueryOrForm("tokenName") : null;
  222. bool includeInfo = request.GetQueryOrForm("includeInfo", bool.Parse, false);
  223. IPEndPoint remoteEP = context.GetRemoteEndPoint();
  224. UserSession session = await _dnsWebService._authManager.CreateSessionAsync(sessionType, tokenName, username, password, remoteEP.Address, request.Headers.UserAgent);
  225. _dnsWebService._log.Write(remoteEP, "[" + session.User.Username + "] User logged in.");
  226. _dnsWebService._authManager.SaveConfigFile();
  227. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  228. WriteCurrentSessionDetails(jsonWriter, session, includeInfo);
  229. }
  230. public void Logout(HttpContext context)
  231. {
  232. string token = context.Request.GetQueryOrForm("token");
  233. UserSession session = _dnsWebService._authManager.DeleteSession(token);
  234. if (session is not null)
  235. {
  236. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User logged out.");
  237. _dnsWebService._authManager.SaveConfigFile();
  238. }
  239. }
  240. public void GetCurrentSessionDetails(HttpContext context)
  241. {
  242. UserSession session = context.GetCurrentSession();
  243. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  244. WriteCurrentSessionDetails(jsonWriter, session, true);
  245. }
  246. public void ChangePassword(HttpContext context)
  247. {
  248. UserSession session = context.GetCurrentSession();
  249. if (session.Type != UserSessionType.Standard)
  250. throw new DnsWebServiceException("Access was denied.");
  251. string password = context.Request.GetQueryOrForm("pass");
  252. session.User.ChangePassword(password);
  253. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Password was changed successfully.");
  254. _dnsWebService._authManager.SaveConfigFile();
  255. }
  256. public void GetProfile(HttpContext context)
  257. {
  258. UserSession session = context.GetCurrentSession();
  259. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  260. WriteUserDetails(jsonWriter, session.User, session, true, false);
  261. }
  262. public void SetProfile(HttpContext context)
  263. {
  264. UserSession session = context.GetCurrentSession();
  265. if (session.Type != UserSessionType.Standard)
  266. throw new DnsWebServiceException("Access was denied.");
  267. HttpRequest request = context.Request;
  268. if (request.TryGetQueryOrForm("displayName", out string displayName))
  269. session.User.DisplayName = displayName;
  270. if (request.TryGetQueryOrForm("sessionTimeoutSeconds", int.Parse, out int sessionTimeoutSeconds))
  271. session.User.SessionTimeoutSeconds = sessionTimeoutSeconds;
  272. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User profile was updated successfully.");
  273. _dnsWebService._authManager.SaveConfigFile();
  274. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  275. WriteUserDetails(jsonWriter, session.User, session, true, false);
  276. }
  277. public void ListSessions(HttpContext context)
  278. {
  279. UserSession session = context.GetCurrentSession();
  280. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  281. throw new DnsWebServiceException("Access was denied.");
  282. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  283. jsonWriter.WritePropertyName("sessions");
  284. jsonWriter.WriteStartArray();
  285. List<UserSession> sessions = new List<UserSession>(_dnsWebService._authManager.Sessions);
  286. sessions.Sort();
  287. foreach (UserSession activeSession in sessions)
  288. {
  289. if (!activeSession.HasExpired())
  290. WriteUserSessionDetails(jsonWriter, activeSession, session);
  291. }
  292. jsonWriter.WriteEndArray();
  293. }
  294. public void CreateApiToken(HttpContext context)
  295. {
  296. UserSession session = context.GetCurrentSession();
  297. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Modify))
  298. throw new DnsWebServiceException("Access was denied.");
  299. HttpRequest request = context.Request;
  300. string username = request.GetQueryOrForm("user");
  301. string tokenName = request.GetQueryOrForm("tokenName");
  302. IPEndPoint remoteEP = context.GetRemoteEndPoint();
  303. UserSession createdSession = _dnsWebService._authManager.CreateApiToken(tokenName, username, remoteEP.Address, request.Headers.UserAgent);
  304. _dnsWebService._log.Write(remoteEP, "[" + session.User.Username + "] API token [" + tokenName + "] was created successfully for user: " + username);
  305. _dnsWebService._authManager.SaveConfigFile();
  306. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  307. jsonWriter.WriteString("username", createdSession.User.Username);
  308. jsonWriter.WriteString("tokenName", createdSession.TokenName);
  309. jsonWriter.WriteString("token", createdSession.Token);
  310. }
  311. public void DeleteSession(HttpContext context, bool isAdminContext)
  312. {
  313. UserSession session = context.GetCurrentSession();
  314. if (isAdminContext)
  315. {
  316. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Delete))
  317. throw new DnsWebServiceException("Access was denied.");
  318. }
  319. string strPartialToken = context.Request.GetQueryOrForm("partialToken");
  320. if (session.Token.StartsWith(strPartialToken))
  321. throw new InvalidOperationException("Invalid operation: cannot delete current session.");
  322. string token = null;
  323. foreach (UserSession activeSession in _dnsWebService._authManager.Sessions)
  324. {
  325. if (activeSession.Token.StartsWith(strPartialToken))
  326. {
  327. token = activeSession.Token;
  328. break;
  329. }
  330. }
  331. if (token is null)
  332. throw new DnsWebServiceException("No such active session was found for partial token: " + strPartialToken);
  333. if (!isAdminContext)
  334. {
  335. UserSession sessionToDelete = _dnsWebService._authManager.GetSession(token);
  336. if (sessionToDelete.User != session.User)
  337. throw new DnsWebServiceException("Access was denied.");
  338. }
  339. UserSession deletedSession = _dnsWebService._authManager.DeleteSession(token);
  340. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User session [" + strPartialToken + "] was deleted successfully for user: " + deletedSession.User.Username);
  341. _dnsWebService._authManager.SaveConfigFile();
  342. }
  343. public void ListUsers(HttpContext context)
  344. {
  345. UserSession session = context.GetCurrentSession();
  346. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  347. throw new DnsWebServiceException("Access was denied.");
  348. List<User> users = new List<User>(_dnsWebService._authManager.Users);
  349. users.Sort();
  350. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  351. jsonWriter.WritePropertyName("users");
  352. jsonWriter.WriteStartArray();
  353. foreach (User user in users)
  354. {
  355. jsonWriter.WriteStartObject();
  356. WriteUserDetails(jsonWriter, user, null, false, false);
  357. jsonWriter.WriteEndObject();
  358. }
  359. jsonWriter.WriteEndArray();
  360. }
  361. public void CreateUser(HttpContext context)
  362. {
  363. UserSession session = context.GetCurrentSession();
  364. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Modify))
  365. throw new DnsWebServiceException("Access was denied.");
  366. HttpRequest request = context.Request;
  367. string displayName = request.QueryOrForm("displayName");
  368. string username = request.GetQueryOrForm("user");
  369. string password = request.GetQueryOrForm("pass");
  370. User user = _dnsWebService._authManager.CreateUser(displayName, username, password);
  371. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User account was created successfully with username: " + user.Username);
  372. _dnsWebService._authManager.SaveConfigFile();
  373. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  374. WriteUserDetails(jsonWriter, user, null, false, false);
  375. }
  376. public void GetUserDetails(HttpContext context)
  377. {
  378. UserSession session = context.GetCurrentSession();
  379. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  380. throw new DnsWebServiceException("Access was denied.");
  381. HttpRequest request = context.Request;
  382. string username = request.GetQueryOrForm("user");
  383. bool includeGroups = request.GetQueryOrForm("includeGroups", bool.Parse, false);
  384. User user = _dnsWebService._authManager.GetUser(username);
  385. if (user is null)
  386. throw new DnsWebServiceException("No such user exists: " + username);
  387. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  388. WriteUserDetails(jsonWriter, user, null, true, includeGroups);
  389. }
  390. public void SetUserDetails(HttpContext context)
  391. {
  392. UserSession session = context.GetCurrentSession();
  393. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Modify))
  394. throw new DnsWebServiceException("Access was denied.");
  395. HttpRequest request = context.Request;
  396. string username = request.GetQueryOrForm("user");
  397. User user = _dnsWebService._authManager.GetUser(username);
  398. if (user is null)
  399. throw new DnsWebServiceException("No such user exists: " + username);
  400. if (request.TryGetQueryOrForm("displayName", out string displayName))
  401. user.DisplayName = displayName;
  402. if (request.TryGetQueryOrForm("newUser", out string newUsername))
  403. _dnsWebService._authManager.ChangeUsername(user, newUsername);
  404. if (request.TryGetQueryOrForm("disabled", bool.Parse, out bool disabled) && (session.User != user)) //to avoid self lockout
  405. {
  406. user.Disabled = disabled;
  407. if (user.Disabled)
  408. {
  409. foreach (UserSession userSession in _dnsWebService._authManager.Sessions)
  410. {
  411. if (userSession.Type == UserSessionType.ApiToken)
  412. continue;
  413. if (userSession.User == user)
  414. _dnsWebService._authManager.DeleteSession(userSession.Token);
  415. }
  416. }
  417. }
  418. if (request.TryGetQueryOrForm("sessionTimeoutSeconds", int.Parse, out int sessionTimeoutSeconds))
  419. user.SessionTimeoutSeconds = sessionTimeoutSeconds;
  420. string newPassword = request.QueryOrForm("newPass");
  421. if (!string.IsNullOrWhiteSpace(newPassword))
  422. {
  423. int iterations = request.GetQueryOrForm("iterations", int.Parse, User.DEFAULT_ITERATIONS);
  424. user.ChangePassword(newPassword, iterations);
  425. }
  426. string memberOfGroups = request.QueryOrForm("memberOfGroups");
  427. if (memberOfGroups is not null)
  428. {
  429. string[] parts = memberOfGroups.Split(',');
  430. Dictionary<string, Group> groups = new Dictionary<string, Group>(parts.Length);
  431. foreach (string part in parts)
  432. {
  433. if (part.Length == 0)
  434. continue;
  435. Group group = _dnsWebService._authManager.GetGroup(part);
  436. if (group is null)
  437. throw new DnsWebServiceException("No such group exists: " + part);
  438. groups.Add(group.Name.ToLower(), group);
  439. }
  440. //ensure user is member of everyone group
  441. Group everyone = _dnsWebService._authManager.GetGroup(Group.EVERYONE);
  442. groups[everyone.Name.ToLower()] = everyone;
  443. if (session.User == user)
  444. {
  445. //ensure current admin user is member of administrators group to avoid self lockout
  446. Group admins = _dnsWebService._authManager.GetGroup(Group.ADMINISTRATORS);
  447. groups[admins.Name.ToLower()] = admins;
  448. }
  449. user.SyncGroups(groups);
  450. }
  451. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User account details were updated successfully for user: " + username);
  452. _dnsWebService._authManager.SaveConfigFile();
  453. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  454. WriteUserDetails(jsonWriter, user, null, true, false);
  455. }
  456. public void DeleteUser(HttpContext context)
  457. {
  458. UserSession session = context.GetCurrentSession();
  459. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Delete))
  460. throw new DnsWebServiceException("Access was denied.");
  461. string username = context.Request.GetQueryOrForm("user");
  462. if (session.User.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
  463. throw new InvalidOperationException("Invalid operation: cannot delete current user.");
  464. if (!_dnsWebService._authManager.DeleteUser(username))
  465. throw new DnsWebServiceException("Failed to delete user: " + username);
  466. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] User account was deleted successfully with username: " + username);
  467. _dnsWebService._authManager.SaveConfigFile();
  468. }
  469. public void ListGroups(HttpContext context)
  470. {
  471. UserSession session = context.GetCurrentSession();
  472. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  473. throw new DnsWebServiceException("Access was denied.");
  474. List<Group> groups = new List<Group>(_dnsWebService._authManager.Groups);
  475. groups.Sort();
  476. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  477. jsonWriter.WritePropertyName("groups");
  478. jsonWriter.WriteStartArray();
  479. foreach (Group group in groups)
  480. {
  481. if (group.Name.Equals("Everyone", StringComparison.OrdinalIgnoreCase))
  482. continue;
  483. jsonWriter.WriteStartObject();
  484. WriteGroupDetails(jsonWriter, group, false, false);
  485. jsonWriter.WriteEndObject();
  486. }
  487. jsonWriter.WriteEndArray();
  488. }
  489. public void CreateGroup(HttpContext context)
  490. {
  491. UserSession session = context.GetCurrentSession();
  492. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Modify))
  493. throw new DnsWebServiceException("Access was denied.");
  494. HttpRequest request = context.Request;
  495. string groupName = request.GetQueryOrForm("group");
  496. string description = request.GetQueryOrForm("description", "");
  497. Group group = _dnsWebService._authManager.CreateGroup(groupName, description);
  498. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Group was created successfully with name: " + group.Name);
  499. _dnsWebService._authManager.SaveConfigFile();
  500. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  501. WriteGroupDetails(jsonWriter, group, false, false);
  502. }
  503. public void GetGroupDetails(HttpContext context)
  504. {
  505. UserSession session = context.GetCurrentSession();
  506. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  507. throw new DnsWebServiceException("Access was denied.");
  508. HttpRequest request = context.Request;
  509. string groupName = request.GetQueryOrForm("group");
  510. bool includeUsers = request.GetQueryOrForm("includeUsers", bool.Parse, false);
  511. Group group = _dnsWebService._authManager.GetGroup(groupName);
  512. if (group is null)
  513. throw new DnsWebServiceException("No such group exists: " + groupName);
  514. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  515. WriteGroupDetails(jsonWriter, group, true, includeUsers);
  516. }
  517. public void SetGroupDetails(HttpContext context)
  518. {
  519. UserSession session = context.GetCurrentSession();
  520. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Modify))
  521. throw new DnsWebServiceException("Access was denied.");
  522. HttpRequest request = context.Request;
  523. string groupName = request.GetQueryOrForm("group");
  524. Group group = _dnsWebService._authManager.GetGroup(groupName);
  525. if (group is null)
  526. throw new DnsWebServiceException("No such group exists: " + groupName);
  527. if (request.TryGetQueryOrForm("newGroup", out string newGroup))
  528. _dnsWebService._authManager.RenameGroup(group, newGroup);
  529. if (request.TryGetQueryOrForm("description", out string description))
  530. group.Description = description;
  531. string members = request.QueryOrForm("members");
  532. if (members is not null)
  533. {
  534. string[] parts = members.Split(',');
  535. Dictionary<string, User> users = new Dictionary<string, User>();
  536. foreach (string part in parts)
  537. {
  538. if (part.Length == 0)
  539. continue;
  540. User user = _dnsWebService._authManager.GetUser(part);
  541. if (user is null)
  542. throw new DnsWebServiceException("No such user exists: " + part);
  543. users.Add(user.Username, user);
  544. }
  545. if (group.Name.Equals("administrators", StringComparison.OrdinalIgnoreCase))
  546. users[session.User.Username] = session.User; //ensure current admin user is member of administrators group to avoid self lockout
  547. _dnsWebService._authManager.SyncGroupMembers(group, users);
  548. }
  549. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Group details were updated successfully for group: " + groupName);
  550. _dnsWebService._authManager.SaveConfigFile();
  551. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  552. WriteGroupDetails(jsonWriter, group, true, false);
  553. }
  554. public void DeleteGroup(HttpContext context)
  555. {
  556. UserSession session = context.GetCurrentSession();
  557. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Delete))
  558. throw new DnsWebServiceException("Access was denied.");
  559. string groupName = context.Request.GetQueryOrForm("group");
  560. if (!_dnsWebService._authManager.DeleteGroup(groupName))
  561. throw new DnsWebServiceException("Failed to delete group: " + groupName);
  562. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Group was deleted successfully with name: " + groupName);
  563. _dnsWebService._authManager.SaveConfigFile();
  564. }
  565. public void ListPermissions(HttpContext context)
  566. {
  567. UserSession session = context.GetCurrentSession();
  568. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  569. throw new DnsWebServiceException("Access was denied.");
  570. List<Permission> permissions = new List<Permission>(_dnsWebService._authManager.Permissions);
  571. permissions.Sort();
  572. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  573. jsonWriter.WritePropertyName("permissions");
  574. jsonWriter.WriteStartArray();
  575. foreach (Permission permission in permissions)
  576. {
  577. jsonWriter.WriteStartObject();
  578. WritePermissionDetails(jsonWriter, permission, null, false);
  579. jsonWriter.WriteEndObject();
  580. }
  581. jsonWriter.WriteEndArray();
  582. }
  583. public void GetPermissionDetails(HttpContext context, PermissionSection section)
  584. {
  585. UserSession session = context.GetCurrentSession();
  586. HttpRequest request = context.Request;
  587. string strSubItem = null;
  588. switch (section)
  589. {
  590. case PermissionSection.Unknown:
  591. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.View))
  592. throw new DnsWebServiceException("Access was denied.");
  593. section = request.GetQueryOrFormEnum<PermissionSection>("section");
  594. break;
  595. case PermissionSection.Zones:
  596. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, session.User, PermissionFlag.Modify))
  597. throw new DnsWebServiceException("Access was denied.");
  598. strSubItem = request.GetQueryOrForm("zone").TrimEnd('.');
  599. break;
  600. default:
  601. throw new InvalidOperationException();
  602. }
  603. bool includeUsersAndGroups = request.GetQueryOrForm("includeUsersAndGroups", bool.Parse, false);
  604. if (strSubItem is not null)
  605. {
  606. if (!_dnsWebService._authManager.IsPermitted(section, strSubItem, session.User, PermissionFlag.View))
  607. throw new DnsWebServiceException("Access was denied.");
  608. }
  609. Permission permission;
  610. if (strSubItem is null)
  611. permission = _dnsWebService._authManager.GetPermission(section);
  612. else
  613. permission = _dnsWebService._authManager.GetPermission(section, strSubItem);
  614. if (permission is null)
  615. throw new DnsWebServiceException("No permissions exists for section: " + section.ToString() + (strSubItem is null ? "" : "/" + strSubItem));
  616. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  617. WritePermissionDetails(jsonWriter, permission, strSubItem, includeUsersAndGroups);
  618. }
  619. public void SetPermissionsDetails(HttpContext context, PermissionSection section)
  620. {
  621. UserSession session = context.GetCurrentSession();
  622. HttpRequest request = context.Request;
  623. string strSubItem = null;
  624. switch (section)
  625. {
  626. case PermissionSection.Unknown:
  627. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Administration, session.User, PermissionFlag.Delete))
  628. throw new DnsWebServiceException("Access was denied.");
  629. section = request.GetQueryOrFormEnum<PermissionSection>("section");
  630. break;
  631. case PermissionSection.Zones:
  632. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, session.User, PermissionFlag.Modify))
  633. throw new DnsWebServiceException("Access was denied.");
  634. strSubItem = request.GetQueryOrForm("zone").TrimEnd('.');
  635. break;
  636. default:
  637. throw new InvalidOperationException();
  638. }
  639. if (strSubItem is not null)
  640. {
  641. if (!_dnsWebService._authManager.IsPermitted(section, strSubItem, session.User, PermissionFlag.Delete))
  642. throw new DnsWebServiceException("Access was denied.");
  643. }
  644. Permission permission;
  645. if (strSubItem is null)
  646. permission = _dnsWebService._authManager.GetPermission(section);
  647. else
  648. permission = _dnsWebService._authManager.GetPermission(section, strSubItem);
  649. if (permission is null)
  650. throw new DnsWebServiceException("No permissions exists for section: " + section.ToString() + (strSubItem is null ? "" : "/" + strSubItem));
  651. string strUserPermissions = request.QueryOrForm("userPermissions");
  652. if (strUserPermissions is not null)
  653. {
  654. string[] parts = strUserPermissions.Split('|');
  655. Dictionary<User, PermissionFlag> userPermissions = new Dictionary<User, PermissionFlag>();
  656. for (int i = 0; i < parts.Length; i += 4)
  657. {
  658. if (parts[i].Length == 0)
  659. continue;
  660. User user = _dnsWebService._authManager.GetUser(parts[i]);
  661. bool canView = bool.Parse(parts[i + 1]);
  662. bool canModify = bool.Parse(parts[i + 2]);
  663. bool canDelete = bool.Parse(parts[i + 3]);
  664. if (user is not null)
  665. {
  666. PermissionFlag permissionFlag = PermissionFlag.None;
  667. if (canView)
  668. permissionFlag |= PermissionFlag.View;
  669. if (canModify)
  670. permissionFlag |= PermissionFlag.Modify;
  671. if (canDelete)
  672. permissionFlag |= PermissionFlag.Delete;
  673. userPermissions[user] = permissionFlag;
  674. }
  675. }
  676. permission.SyncPermissions(userPermissions);
  677. }
  678. string strGroupPermissions = request.QueryOrForm("groupPermissions");
  679. if (strGroupPermissions is not null)
  680. {
  681. string[] parts = strGroupPermissions.Split('|');
  682. Dictionary<Group, PermissionFlag> groupPermissions = new Dictionary<Group, PermissionFlag>();
  683. for (int i = 0; i < parts.Length; i += 4)
  684. {
  685. if (parts[i].Length == 0)
  686. continue;
  687. Group group = _dnsWebService._authManager.GetGroup(parts[i]);
  688. bool canView = bool.Parse(parts[i + 1]);
  689. bool canModify = bool.Parse(parts[i + 2]);
  690. bool canDelete = bool.Parse(parts[i + 3]);
  691. if (group is not null)
  692. {
  693. PermissionFlag permissionFlag = PermissionFlag.None;
  694. if (canView)
  695. permissionFlag |= PermissionFlag.View;
  696. if (canModify)
  697. permissionFlag |= PermissionFlag.Modify;
  698. if (canDelete)
  699. permissionFlag |= PermissionFlag.Delete;
  700. groupPermissions[group] = permissionFlag;
  701. }
  702. }
  703. //ensure administrators group always has all permissions
  704. Group admins = _dnsWebService._authManager.GetGroup(Group.ADMINISTRATORS);
  705. groupPermissions[admins] = PermissionFlag.ViewModifyDelete;
  706. switch (section)
  707. {
  708. case PermissionSection.Zones:
  709. //ensure DNS administrators group always has all permissions
  710. Group dnsAdmins = _dnsWebService._authManager.GetGroup(Group.DNS_ADMINISTRATORS);
  711. groupPermissions[dnsAdmins] = PermissionFlag.ViewModifyDelete;
  712. break;
  713. case PermissionSection.DhcpServer:
  714. //ensure DHCP administrators group always has all permissions
  715. Group dhcpAdmins = _dnsWebService._authManager.GetGroup(Group.DHCP_ADMINISTRATORS);
  716. groupPermissions[dhcpAdmins] = PermissionFlag.ViewModifyDelete;
  717. break;
  718. }
  719. permission.SyncPermissions(groupPermissions);
  720. }
  721. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Permissions were updated successfully for section: " + section.ToString() + (string.IsNullOrEmpty(strSubItem) ? "" : "/" + strSubItem));
  722. _dnsWebService._authManager.SaveConfigFile();
  723. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  724. WritePermissionDetails(jsonWriter, permission, strSubItem, false);
  725. }
  726. #endregion
  727. }
  728. }