1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "dumpstate"
18 
19 #include "DumpstateInternal.h"
20 
21 #include <errno.h>
22 #include <grp.h>
23 #include <poll.h>
24 #include <pwd.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/capability.h>
29 #include <sys/prctl.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 
34 #include <cstdint>
35 #include <string>
36 #include <vector>
37 
38 #include <android-base/file.h>
39 #include <android-base/macros.h>
40 #include <log/log.h>
41 
Nanotime()42 uint64_t Nanotime() {
43     timespec ts;
44     clock_gettime(CLOCK_MONOTONIC, &ts);
45     return static_cast<uint64_t>(ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec);
46 }
47 
48 // Switches to non-root user and group.
DropRootUser()49 bool DropRootUser() {
50     struct group* grp = getgrnam("shell");
51     gid_t shell_gid = grp != nullptr ? grp->gr_gid : 0;
52     struct passwd* pwd = getpwnam("shell");
53     uid_t shell_uid = pwd != nullptr ? pwd->pw_uid : 0;
54 
55     if (!shell_gid || !shell_uid) {
56         MYLOGE("Unable to get AID_SHELL: %s\n", strerror(errno));
57         return false;
58     }
59 
60     if (getgid() == shell_gid && getuid() == shell_uid) {
61         MYLOGD("drop_root_user(): already running as Shell\n");
62         return true;
63     }
64     /* ensure we will keep capabilities when we drop root */
65     if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
66         MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
67         return false;
68     }
69 
70     static const std::vector<std::string> group_names{
71         "log", "sdcard_r", "sdcard_rw", "mount", "inet", "net_bw_stats", "readproc", "bluetooth"};
72     std::vector<gid_t> groups(group_names.size(), 0);
73     for (size_t i = 0; i < group_names.size(); ++i) {
74         grp = getgrnam(group_names[i].c_str());
75         groups[i] = grp != nullptr ? grp->gr_gid : 0;
76         if (groups[i] == 0) {
77             MYLOGE("Unable to get required gid '%s': %s\n", group_names[i].c_str(),
78                    strerror(errno));
79             return false;
80         }
81     }
82 
83     if (setgroups(groups.size(), groups.data()) != 0) {
84         MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
85         return false;
86     }
87     if (setgid(shell_gid) != 0) {
88         MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
89         return false;
90     }
91     if (setuid(shell_uid) != 0) {
92         MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
93         return false;
94     }
95 
96     struct __user_cap_header_struct capheader;
97     struct __user_cap_data_struct capdata[2];
98     memset(&capheader, 0, sizeof(capheader));
99     memset(&capdata, 0, sizeof(capdata));
100     capheader.version = _LINUX_CAPABILITY_VERSION_3;
101     capheader.pid = 0;
102 
103     if (capget(&capheader, &capdata[0]) != 0) {
104         MYLOGE("capget failed: %s\n", strerror(errno));
105         return false;
106     }
107 
108     const uint32_t cap_syslog_mask = CAP_TO_MASK(CAP_SYSLOG);
109     const uint32_t cap_syslog_index = CAP_TO_INDEX(CAP_SYSLOG);
110     bool has_cap_syslog = (capdata[cap_syslog_index].effective & cap_syslog_mask) != 0;
111 
112     memset(&capdata, 0, sizeof(capdata));
113     if (has_cap_syslog) {
114         // Only attempt to keep CAP_SYSLOG if it was present to begin with.
115         capdata[cap_syslog_index].permitted |= cap_syslog_mask;
116         capdata[cap_syslog_index].effective |= cap_syslog_mask;
117     }
118 
119     if (capset(&capheader, &capdata[0]) != 0) {
120         MYLOGE("capset({%#x, %#x}) failed: %s\n", capdata[0].effective,
121                capdata[1].effective, strerror(errno));
122         return false;
123     }
124 
125     return true;
126 }
127 
DumpFileFromFdToFd(const std::string & title,const std::string & path_string,int fd,int out_fd,bool dry_run)128 int DumpFileFromFdToFd(const std::string& title, const std::string& path_string, int fd, int out_fd,
129                        bool dry_run) {
130     const char* path = path_string.c_str();
131     if (!title.empty()) {
132         dprintf(out_fd, "------ %s (%s", title.c_str(), path);
133 
134         struct stat st;
135         // Only show the modification time of non-device files.
136         size_t path_len = strlen(path);
137         if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
138             (path_len < 5 || memcmp(path, "/sys/", 5)) &&
139             (path_len < 3 || memcmp(path, "/d/", 3)) && !fstat(fd, &st)) {
140             char stamp[80];
141             time_t mtime = st.st_mtime;
142             strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
143             dprintf(out_fd, ": %s", stamp);
144         }
145         dprintf(out_fd, ") ------\n");
146         fsync(out_fd);
147     }
148     if (dry_run) {
149         if (out_fd != STDOUT_FILENO) {
150             // There is no title, but we should still print a dry-run message
151             dprintf(out_fd, "%s: skipped on dry run\n", path);
152         } else if (!title.empty()) {
153             dprintf(out_fd, "\t(skipped on dry run)\n");
154         }
155         fsync(out_fd);
156         return 0;
157     }
158     bool newline = false;
159     while (true) {
160         uint64_t start_time = Nanotime();
161         pollfd fds[] = { { .fd = fd, .events = POLLIN } };
162         int ret = TEMP_FAILURE_RETRY(poll(fds, arraysize(fds), 30 * 1000));
163         if (ret == -1) {
164             dprintf(out_fd, "*** %s: poll failed: %s\n", path, strerror(errno));
165             newline = true;
166             break;
167         } else if (ret == 0) {
168             uint64_t elapsed = Nanotime() - start_time;
169             dprintf(out_fd, "*** %s: Timed out after %.3fs\n", path, (float)elapsed / NANOS_PER_SEC);
170             newline = true;
171             break;
172         } else {
173             char buffer[65536];
174             ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
175             if (bytes_read > 0) {
176                 android::base::WriteFully(out_fd, buffer, bytes_read);
177                 newline = (buffer[bytes_read - 1] == '\n');
178             } else {
179                 if (bytes_read == -1) {
180                     dprintf(out_fd, "*** %s: Failed to read from fd: %s", path, strerror(errno));
181                     newline = true;
182                 }
183                 break;
184             }
185         }
186     }
187 
188     if (!newline) dprintf(out_fd, "\n");
189     if (!title.empty()) dprintf(out_fd, "\n");
190     return 0;
191 }
192