Account.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  3. * Copyright (c) 2021-2022, Brian Gianforcaro <bgianf@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Base64.h>
  8. #include <AK/Memory.h>
  9. #include <AK/Random.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <LibCore/Account.h>
  12. #include <LibCore/Directory.h>
  13. #include <LibCore/System.h>
  14. #include <LibCore/UmaskScope.h>
  15. #include <errno.h>
  16. #include <grp.h>
  17. #include <pwd.h>
  18. #ifndef AK_OS_BSD_GENERIC
  19. # include <crypt.h>
  20. # include <shadow.h>
  21. #endif
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. namespace Core {
  27. static String get_salt()
  28. {
  29. char random_data[12];
  30. fill_with_random(random_data, sizeof(random_data));
  31. StringBuilder builder;
  32. builder.append("$5$"sv);
  33. builder.append(encode_base64(ReadonlyBytes(random_data, sizeof(random_data))));
  34. return builder.build();
  35. }
  36. static Vector<gid_t> get_extra_gids(passwd const& pwd)
  37. {
  38. StringView username { pwd.pw_name, strlen(pwd.pw_name) };
  39. Vector<gid_t> extra_gids;
  40. setgrent();
  41. for (auto* group = getgrent(); group; group = getgrent()) {
  42. if (group->gr_gid == pwd.pw_gid)
  43. continue;
  44. for (size_t i = 0; group->gr_mem[i]; ++i) {
  45. if (username == group->gr_mem[i]) {
  46. extra_gids.append(group->gr_gid);
  47. break;
  48. }
  49. }
  50. }
  51. endgrent();
  52. return extra_gids;
  53. }
  54. ErrorOr<Account> Account::from_passwd(passwd const& pwd, spwd const& spwd)
  55. {
  56. Account account(pwd, spwd, get_extra_gids(pwd));
  57. endpwent();
  58. #ifndef AK_OS_BSD_GENERIC
  59. endspent();
  60. #endif
  61. return account;
  62. }
  63. ErrorOr<Account> Account::self([[maybe_unused]] Read options)
  64. {
  65. Vector<gid_t> extra_gids = TRY(Core::System::getgroups());
  66. auto pwd = TRY(Core::System::getpwuid(getuid()));
  67. if (!pwd.has_value())
  68. return Error::from_string_literal("No such user");
  69. spwd spwd = {};
  70. #ifndef AK_OS_BSD_GENERIC
  71. if (options != Read::PasswdOnly) {
  72. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  73. if (!maybe_spwd.has_value())
  74. return Error::from_string_literal("No shadow entry for user");
  75. spwd = maybe_spwd.release_value();
  76. }
  77. #endif
  78. return Account(*pwd, spwd, extra_gids);
  79. }
  80. ErrorOr<Account> Account::from_name(StringView username, [[maybe_unused]] Read options)
  81. {
  82. auto pwd = TRY(Core::System::getpwnam(username));
  83. if (!pwd.has_value())
  84. return Error::from_string_literal("No such user");
  85. spwd spwd = {};
  86. #ifndef AK_OS_BSD_GENERIC
  87. if (options != Read::PasswdOnly) {
  88. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  89. if (!maybe_spwd.has_value())
  90. return Error::from_string_literal("No shadow entry for user");
  91. spwd = maybe_spwd.release_value();
  92. }
  93. #endif
  94. return from_passwd(*pwd, spwd);
  95. }
  96. ErrorOr<Account> Account::from_uid(uid_t uid, [[maybe_unused]] Read options)
  97. {
  98. auto pwd = TRY(Core::System::getpwuid(uid));
  99. if (!pwd.has_value())
  100. return Error::from_string_literal("No such user");
  101. spwd spwd = {};
  102. #ifndef AK_OS_BSD_GENERIC
  103. if (options != Read::PasswdOnly) {
  104. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  105. if (!maybe_spwd.has_value())
  106. return Error::from_string_literal("No shadow entry for user");
  107. spwd = maybe_spwd.release_value();
  108. }
  109. #endif
  110. return from_passwd(*pwd, spwd);
  111. }
  112. ErrorOr<Vector<Account>> Account::all([[maybe_unused]] Read options)
  113. {
  114. Vector<Account> accounts;
  115. #ifndef AK_OS_MACOS
  116. struct passwd pwd;
  117. struct passwd* ptr = nullptr;
  118. char buffer[1024] = { 0 };
  119. #endif
  120. ScopeGuard pwent_guard([] { endpwent(); });
  121. setpwent();
  122. errno = 0;
  123. #ifndef AK_OS_MACOS
  124. while (getpwent_r(&pwd, buffer, sizeof(buffer), &ptr) == 0 && ptr) {
  125. #else
  126. while (auto const* ptr = getpwent()) {
  127. #endif
  128. spwd spwd = {};
  129. #ifndef AK_OS_BSD_GENERIC
  130. ScopeGuard spent_guard([] { endspent(); });
  131. if (options != Read::PasswdOnly) {
  132. auto maybe_spwd = TRY(Core::System::getspnam({ ptr->pw_name, strlen(ptr->pw_name) }));
  133. if (!maybe_spwd.has_value())
  134. return Error::from_string_literal("No shadow entry for user");
  135. spwd = maybe_spwd.release_value();
  136. }
  137. #endif
  138. accounts.append({ *ptr, spwd, get_extra_gids(*ptr) });
  139. }
  140. if (errno)
  141. return Error::from_errno(errno);
  142. return accounts;
  143. }
  144. bool Account::authenticate(SecretString const& password) const
  145. {
  146. // If there was no shadow entry for this account, authentication always fails.
  147. if (m_password_hash.is_null())
  148. return false;
  149. // An empty passwd field indicates that no password is required to log in.
  150. if (m_password_hash.is_empty())
  151. return true;
  152. // FIXME: Use crypt_r if it can be built in lagom.
  153. char* hash = crypt(password.characters(), m_password_hash.characters());
  154. return hash != nullptr && AK::timing_safe_compare(hash, m_password_hash.characters(), m_password_hash.length());
  155. }
  156. ErrorOr<void> Account::login() const
  157. {
  158. TRY(Core::System::setgroups(m_extra_gids));
  159. TRY(Core::System::setgid(m_gid));
  160. TRY(Core::System::setuid(m_uid));
  161. return {};
  162. }
  163. void Account::set_password(SecretString const& password)
  164. {
  165. m_password_hash = crypt(password.characters(), get_salt().characters());
  166. }
  167. void Account::set_password_enabled(bool enabled)
  168. {
  169. if (enabled && m_password_hash != "" && m_password_hash[0] == '!') {
  170. m_password_hash = m_password_hash.substring(1, m_password_hash.length() - 1);
  171. } else if (!enabled && (m_password_hash == "" || m_password_hash[0] != '!')) {
  172. StringBuilder builder;
  173. builder.append('!');
  174. builder.append(m_password_hash);
  175. m_password_hash = builder.build();
  176. }
  177. }
  178. void Account::delete_password()
  179. {
  180. m_password_hash = "";
  181. }
  182. Account::Account(passwd const& pwd, spwd const& spwd, Vector<gid_t> extra_gids)
  183. : m_username(pwd.pw_name)
  184. , m_password_hash(spwd.sp_pwdp)
  185. , m_uid(pwd.pw_uid)
  186. , m_gid(pwd.pw_gid)
  187. , m_gecos(pwd.pw_gecos)
  188. , m_home_directory(pwd.pw_dir)
  189. , m_shell(pwd.pw_shell)
  190. , m_extra_gids(move(extra_gids))
  191. {
  192. }
  193. ErrorOr<String> Account::generate_passwd_file() const
  194. {
  195. StringBuilder builder;
  196. setpwent();
  197. struct passwd* p;
  198. errno = 0;
  199. while ((p = getpwent())) {
  200. if (p->pw_name == m_username) {
  201. builder.appendff("{}:!:{}:{}:{}:{}:{}\n",
  202. m_username,
  203. m_uid, m_gid,
  204. m_gecos,
  205. m_home_directory,
  206. m_shell);
  207. } else {
  208. builder.appendff("{}:!:{}:{}:{}:{}:{}\n",
  209. p->pw_name, p->pw_uid,
  210. p->pw_gid, p->pw_gecos, p->pw_dir,
  211. p->pw_shell);
  212. }
  213. }
  214. endpwent();
  215. if (errno)
  216. return Error::from_errno(errno);
  217. return builder.to_string();
  218. }
  219. #ifndef AK_OS_BSD_GENERIC
  220. ErrorOr<String> Account::generate_shadow_file() const
  221. {
  222. StringBuilder builder;
  223. setspent();
  224. struct spwd* p;
  225. errno = 0;
  226. while ((p = getspent())) {
  227. if (p->sp_namp == m_username) {
  228. builder.appendff("{}:{}:{}:{}:{}:{}:{}:{}:{}\n",
  229. m_username, m_password_hash,
  230. (p->sp_lstchg == -1) ? "" : String::formatted("{}", p->sp_lstchg),
  231. (p->sp_min == -1) ? "" : String::formatted("{}", p->sp_min),
  232. (p->sp_max == -1) ? "" : String::formatted("{}", p->sp_max),
  233. (p->sp_warn == -1) ? "" : String::formatted("{}", p->sp_warn),
  234. (p->sp_inact == -1) ? "" : String::formatted("{}", p->sp_inact),
  235. (p->sp_expire == -1) ? "" : String::formatted("{}", p->sp_expire),
  236. (p->sp_flag == 0) ? "" : String::formatted("{}", p->sp_flag));
  237. } else {
  238. builder.appendff("{}:{}:{}:{}:{}:{}:{}:{}:{}\n",
  239. p->sp_namp, p->sp_pwdp,
  240. (p->sp_lstchg == -1) ? "" : String::formatted("{}", p->sp_lstchg),
  241. (p->sp_min == -1) ? "" : String::formatted("{}", p->sp_min),
  242. (p->sp_max == -1) ? "" : String::formatted("{}", p->sp_max),
  243. (p->sp_warn == -1) ? "" : String::formatted("{}", p->sp_warn),
  244. (p->sp_inact == -1) ? "" : String::formatted("{}", p->sp_inact),
  245. (p->sp_expire == -1) ? "" : String::formatted("{}", p->sp_expire),
  246. (p->sp_flag == 0) ? "" : String::formatted("{}", p->sp_flag));
  247. }
  248. }
  249. endspent();
  250. if (errno)
  251. return Error::from_errno(errno);
  252. return builder.to_string();
  253. }
  254. #endif
  255. ErrorOr<void> Account::sync()
  256. {
  257. Core::UmaskScope umask_scope(0777);
  258. auto new_passwd_file_content = TRY(generate_passwd_file());
  259. #ifndef AK_OS_BSD_GENERIC
  260. auto new_shadow_file_content = TRY(generate_shadow_file());
  261. #endif
  262. // FIXME: mkstemp taking Span<char> makes this code entirely un-AKable.
  263. // Make this code less char-pointery.
  264. char new_passwd_name[] = "/etc/passwd.XXXXXX";
  265. size_t new_passwd_name_length = strlen(new_passwd_name);
  266. #ifndef AK_OS_BSD_GENERIC
  267. char new_shadow_name[] = "/etc/shadow.XXXXXX";
  268. size_t new_shadow_name_length = strlen(new_shadow_name);
  269. #endif
  270. {
  271. auto new_passwd_fd = TRY(Core::System::mkstemp({ new_passwd_name, new_passwd_name_length }));
  272. ScopeGuard new_passwd_fd_guard = [new_passwd_fd] { close(new_passwd_fd); };
  273. TRY(Core::System::fchmod(new_passwd_fd, 0644));
  274. #ifndef AK_OS_BSD_GENERIC
  275. auto new_shadow_fd = TRY(Core::System::mkstemp({ new_shadow_name, new_shadow_name_length }));
  276. ScopeGuard new_shadow_fd_guard = [new_shadow_fd] { close(new_shadow_fd); };
  277. TRY(Core::System::fchmod(new_shadow_fd, 0600));
  278. #endif
  279. auto nwritten = TRY(Core::System::write(new_passwd_fd, new_passwd_file_content.bytes()));
  280. VERIFY(static_cast<size_t>(nwritten) == new_passwd_file_content.length());
  281. #ifndef AK_OS_BSD_GENERIC
  282. nwritten = TRY(Core::System::write(new_shadow_fd, new_shadow_file_content.bytes()));
  283. VERIFY(static_cast<size_t>(nwritten) == new_shadow_file_content.length());
  284. #endif
  285. }
  286. TRY(Core::System::rename({ new_passwd_name, new_passwd_name_length }, "/etc/passwd"sv));
  287. #ifndef AK_OS_BSD_GENERIC
  288. TRY(Core::System::rename({ new_shadow_name, new_shadow_name_length }, "/etc/shadow"sv));
  289. #endif
  290. return {};
  291. // FIXME: Sync extra groups.
  292. }
  293. }