blob: 092c51ceb376349fba76d6bd62382f833ff81a1f [file] [log] [blame]
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001/*
2 * Copyright (C) 2017 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#include "subcontext.h"
18
19#include <fcntl.h>
20#include <poll.h>
21#include <sys/socket.h>
22#include <unistd.h>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
26#include <android-base/strings.h>
27#include <selinux/android.h>
28
29#include "action.h"
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070030#include "util.h"
31
Tom Cherryde6bd502018-02-13 16:50:08 -080032#if defined(__ANDROID__)
Tom Cherry40acb372018-08-01 13:41:12 -070033#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080034#include "property_service.h"
35#include "selinux.h"
36#else
37#include "host_init_stubs.h"
38#endif
Tom Cherry32228482018-01-18 16:14:25 -080039
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070040using android::base::GetExecutablePath;
41using android::base::Join;
42using android::base::Socketpair;
43using android::base::Split;
44using android::base::StartsWith;
45using android::base::unique_fd;
46
47namespace android {
48namespace init {
49
Tom Cherryac7428b2017-10-02 16:59:02 -070050const std::string kInitContext = "u:r:init:s0";
51const std::string kVendorContext = "u:r:vendor_init:s0";
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070052
Tom Cherrydc375862018-02-28 10:39:01 -080053const char* const paths_and_secontexts[2][2] = {
54 {"/vendor", kVendorContext.c_str()},
55 {"/odm", kVendorContext.c_str()},
56};
57
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070058namespace {
59
60constexpr size_t kBufferSize = 4096;
61
62Result<std::string> ReadMessage(int socket) {
63 char buffer[kBufferSize] = {};
64 auto result = TEMP_FAILURE_RETRY(recv(socket, buffer, sizeof(buffer), 0));
Luis Hector Chavez72353592018-09-21 12:27:02 -070065 if (result == 0) {
66 return Error();
67 } else if (result < 0) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070068 return ErrnoError();
69 }
70 return std::string(buffer, result);
71}
72
73template <typename T>
74Result<Success> SendMessage(int socket, const T& message) {
75 std::string message_string;
76 if (!message.SerializeToString(&message_string)) {
77 return Error() << "Unable to serialize message";
78 }
79
80 if (message_string.size() > kBufferSize) {
81 return Error() << "Serialized message too long to send";
82 }
83
84 if (auto result =
85 TEMP_FAILURE_RETRY(send(socket, message_string.c_str(), message_string.size(), 0));
86 result != static_cast<long>(message_string.size())) {
87 return ErrnoError() << "send() failed to send message contents";
88 }
89 return Success();
90}
91
Tom Cherry32228482018-01-18 16:14:25 -080092std::vector<std::pair<std::string, std::string>> properties_to_set;
93
94uint32_t SubcontextPropertySet(const std::string& name, const std::string& value) {
95 properties_to_set.emplace_back(name, value);
Tom Cherryde6bd502018-02-13 16:50:08 -080096 return 0;
Tom Cherry32228482018-01-18 16:14:25 -080097}
98
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070099class SubcontextProcess {
100 public:
101 SubcontextProcess(const KeywordFunctionMap* function_map, std::string context, int init_fd)
102 : function_map_(function_map), context_(std::move(context)), init_fd_(init_fd){};
103 void MainLoop();
104
105 private:
106 void RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -0800107 SubcontextReply* reply) const;
108 void ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
109 SubcontextReply* reply) const;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700110
111 const KeywordFunctionMap* function_map_;
112 const std::string context_;
113 const int init_fd_;
114};
115
116void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -0800117 SubcontextReply* reply) const {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700118 // Need to use ArraySplice instead of this code.
119 auto args = std::vector<std::string>();
120 for (const auto& string : execute_command.args()) {
121 args.emplace_back(string);
122 }
123
124 auto map_result = function_map_->FindFunction(args);
125 Result<Success> result;
126 if (!map_result) {
127 result = Error() << "Cannot find command: " << map_result.error();
128 } else {
129 result = RunBuiltinFunction(map_result->second, args, context_);
130 }
131
Tom Cherry32228482018-01-18 16:14:25 -0800132 for (const auto& [name, value] : properties_to_set) {
133 auto property = reply->add_properties_to_set();
134 property->set_name(name);
135 property->set_value(value);
136 }
137
138 properties_to_set.clear();
139
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700140 if (result) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800141 reply->set_success(true);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700142 } else {
Tom Cherryc49719f2018-01-10 11:04:34 -0800143 auto* failure = reply->mutable_failure();
144 failure->set_error_string(result.error_string());
145 failure->set_error_errno(result.error_errno());
146 }
147}
148
149void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
150 SubcontextReply* reply) const {
151 for (const auto& arg : expand_args_command.args()) {
152 auto expanded_prop = std::string{};
153 if (!expand_props(arg, &expanded_prop)) {
154 auto* failure = reply->mutable_failure();
155 failure->set_error_string("Failed to expand '" + arg + "'");
156 failure->set_error_errno(0);
157 return;
158 } else {
159 auto* expand_args_reply = reply->mutable_expand_args_reply();
160 expand_args_reply->add_expanded_args(expanded_prop);
161 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700162 }
163}
164
165void SubcontextProcess::MainLoop() {
166 pollfd ufd[1];
167 ufd[0].events = POLLIN;
168 ufd[0].fd = init_fd_;
169
170 while (true) {
171 ufd[0].revents = 0;
172 int nr = TEMP_FAILURE_RETRY(poll(ufd, arraysize(ufd), -1));
173 if (nr == 0) continue;
174 if (nr < 0) {
175 PLOG(FATAL) << "poll() of subcontext socket failed, continuing";
176 }
177
178 auto init_message = ReadMessage(init_fd_);
179 if (!init_message) {
Luis Hector Chavez72353592018-09-21 12:27:02 -0700180 if (init_message.error_errno() == 0) {
181 // If the init file descriptor was closed, let's exit quietly. If
182 // this was accidental, init will restart us. If init died, this
183 // avoids calling abort(3) unnecessarily.
184 return;
185 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700186 LOG(FATAL) << "Could not read message from init: " << init_message.error();
187 }
188
189 auto subcontext_command = SubcontextCommand();
190 if (!subcontext_command.ParseFromString(*init_message)) {
191 LOG(FATAL) << "Unable to parse message from init";
192 }
193
194 auto reply = SubcontextReply();
195 switch (subcontext_command.command_case()) {
196 case SubcontextCommand::kExecuteCommand: {
Tom Cherryc49719f2018-01-10 11:04:34 -0800197 RunCommand(subcontext_command.execute_command(), &reply);
198 break;
199 }
200 case SubcontextCommand::kExpandArgsCommand: {
201 ExpandArgs(subcontext_command.expand_args_command(), &reply);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700202 break;
203 }
204 default:
205 LOG(FATAL) << "Unknown message type from init: "
206 << subcontext_command.command_case();
207 }
208
209 if (auto result = SendMessage(init_fd_, reply); !result) {
210 LOG(FATAL) << "Failed to send message to init: " << result.error();
211 }
212 }
213}
214
215} // namespace
216
217int SubcontextMain(int argc, char** argv, const KeywordFunctionMap* function_map) {
218 if (argc < 4) LOG(FATAL) << "Fewer than 4 args specified to subcontext (" << argc << ")";
219
220 auto context = std::string(argv[2]);
221 auto init_fd = std::atoi(argv[3]);
222
Tom Cherry0d1452e2017-10-19 14:39:35 -0700223 SelabelInitialize();
Tom Cherry32228482018-01-18 16:14:25 -0800224
225 property_set = SubcontextPropertySet;
226
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700227 auto subcontext_process = SubcontextProcess(function_map, context, init_fd);
228 subcontext_process.MainLoop();
229 return 0;
230}
231
232void Subcontext::Fork() {
233 unique_fd subcontext_socket;
234 if (!Socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, &socket_, &subcontext_socket)) {
235 LOG(FATAL) << "Could not create socket pair to communicate to subcontext";
236 return;
237 }
238
239 auto result = fork();
240
241 if (result == -1) {
242 LOG(FATAL) << "Could not fork subcontext";
243 } else if (result == 0) {
244 socket_.reset();
245
246 // We explicitly do not use O_CLOEXEC here, such that we can reference this FD by number
247 // in the subcontext process after we exec.
248 int child_fd = dup(subcontext_socket);
249 if (child_fd < 0) {
250 PLOG(FATAL) << "Could not dup child_fd";
251 }
252
253 if (setexeccon(context_.c_str()) < 0) {
254 PLOG(FATAL) << "Could not set execcon for '" << context_ << "'";
255 }
256
257 auto init_path = GetExecutablePath();
258 auto child_fd_string = std::to_string(child_fd);
259 const char* args[] = {init_path.c_str(), "subcontext", context_.c_str(),
260 child_fd_string.c_str(), nullptr};
261 execv(init_path.data(), const_cast<char**>(args));
262
263 PLOG(FATAL) << "Could not execv subcontext init";
264 } else {
265 subcontext_socket.reset();
266 pid_ = result;
267 LOG(INFO) << "Forked subcontext for '" << context_ << "' with pid " << pid_;
268 }
269}
270
271void Subcontext::Restart() {
272 LOG(ERROR) << "Restarting subcontext '" << context_ << "'";
273 if (pid_) {
274 kill(pid_, SIGKILL);
275 }
276 pid_ = 0;
277 socket_.reset();
278 Fork();
279}
280
Tom Cherryc49719f2018-01-10 11:04:34 -0800281Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700282 if (auto result = SendMessage(socket_, subcontext_command); !result) {
283 Restart();
284 return ErrnoError() << "Failed to send message to subcontext";
285 }
286
287 auto subcontext_message = ReadMessage(socket_);
288 if (!subcontext_message) {
289 Restart();
290 return Error() << "Failed to receive result from subcontext: " << subcontext_message.error();
291 }
292
Tom Cherryc49719f2018-01-10 11:04:34 -0800293 auto subcontext_reply = SubcontextReply{};
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700294 if (!subcontext_reply.ParseFromString(*subcontext_message)) {
295 Restart();
296 return Error() << "Unable to parse message from subcontext";
297 }
Tom Cherryc49719f2018-01-10 11:04:34 -0800298 return subcontext_reply;
299}
300
301Result<Success> Subcontext::Execute(const std::vector<std::string>& args) {
302 auto subcontext_command = SubcontextCommand();
303 std::copy(
304 args.begin(), args.end(),
305 RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
306
307 auto subcontext_reply = TransmitMessage(subcontext_command);
308 if (!subcontext_reply) {
309 return subcontext_reply.error();
310 }
311
Tom Cherry32228482018-01-18 16:14:25 -0800312 for (const auto& property : subcontext_reply->properties_to_set()) {
313 ucred cr = {.pid = pid_, .uid = 0, .gid = 0};
Tom Cherry69d47aa2018-03-01 11:00:57 -0800314 std::string error;
315 if (HandlePropertySet(property.name(), property.value(), context_, cr, &error) != 0) {
316 LOG(ERROR) << "Subcontext init could not set '" << property.name() << "' to '"
317 << property.value() << "': " << error;
318 }
Tom Cherry32228482018-01-18 16:14:25 -0800319 }
320
321 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
322 auto& failure = subcontext_reply->failure();
323 return ResultError(failure.error_string(), failure.error_errno());
324 }
325
Tom Cherryc49719f2018-01-10 11:04:34 -0800326 if (subcontext_reply->reply_case() != SubcontextReply::kSuccess) {
327 return Error() << "Unexpected message type from subcontext: "
328 << subcontext_reply->reply_case();
329 }
330
331 return Success();
332}
333
334Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::string>& args) {
335 auto subcontext_command = SubcontextCommand{};
336 std::copy(args.begin(), args.end(),
337 RepeatedPtrFieldBackInserter(
338 subcontext_command.mutable_expand_args_command()->mutable_args()));
339
340 auto subcontext_reply = TransmitMessage(subcontext_command);
341 if (!subcontext_reply) {
342 return subcontext_reply.error();
343 }
344
Tom Cherry32228482018-01-18 16:14:25 -0800345 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
346 auto& failure = subcontext_reply->failure();
347 return ResultError(failure.error_string(), failure.error_errno());
348 }
349
Tom Cherryc49719f2018-01-10 11:04:34 -0800350 if (subcontext_reply->reply_case() != SubcontextReply::kExpandArgsReply) {
351 return Error() << "Unexpected message type from subcontext: "
352 << subcontext_reply->reply_case();
353 }
354
355 auto& reply = subcontext_reply->expand_args_reply();
356 auto expanded_args = std::vector<std::string>{};
357 for (const auto& string : reply.expanded_args()) {
358 expanded_args.emplace_back(string);
359 }
360 return expanded_args;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700361}
362
363static std::vector<Subcontext> subcontexts;
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700364static bool shutting_down;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700365
366std::vector<Subcontext>* InitializeSubcontexts() {
Tom Cherry40acb372018-08-01 13:41:12 -0700367 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherrya1dbeb82018-04-11 15:50:00 -0700368 for (const auto& [path_prefix, secontext] : paths_and_secontexts) {
369 subcontexts.emplace_back(path_prefix, secontext);
370 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700371 }
372 return &subcontexts;
373}
374
375bool SubcontextChildReap(pid_t pid) {
376 for (auto& subcontext : subcontexts) {
377 if (subcontext.pid() == pid) {
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700378 if (!shutting_down) {
379 subcontext.Restart();
380 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700381 return true;
382 }
383 }
384 return false;
385}
386
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700387void SubcontextTerminate() {
388 shutting_down = true;
389 for (auto& subcontext : subcontexts) {
390 kill(subcontext.pid(), SIGTERM);
391 }
392}
393
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700394} // namespace init
395} // namespace android