Account.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 DeprecatedString 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. // FIXME: change to TRY() and make method fallible
  34. auto salt_string = MUST(encode_base64({ random_data, sizeof(random_data) }));
  35. builder.append(salt_string);
  36. return builder.build();
  37. }
  38. static Vector<gid_t> get_extra_gids(passwd const& pwd)
  39. {
  40. StringView username { pwd.pw_name, strlen(pwd.pw_name) };
  41. Vector<gid_t> extra_gids;
  42. setgrent();
  43. for (auto* group = getgrent(); group; group = getgrent()) {
  44. if (group->gr_gid == pwd.pw_gid)
  45. continue;
  46. for (size_t i = 0; group->gr_mem[i]; ++i) {
  47. if (username == group->gr_mem[i]) {
  48. extra_gids.append(group->gr_gid);
  49. break;
  50. }
  51. }
  52. }
  53. endgrent();
  54. return extra_gids;
  55. }
  56. ErrorOr<Account> Account::from_passwd(passwd const& pwd, spwd const& spwd)
  57. {
  58. Account account(pwd, spwd, get_extra_gids(pwd));
  59. endpwent();
  60. #ifndef AK_OS_BSD_GENERIC
  61. endspent();
  62. #endif
  63. return account;
  64. }
  65. ErrorOr<Account> Account::self([[maybe_unused]] Read options)
  66. {
  67. Vector<gid_t> extra_gids = TRY(Core::System::getgroups());
  68. auto pwd = TRY(Core::System::getpwuid(getuid()));
  69. if (!pwd.has_value())
  70. return Error::from_string_literal("No such user");
  71. spwd spwd = {};
  72. #ifndef AK_OS_BSD_GENERIC
  73. if (options != Read::PasswdOnly) {
  74. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  75. if (!maybe_spwd.has_value())
  76. return Error::from_string_literal("No shadow entry for user");
  77. spwd = maybe_spwd.release_value();
  78. }
  79. #endif
  80. return Account(*pwd, spwd, extra_gids);
  81. }
  82. ErrorOr<Account> Account::from_name(StringView username, [[maybe_unused]] Read options)
  83. {
  84. auto pwd = TRY(Core::System::getpwnam(username));
  85. if (!pwd.has_value())
  86. return Error::from_string_literal("No such user");
  87. spwd spwd = {};
  88. #ifndef AK_OS_BSD_GENERIC
  89. if (options != Read::PasswdOnly) {
  90. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  91. if (!maybe_spwd.has_value())
  92. return Error::from_string_literal("No shadow entry for user");
  93. spwd = maybe_spwd.release_value();
  94. }
  95. #endif
  96. return from_passwd(*pwd, spwd);
  97. }
  98. ErrorOr<Account> Account::from_uid(uid_t uid, [[maybe_unused]] Read options)
  99. {
  100. auto pwd = TRY(Core::System::getpwuid(uid));
  101. if (!pwd.has_value())
  102. return Error::from_string_literal("No such user");
  103. spwd spwd = {};
  104. #ifndef AK_OS_BSD_GENERIC
  105. if (options != Read::PasswdOnly) {
  106. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  107. if (!maybe_spwd.has_value())
  108. return Error::from_string_literal("No shadow entry for user");
  109. spwd = maybe_spwd.release_value();
  110. }
  111. #endif
  112. return from_passwd(*pwd, spwd);
  113. }
  114. ErrorOr<Vector<Account>> Account::all([[maybe_unused]] Read options)
  115. {
  116. Vector<Account> accounts;
  117. char buffer[1024] = { 0 };
  118. ScopeGuard pwent_guard([] { endpwent(); });
  119. setpwent();
  120. while (true) {
  121. auto pwd = TRY(Core::System::getpwent({ buffer, sizeof(buffer) }));
  122. if (!pwd.has_value())
  123. break;
  124. spwd spwd = {};
  125. #ifndef AK_OS_BSD_GENERIC
  126. ScopeGuard spent_guard([] { endspent(); });
  127. if (options != Read::PasswdOnly) {
  128. auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
  129. if (!maybe_spwd.has_value())
  130. return Error::from_string_literal("No shadow entry for user");
  131. spwd = maybe_spwd.release_value();
  132. }
  133. #endif
  134. accounts.append({ *pwd, spwd, get_extra_gids(*pwd) });
  135. }
  136. return accounts;
  137. }
  138. bool Account::authenticate(SecretString const& password) const
  139. {
  140. // If there was no shadow entry for this account, authentication always fails.
  141. if (m_password_hash.is_null())
  142. return false;
  143. // An empty passwd field indicates that no password is required to log in.
  144. if (m_password_hash.is_empty())
  145. return true;
  146. // FIXME: Use crypt_r if it can be built in lagom.
  147. char* hash = crypt(password.characters(), m_password_hash.characters());
  148. return hash != nullptr && AK::timing_safe_compare(hash, m_password_hash.characters(), m_password_hash.length());
  149. }
  150. ErrorOr<void> Account::login() const
  151. {
  152. TRY(Core::System::setgroups(m_extra_gids));
  153. TRY(Core::System::setgid(m_gid));
  154. TRY(Core::System::setuid(m_uid));
  155. return {};
  156. }
  157. void Account::set_password(SecretString const& password)
  158. {
  159. m_password_hash = crypt(password.characters(), get_salt().characters());
  160. }
  161. void Account::set_password_enabled(bool enabled)
  162. {
  163. if (enabled && m_password_hash != "" && m_password_hash[0] == '!') {
  164. m_password_hash = m_password_hash.substring(1, m_password_hash.length() - 1);
  165. } else if (!enabled && (m_password_hash == "" || m_password_hash[0] != '!')) {
  166. StringBuilder builder;
  167. builder.append('!');
  168. builder.append(m_password_hash);
  169. m_password_hash = builder.build();
  170. }
  171. }
  172. void Account::delete_password()
  173. {
  174. m_password_hash = "";
  175. }
  176. Account::Account(passwd const& pwd, spwd const& spwd, Vector<gid_t> extra_gids)
  177. : m_username(pwd.pw_name)
  178. , m_password_hash(spwd.sp_pwdp)
  179. , m_uid(pwd.pw_uid)
  180. , m_gid(pwd.pw_gid)
  181. , m_gecos(pwd.pw_gecos)
  182. , m_home_directory(pwd.pw_dir)
  183. , m_shell(pwd.pw_shell)
  184. , m_extra_gids(move(extra_gids))
  185. {
  186. }
  187. ErrorOr<DeprecatedString> Account::generate_passwd_file() const
  188. {
  189. StringBuilder builder;
  190. char buffer[1024] = { 0 };
  191. ScopeGuard pwent_guard([] { endpwent(); });
  192. setpwent();
  193. while (true) {
  194. auto pwd = TRY(Core::System::getpwent({ buffer, sizeof(buffer) }));
  195. if (!pwd.has_value())
  196. break;
  197. if (pwd->pw_name == m_username) {
  198. if (m_deleted)
  199. continue;
  200. builder.appendff("{}:!:{}:{}:{}:{}:{}\n",
  201. m_username,
  202. m_uid, m_gid,
  203. m_gecos,
  204. m_home_directory,
  205. m_shell);
  206. } else {
  207. builder.appendff("{}:!:{}:{}:{}:{}:{}\n",
  208. pwd->pw_name, pwd->pw_uid,
  209. pwd->pw_gid, pwd->pw_gecos, pwd->pw_dir,
  210. pwd->pw_shell);
  211. }
  212. }
  213. return builder.to_deprecated_string();
  214. }
  215. #ifndef AK_OS_BSD_GENERIC
  216. ErrorOr<DeprecatedString> Account::generate_shadow_file() const
  217. {
  218. StringBuilder builder;
  219. setspent();
  220. struct spwd* p;
  221. errno = 0;
  222. while ((p = getspent())) {
  223. if (p->sp_namp == m_username) {
  224. if (m_deleted)
  225. continue;
  226. builder.appendff("{}:{}", m_username, m_password_hash);
  227. } else
  228. builder.appendff("{}:{}", p->sp_namp, p->sp_pwdp);
  229. builder.appendff(":{}:{}:{}:{}:{}:{}:{}\n",
  230. (p->sp_lstchg == -1) ? "" : DeprecatedString::formatted("{}", p->sp_lstchg),
  231. (p->sp_min == -1) ? "" : DeprecatedString::formatted("{}", p->sp_min),
  232. (p->sp_max == -1) ? "" : DeprecatedString::formatted("{}", p->sp_max),
  233. (p->sp_warn == -1) ? "" : DeprecatedString::formatted("{}", p->sp_warn),
  234. (p->sp_inact == -1) ? "" : DeprecatedString::formatted("{}", p->sp_inact),
  235. (p->sp_expire == -1) ? "" : DeprecatedString::formatted("{}", p->sp_expire),
  236. (p->sp_flag == 0) ? "" : DeprecatedString::formatted("{}", p->sp_flag));
  237. }
  238. endspent();
  239. if (errno)
  240. return Error::from_errno(errno);
  241. return builder.to_deprecated_string();
  242. }
  243. #endif
  244. ErrorOr<void> Account::sync()
  245. {
  246. Core::UmaskScope umask_scope(0777);
  247. auto new_passwd_file_content = TRY(generate_passwd_file());
  248. #ifndef AK_OS_BSD_GENERIC
  249. auto new_shadow_file_content = TRY(generate_shadow_file());
  250. #endif
  251. char new_passwd_file[] = "/etc/passwd.XXXXXX";
  252. #ifndef AK_OS_BSD_GENERIC
  253. char new_shadow_file[] = "/etc/shadow.XXXXXX";
  254. #endif
  255. {
  256. auto new_passwd_fd = TRY(Core::System::mkstemp(new_passwd_file));
  257. ScopeGuard new_passwd_fd_guard = [new_passwd_fd] { close(new_passwd_fd); };
  258. TRY(Core::System::fchmod(new_passwd_fd, 0644));
  259. #ifndef AK_OS_BSD_GENERIC
  260. auto new_shadow_fd = TRY(Core::System::mkstemp(new_shadow_file));
  261. ScopeGuard new_shadow_fd_guard = [new_shadow_fd] { close(new_shadow_fd); };
  262. TRY(Core::System::fchmod(new_shadow_fd, 0600));
  263. #endif
  264. auto nwritten = TRY(Core::System::write(new_passwd_fd, new_passwd_file_content.bytes()));
  265. VERIFY(static_cast<size_t>(nwritten) == new_passwd_file_content.length());
  266. #ifndef AK_OS_BSD_GENERIC
  267. nwritten = TRY(Core::System::write(new_shadow_fd, new_shadow_file_content.bytes()));
  268. VERIFY(static_cast<size_t>(nwritten) == new_shadow_file_content.length());
  269. #endif
  270. }
  271. auto new_passwd_file_view = StringView { new_passwd_file, sizeof(new_passwd_file) };
  272. TRY(Core::System::rename(new_passwd_file_view, "/etc/passwd"sv));
  273. #ifndef AK_OS_BSD_GENERIC
  274. auto new_shadow_file_view = StringView { new_shadow_file, sizeof(new_shadow_file) };
  275. TRY(Core::System::rename(new_shadow_file_view, "/etc/shadow"sv));
  276. #endif
  277. return {};
  278. // FIXME: Sync extra groups.
  279. }
  280. }