summaryrefslogtreecommitdiff
path: root/Tests/Kernel/TestKernelFilePermissions.cpp
blob: fa1edef211b0340e4da868aff01c0e817bf625f8 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
 * Copyright (c) 2020-2021, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/String.h>
#include <LibCore/File.h>
#include <LibTest/TestCase.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

TEST_CASE(test_change_file_contents)
{
    char path[] = "/tmp/suid.XXXXXX";
    auto fd = mkstemp(path);
    EXPECT(fd != -1);
    ftruncate(fd, 0);
    EXPECT(fchmod(fd, 06755) != -1);

    char buffer[8] {};
    write(fd, buffer, sizeof(buffer));

    struct stat s;
    EXPECT(fstat(fd, &s) != -1);
    close(fd);
    unlink(path);

    EXPECT(!(s.st_mode & S_ISUID));
    EXPECT(!(s.st_mode & S_ISGID));
}

TEST_CASE(test_change_file_ownership)
{
    char path[] = "/tmp/suid.XXXXXX";
    auto fd = mkstemp(path);
    EXPECT(fd != -1);
    ftruncate(fd, 0);
    EXPECT(fchmod(fd, 06755) != -1);

    fchown(fd, getuid(), getgid());

    struct stat s;
    EXPECT(fstat(fd, &s) != -1);
    close(fd);
    unlink(path);

    EXPECT(!(s.st_mode & S_ISUID));
    EXPECT(!(s.st_mode & S_ISGID));
}

TEST_CASE(test_change_file_permissions)
{
    char path[] = "/tmp/suid.XXXXXX";
    auto fd = mkstemp(path);
    EXPECT(fd != -1);
    ftruncate(fd, 0);
    EXPECT(fchmod(fd, 06755) != -1);

    fchmod(fd, 0755);

    struct stat s;
    EXPECT(fstat(fd, &s) != -1);
    close(fd);
    unlink(path);

    EXPECT(!(s.st_mode & S_ISUID));
    EXPECT(!(s.st_mode & S_ISGID));
}

TEST_CASE(test_change_file_location)
{
    char path[] = "/tmp/suid.XXXXXX";
    auto fd = mkstemp(path);
    EXPECT(fd != -1);
    ftruncate(fd, 0);
    EXPECT(fchmod(fd, 06755) != -1);

    auto suid_path = Core::File::read_link(String::formatted("/proc/{}/fd/{}", getpid(), fd));
    EXPECT(suid_path.characters());
    auto new_path = String::formatted("{}.renamed", suid_path);

    rename(suid_path.characters(), new_path.characters());

    struct stat s;
    EXPECT(lstat(new_path.characters(), &s) != -1);
    close(fd);
    unlink(path);

    // Renamed file should retain set-uid/set-gid permissions
    EXPECT(s.st_mode & S_ISUID);
    EXPECT(s.st_mode & S_ISGID);

    unlink(new_path.characters());
}