summaryrefslogtreecommitdiff
path: root/Userland/Utilities/su.cpp
blob: 382ae1e6b51dcadf2f3f51e9e38c72c516cea4c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * 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>
#include <LibCore/GetPassword.h>
#include <LibCore/System.h>
#include <LibMain/Main.h>
#include <stdio.h>
#include <unistd.h>

ErrorOr<int> serenity_main(Main::Arguments arguments)
{
    TRY(Core::System::pledge("stdio rpath tty exec id"));

    if (!TRY(Core::System::isatty(STDIN_FILENO)))
        return Error::from_string_literal("Standard input is not a terminal");

    const char* 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);
    args_parser.parse(arguments);

    if (geteuid() != 0)
        return Error::from_string_literal("Not running as root :(");

    auto account = TRY(user ? Core::Account::from_name(user) : Core::Account::from_uid(0));

    TRY(Core::System::pledge("stdio tty exec id"));

    if (getuid() != 0 && account.has_password()) {
        auto password = TRY(Core::get_password());
        if (!account.authenticate(password))
            return Error::from_string_literal("Incorrect or disabled password.");
    }

    TRY(Core::System::pledge("stdio exec id"));

    if (!account.login()) {
        perror("Core::Account::login");
        return 1;
    }

    TRY(Core::System::pledge("stdio exec"));

    execl(account.shell().characters(), account.shell().characters(), nullptr);
    perror("execl");
    return 1;
}