ladybird/Userland/Utilities/su.cpp

55 lines
1.6 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/ScopeGuard.h>
#include <LibCore/Account.h>
#include <LibCore/ArgsParser.h>
2020-07-25 18:36:32 -06:00
#include <LibCore/GetPassword.h>
2021-12-16 19:34:21 +01:00
#include <LibCore/System.h>
#include <LibMain/Main.h>
#include <stdio.h>
#include <unistd.h>
2021-12-16 19:34:21 +01:00
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
2021-12-16 19:34:21 +01:00
TRY(Core::System::pledge("stdio rpath tty exec id"));
2021-12-16 19:34:21 +01:00
if (!TRY(Core::System::isatty(STDIN_FILENO)))
return Error::from_string_literal("Standard input is not a terminal");
2022-04-01 20:58:27 +03:00
char const* user = nullptr;
Core::ArgsParser args_parser;
args_parser.add_positional_argument(user, "User to switch to (defaults to user with UID 0)", "user", Core::ArgsParser::Required::No);
2021-12-16 19:34:21 +01:00
args_parser.parse(arguments);
2021-12-16 19:34:21 +01:00
if (geteuid() != 0)
return Error::from_string_literal("Not running as root :(");
2021-12-16 19:34:21 +01:00
auto account = TRY(user ? Core::Account::from_name(user) : Core::Account::from_uid(0));
2021-12-16 19:34:21 +01:00
TRY(Core::System::pledge("stdio tty exec id"));
if (getuid() != 0 && account.has_password()) {
2021-12-16 19:34:21 +01:00
auto password = TRY(Core::get_password());
if (!account.authenticate(password))
return Error::from_string_literal("Incorrect or disabled password.");
2020-07-25 18:36:32 -06:00
}
2021-12-16 19:34:21 +01:00
TRY(Core::System::pledge("stdio exec id"));
if (!account.login()) {
perror("Core::Account::login");
return 1;
}
2021-12-16 19:34:21 +01:00
TRY(Core::System::pledge("stdio exec"));
execl(account.shell().characters(), account.shell().characters(), nullptr);
2019-02-21 23:49:16 +01:00
perror("execl");
return 1;
}