Account.cpp 10 KB

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