blob: faab3684874476e22d45ce851e329e2f69167411 [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__)
33#include "property_service.h"
34#include "selinux.h"
35#else
36#include "host_init_stubs.h"
37#endif
Tom Cherry32228482018-01-18 16:14:25 -080038
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070039using android::base::GetExecutablePath;
40using android::base::Join;
41using android::base::Socketpair;
42using android::base::Split;
43using android::base::StartsWith;
44using android::base::unique_fd;
45
46namespace android {
47namespace init {
48
Tom Cherryac7428b2017-10-02 16:59:02 -070049const std::string kInitContext = "u:r:init:s0";
50const std::string kVendorContext = "u:r:vendor_init:s0";
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070051
52namespace {
53
54constexpr size_t kBufferSize = 4096;
55
56Result<std::string> ReadMessage(int socket) {
57 char buffer[kBufferSize] = {};
58 auto result = TEMP_FAILURE_RETRY(recv(socket, buffer, sizeof(buffer), 0));
59 if (result <= 0) {
60 return ErrnoError();
61 }
62 return std::string(buffer, result);
63}
64
65template <typename T>
66Result<Success> SendMessage(int socket, const T& message) {
67 std::string message_string;
68 if (!message.SerializeToString(&message_string)) {
69 return Error() << "Unable to serialize message";
70 }
71
72 if (message_string.size() > kBufferSize) {
73 return Error() << "Serialized message too long to send";
74 }
75
76 if (auto result =
77 TEMP_FAILURE_RETRY(send(socket, message_string.c_str(), message_string.size(), 0));
78 result != static_cast<long>(message_string.size())) {
79 return ErrnoError() << "send() failed to send message contents";
80 }
81 return Success();
82}
83
Tom Cherry32228482018-01-18 16:14:25 -080084std::vector<std::pair<std::string, std::string>> properties_to_set;
85
86uint32_t SubcontextPropertySet(const std::string& name, const std::string& value) {
87 properties_to_set.emplace_back(name, value);
Tom Cherryde6bd502018-02-13 16:50:08 -080088 return 0;
Tom Cherry32228482018-01-18 16:14:25 -080089}
90
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070091class SubcontextProcess {
92 public:
93 SubcontextProcess(const KeywordFunctionMap* function_map, std::string context, int init_fd)
94 : function_map_(function_map), context_(std::move(context)), init_fd_(init_fd){};
95 void MainLoop();
96
97 private:
98 void RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -080099 SubcontextReply* reply) const;
100 void ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
101 SubcontextReply* reply) const;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700102
103 const KeywordFunctionMap* function_map_;
104 const std::string context_;
105 const int init_fd_;
106};
107
108void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -0800109 SubcontextReply* reply) const {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700110 // Need to use ArraySplice instead of this code.
111 auto args = std::vector<std::string>();
112 for (const auto& string : execute_command.args()) {
113 args.emplace_back(string);
114 }
115
116 auto map_result = function_map_->FindFunction(args);
117 Result<Success> result;
118 if (!map_result) {
119 result = Error() << "Cannot find command: " << map_result.error();
120 } else {
121 result = RunBuiltinFunction(map_result->second, args, context_);
122 }
123
Tom Cherry32228482018-01-18 16:14:25 -0800124 for (const auto& [name, value] : properties_to_set) {
125 auto property = reply->add_properties_to_set();
126 property->set_name(name);
127 property->set_value(value);
128 }
129
130 properties_to_set.clear();
131
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700132 if (result) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800133 reply->set_success(true);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700134 } else {
Tom Cherryc49719f2018-01-10 11:04:34 -0800135 auto* failure = reply->mutable_failure();
136 failure->set_error_string(result.error_string());
137 failure->set_error_errno(result.error_errno());
138 }
139}
140
141void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
142 SubcontextReply* reply) const {
143 for (const auto& arg : expand_args_command.args()) {
144 auto expanded_prop = std::string{};
145 if (!expand_props(arg, &expanded_prop)) {
146 auto* failure = reply->mutable_failure();
147 failure->set_error_string("Failed to expand '" + arg + "'");
148 failure->set_error_errno(0);
149 return;
150 } else {
151 auto* expand_args_reply = reply->mutable_expand_args_reply();
152 expand_args_reply->add_expanded_args(expanded_prop);
153 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700154 }
155}
156
157void SubcontextProcess::MainLoop() {
158 pollfd ufd[1];
159 ufd[0].events = POLLIN;
160 ufd[0].fd = init_fd_;
161
162 while (true) {
163 ufd[0].revents = 0;
164 int nr = TEMP_FAILURE_RETRY(poll(ufd, arraysize(ufd), -1));
165 if (nr == 0) continue;
166 if (nr < 0) {
167 PLOG(FATAL) << "poll() of subcontext socket failed, continuing";
168 }
169
170 auto init_message = ReadMessage(init_fd_);
171 if (!init_message) {
172 LOG(FATAL) << "Could not read message from init: " << init_message.error();
173 }
174
175 auto subcontext_command = SubcontextCommand();
176 if (!subcontext_command.ParseFromString(*init_message)) {
177 LOG(FATAL) << "Unable to parse message from init";
178 }
179
180 auto reply = SubcontextReply();
181 switch (subcontext_command.command_case()) {
182 case SubcontextCommand::kExecuteCommand: {
Tom Cherryc49719f2018-01-10 11:04:34 -0800183 RunCommand(subcontext_command.execute_command(), &reply);
184 break;
185 }
186 case SubcontextCommand::kExpandArgsCommand: {
187 ExpandArgs(subcontext_command.expand_args_command(), &reply);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700188 break;
189 }
190 default:
191 LOG(FATAL) << "Unknown message type from init: "
192 << subcontext_command.command_case();
193 }
194
195 if (auto result = SendMessage(init_fd_, reply); !result) {
196 LOG(FATAL) << "Failed to send message to init: " << result.error();
197 }
198 }
199}
200
201} // namespace
202
203int SubcontextMain(int argc, char** argv, const KeywordFunctionMap* function_map) {
204 if (argc < 4) LOG(FATAL) << "Fewer than 4 args specified to subcontext (" << argc << ")";
205
206 auto context = std::string(argv[2]);
207 auto init_fd = std::atoi(argv[3]);
208
Tom Cherry0d1452e2017-10-19 14:39:35 -0700209 SelabelInitialize();
Tom Cherry32228482018-01-18 16:14:25 -0800210
211 property_set = SubcontextPropertySet;
212
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700213 auto subcontext_process = SubcontextProcess(function_map, context, init_fd);
214 subcontext_process.MainLoop();
215 return 0;
216}
217
218void Subcontext::Fork() {
219 unique_fd subcontext_socket;
220 if (!Socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, &socket_, &subcontext_socket)) {
221 LOG(FATAL) << "Could not create socket pair to communicate to subcontext";
222 return;
223 }
224
225 auto result = fork();
226
227 if (result == -1) {
228 LOG(FATAL) << "Could not fork subcontext";
229 } else if (result == 0) {
230 socket_.reset();
231
232 // We explicitly do not use O_CLOEXEC here, such that we can reference this FD by number
233 // in the subcontext process after we exec.
234 int child_fd = dup(subcontext_socket);
235 if (child_fd < 0) {
236 PLOG(FATAL) << "Could not dup child_fd";
237 }
238
239 if (setexeccon(context_.c_str()) < 0) {
240 PLOG(FATAL) << "Could not set execcon for '" << context_ << "'";
241 }
242
243 auto init_path = GetExecutablePath();
244 auto child_fd_string = std::to_string(child_fd);
245 const char* args[] = {init_path.c_str(), "subcontext", context_.c_str(),
246 child_fd_string.c_str(), nullptr};
247 execv(init_path.data(), const_cast<char**>(args));
248
249 PLOG(FATAL) << "Could not execv subcontext init";
250 } else {
251 subcontext_socket.reset();
252 pid_ = result;
253 LOG(INFO) << "Forked subcontext for '" << context_ << "' with pid " << pid_;
254 }
255}
256
257void Subcontext::Restart() {
258 LOG(ERROR) << "Restarting subcontext '" << context_ << "'";
259 if (pid_) {
260 kill(pid_, SIGKILL);
261 }
262 pid_ = 0;
263 socket_.reset();
264 Fork();
265}
266
Tom Cherryc49719f2018-01-10 11:04:34 -0800267Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700268 if (auto result = SendMessage(socket_, subcontext_command); !result) {
269 Restart();
270 return ErrnoError() << "Failed to send message to subcontext";
271 }
272
273 auto subcontext_message = ReadMessage(socket_);
274 if (!subcontext_message) {
275 Restart();
276 return Error() << "Failed to receive result from subcontext: " << subcontext_message.error();
277 }
278
Tom Cherryc49719f2018-01-10 11:04:34 -0800279 auto subcontext_reply = SubcontextReply{};
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700280 if (!subcontext_reply.ParseFromString(*subcontext_message)) {
281 Restart();
282 return Error() << "Unable to parse message from subcontext";
283 }
Tom Cherryc49719f2018-01-10 11:04:34 -0800284 return subcontext_reply;
285}
286
287Result<Success> Subcontext::Execute(const std::vector<std::string>& args) {
288 auto subcontext_command = SubcontextCommand();
289 std::copy(
290 args.begin(), args.end(),
291 RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
292
293 auto subcontext_reply = TransmitMessage(subcontext_command);
294 if (!subcontext_reply) {
295 return subcontext_reply.error();
296 }
297
Tom Cherry32228482018-01-18 16:14:25 -0800298 for (const auto& property : subcontext_reply->properties_to_set()) {
299 ucred cr = {.pid = pid_, .uid = 0, .gid = 0};
300 HandlePropertySet(property.name(), property.value(), context_, cr);
301 }
302
303 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
304 auto& failure = subcontext_reply->failure();
305 return ResultError(failure.error_string(), failure.error_errno());
306 }
307
Tom Cherryc49719f2018-01-10 11:04:34 -0800308 if (subcontext_reply->reply_case() != SubcontextReply::kSuccess) {
309 return Error() << "Unexpected message type from subcontext: "
310 << subcontext_reply->reply_case();
311 }
312
313 return Success();
314}
315
316Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::string>& args) {
317 auto subcontext_command = SubcontextCommand{};
318 std::copy(args.begin(), args.end(),
319 RepeatedPtrFieldBackInserter(
320 subcontext_command.mutable_expand_args_command()->mutable_args()));
321
322 auto subcontext_reply = TransmitMessage(subcontext_command);
323 if (!subcontext_reply) {
324 return subcontext_reply.error();
325 }
326
Tom Cherry32228482018-01-18 16:14:25 -0800327 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
328 auto& failure = subcontext_reply->failure();
329 return ResultError(failure.error_string(), failure.error_errno());
330 }
331
Tom Cherryc49719f2018-01-10 11:04:34 -0800332 if (subcontext_reply->reply_case() != SubcontextReply::kExpandArgsReply) {
333 return Error() << "Unexpected message type from subcontext: "
334 << subcontext_reply->reply_case();
335 }
336
337 auto& reply = subcontext_reply->expand_args_reply();
338 auto expanded_args = std::vector<std::string>{};
339 for (const auto& string : reply.expanded_args()) {
340 expanded_args.emplace_back(string);
341 }
342 return expanded_args;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700343}
344
345static std::vector<Subcontext> subcontexts;
346
347std::vector<Subcontext>* InitializeSubcontexts() {
Tom Cherry193e4342017-11-27 09:02:08 -0800348 static const char* const paths_and_secontexts[][2] = {
349 {"/vendor", kVendorContext.c_str()},
350 };
351 for (const auto& [path_prefix, secontext] : paths_and_secontexts) {
352 subcontexts.emplace_back(path_prefix, secontext);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700353 }
354 return &subcontexts;
355}
356
357bool SubcontextChildReap(pid_t pid) {
358 for (auto& subcontext : subcontexts) {
359 if (subcontext.pid() == pid) {
360 subcontext.Restart();
361 return true;
362 }
363 }
364 return false;
365}
366
367} // namespace init
368} // namespace android