1 /*
2  * Copyright (C) 2015 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 "cmd"
18 
19 #include <utils/Log.h>
20 #include <binder/Parcel.h>
21 #include <binder/ProcessState.h>
22 #include <binder/IResultReceiver.h>
23 #include <binder/IServiceManager.h>
24 #include <binder/IShellCallback.h>
25 #include <binder/TextOutput.h>
26 #include <utils/Condition.h>
27 #include <utils/Mutex.h>
28 #include <utils/Vector.h>
29 
30 #include <filesystem>
31 #include <getopt.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <sys/time.h>
38 #include <errno.h>
39 #include <memory>
40 
41 #include "selinux/selinux.h"
42 #include "selinux/android.h"
43 
44 #include "cmd.h"
45 
46 #define DEBUG 0
47 
48 using namespace android;
49 
sort_func(const String16 * lhs,const String16 * rhs)50 static int sort_func(const String16* lhs, const String16* rhs)
51 {
52     return lhs->compare(*rhs);
53 }
54 
55 struct SecurityContext_Delete {
operator ()SecurityContext_Delete56     void operator()(char* p) const {
57         freecon(p);
58     }
59 };
60 typedef std::unique_ptr<char[], SecurityContext_Delete> Unique_SecurityContext;
61 
62 class MyShellCallback : public BnShellCallback
63 {
64 public:
65     TextOutput& mErrorLog;
66     bool mActive = true;
67 
MyShellCallback(TextOutput & errorLog)68     MyShellCallback(TextOutput& errorLog) : mErrorLog(errorLog) {}
69 
openFile(const String16 & path,const String16 & seLinuxContext,const String16 & mode)70     virtual int openFile(const String16& path, const String16& seLinuxContext,
71             const String16& mode) {
72         String8 path8(path);
73         auto fullPath = std::filesystem::current_path();
74         fullPath /= path8.c_str();
75         if (!mActive) {
76             mErrorLog << "Open attempt after active for: " << fullPath << endl;
77             return -EPERM;
78         }
79 #if DEBUG
80         ALOGD("openFile: %s, full=%s", path8.c_str(), fullPath.c_str());
81 #endif
82         int flags = 0;
83         bool checkRead = false;
84         bool checkWrite = false;
85         if (mode == u"w") {
86             flags = O_WRONLY|O_CREAT|O_TRUNC;
87             checkWrite = true;
88         } else if (mode == u"w+") {
89             flags = O_RDWR|O_CREAT|O_TRUNC;
90             checkRead = checkWrite = true;
91         } else if (mode == u"r") {
92             flags = O_RDONLY;
93             checkRead = true;
94         } else if (mode == u"r+") {
95             flags = O_RDWR;
96             checkRead = checkWrite = true;
97         } else {
98             mErrorLog << "Invalid mode requested: " << mode << endl;
99             return -EINVAL;
100         }
101         int fd = open(fullPath.c_str(), flags, S_IRWXU|S_IRWXG);
102 #if DEBUG
103         ALOGD("openFile: fd=%d", fd);
104 #endif
105         if (fd < 0) {
106             return fd;
107         }
108         if (is_selinux_enabled() && seLinuxContext.size() > 0) {
109             String8 seLinuxContext8(seLinuxContext);
110             char* tmp = nullptr;
111             getfilecon(fullPath.c_str(), &tmp);
112             Unique_SecurityContext context(tmp);
113             if (checkWrite) {
114                 int accessGranted = selinux_check_access(seLinuxContext8.c_str(), context.get(),
115                         "file", "write", nullptr);
116                 if (accessGranted != 0) {
117 #if DEBUG
118                     ALOGD("openFile: failed selinux write check!");
119 #endif
120                     close(fd);
121                     mErrorLog << "System server has no access to write file context " << context.get() << " (from path " << fullPath.c_str() << ", context " << seLinuxContext8.c_str() << ")" << endl;
122                     return -EPERM;
123                 }
124             }
125             if (checkRead) {
126                 int accessGranted = selinux_check_access(seLinuxContext8.c_str(), context.get(),
127                         "file", "read", nullptr);
128                 if (accessGranted != 0) {
129 #if DEBUG
130                     ALOGD("openFile: failed selinux read check!");
131 #endif
132                     close(fd);
133                     mErrorLog << "System server has no access to read file context " << context.get() << " (from path " << fullPath.c_str() << ", context " << seLinuxContext8.c_str() << ")" << endl;
134                     return -EPERM;
135                 }
136             }
137         }
138         return fd;
139     }
140 };
141 
142 class MyResultReceiver : public BnResultReceiver
143 {
144 public:
145     Mutex mMutex;
146     Condition mCondition;
147     bool mHaveResult = false;
148     int32_t mResult = 0;
149 
send(int32_t resultCode)150     virtual void send(int32_t resultCode) {
151         AutoMutex _l(mMutex);
152         mResult = resultCode;
153         mHaveResult = true;
154         mCondition.signal();
155     }
156 
waitForResult()157     int32_t waitForResult() {
158         AutoMutex _l(mMutex);
159         while (!mHaveResult) {
160             mCondition.wait(mMutex);
161         }
162         return mResult;
163     }
164 };
165 
cmdMain(const std::vector<std::string_view> & argv,TextOutput & outputLog,TextOutput & errorLog,int in,int out,int err,RunMode runMode)166 int cmdMain(const std::vector<std::string_view>& argv, TextOutput& outputLog, TextOutput& errorLog,
167             int in, int out, int err, RunMode runMode) {
168     sp<ProcessState> proc = ProcessState::self();
169     proc->startThreadPool();
170 
171 #if DEBUG
172     ALOGD("cmd: starting");
173 #endif
174     sp<IServiceManager> sm = defaultServiceManager();
175     if (runMode == RunMode::kStandalone) {
176         fflush(stdout);
177     }
178     if (sm == nullptr) {
179         ALOGW("Unable to get default service manager!");
180         errorLog << "cmd: Unable to get default service manager!" << endl;
181         return 20;
182     }
183 
184     int argc = argv.size();
185 
186     if (argc == 0) {
187         errorLog << "cmd: No service specified; use -l to list all running services. Use -w to start and wait for a service." << endl;
188         return 20;
189     }
190 
191     if ((argc == 1) && (argv[0] == "-l")) {
192         Vector<String16> services = sm->listServices();
193         services.sort(sort_func);
194         outputLog << "Currently running services:" << endl;
195 
196         for (size_t i=0; i<services.size(); i++) {
197             sp<IBinder> service = sm->checkService(services[i]);
198             if (service != nullptr) {
199                 outputLog << "  " << services[i] << endl;
200             }
201         }
202         return 0;
203     }
204 
205     bool waitForService = ((argc > 1) && (argv[0] == "-w"));
206     int serviceIdx = (waitForService) ? 1 : 0;
207     const auto cmd = argv[serviceIdx];
208 
209     Vector<String16> args;
210     String16 serviceName = String16(cmd.data(), cmd.size());
211     for (int i = serviceIdx + 1; i < argc; i++) {
212         args.add(String16(argv[i].data(), argv[i].size()));
213     }
214     sp<IBinder> service;
215     if(waitForService) {
216         service = sm->waitForService(serviceName);
217     } else {
218         service = sm->checkService(serviceName);
219     }
220 
221     if (service == nullptr) {
222         if (runMode == RunMode::kStandalone) {
223             ALOGW("Can't find service %.*s", static_cast<int>(cmd.size()), cmd.data());
224         }
225         errorLog << "cmd: Can't find service: " << cmd << endl;
226         return 20;
227     }
228 
229     sp<MyShellCallback> cb = new MyShellCallback(errorLog);
230     sp<MyResultReceiver> result = new MyResultReceiver();
231 
232 #if DEBUG
233     ALOGD("cmd: Invoking %.*s in=%d, out=%d, err=%d",
234           static_cast<int>(cmd.size()), cmd.data(), in, out, err);
235 #endif
236 
237     // TODO: block until a result is returned to MyResultReceiver.
238     status_t error = IBinder::shellCommand(service, in, out, err, args, cb, result);
239     if (error < 0) {
240         const char* errstr;
241         switch (error) {
242             case BAD_TYPE: errstr = "Bad type"; break;
243             case FAILED_TRANSACTION: errstr = "Failed transaction"; break;
244             case FDS_NOT_ALLOWED: errstr = "File descriptors not allowed"; break;
245             case UNEXPECTED_NULL: errstr = "Unexpected null"; break;
246             default: errstr = strerror(-error); break;
247         }
248         if (runMode == RunMode::kStandalone) {
249             ALOGW("Failure calling service %.*s: %s (%d)", static_cast<int>(cmd.size()), cmd.data(),
250                   errstr, -error);
251         }
252         outputLog << "cmd: Failure calling service " << cmd << ": " << errstr << " (" << (-error)
253                   << ")" << endl;
254         return error;
255     }
256 
257     cb->mActive = false;
258     status_t res = result->waitForResult();
259 #if DEBUG
260     ALOGD("result=%d", (int)res);
261 #endif
262     return res;
263 }
264