• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 "property_service.h"
18 
19 #include <android/api-level.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <limits.h>
25 #include <netinet/in.h>
26 #include <stdarg.h>
27 #include <stddef.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/mman.h>
32 #include <sys/poll.h>
33 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <sys/un.h>
36 #include <unistd.h>
37 #include <wchar.h>
38 
39 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
40 #include <sys/_system_properties.h>
41 
42 #include <map>
43 #include <memory>
44 #include <mutex>
45 #include <optional>
46 #include <queue>
47 #include <thread>
48 #include <vector>
49 
50 #include <InitProperties.sysprop.h>
51 #include <android-base/chrono_utils.h>
52 #include <android-base/file.h>
53 #include <android-base/logging.h>
54 #include <android-base/properties.h>
55 #include <android-base/stringprintf.h>
56 #include <android-base/strings.h>
57 #include <property_info_parser/property_info_parser.h>
58 #include <property_info_serializer/property_info_serializer.h>
59 #include <selinux/android.h>
60 #include <selinux/label.h>
61 #include <selinux/selinux.h>
62 
63 #include "debug_ramdisk.h"
64 #include "epoll.h"
65 #include "init.h"
66 #include "persistent_properties.h"
67 #include "property_type.h"
68 #include "proto_utils.h"
69 #include "selinux.h"
70 #include "subcontext.h"
71 #include "system/core/init/property_service.pb.h"
72 #include "util.h"
73 
74 using namespace std::literals;
75 
76 using android::base::GetProperty;
77 using android::base::ReadFileToString;
78 using android::base::Split;
79 using android::base::StartsWith;
80 using android::base::StringPrintf;
81 using android::base::Timer;
82 using android::base::Trim;
83 using android::base::unique_fd;
84 using android::base::WriteStringToFile;
85 using android::properties::BuildTrie;
86 using android::properties::ParsePropertyInfoFile;
87 using android::properties::PropertyInfoAreaFile;
88 using android::properties::PropertyInfoEntry;
89 using android::sysprop::InitProperties::is_userspace_reboot_supported;
90 
91 namespace android {
92 namespace init {
93 
94 static bool persistent_properties_loaded = false;
95 
96 static int property_set_fd = -1;
97 static int from_init_socket = -1;
98 static int init_socket = -1;
99 static bool accept_messages = false;
100 static std::mutex accept_messages_lock;
101 static std::thread property_service_thread;
102 
103 static PropertyInfoAreaFile property_info_area;
104 
105 struct PropertyAuditData {
106     const ucred* cr;
107     const char* name;
108 };
109 
PropertyAuditCallback(void * data,security_class_t,char * buf,size_t len)110 static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
111     auto* d = reinterpret_cast<PropertyAuditData*>(data);
112 
113     if (!d || !d->name || !d->cr) {
114         LOG(ERROR) << "AuditCallback invoked with null data arguments!";
115         return 0;
116     }
117 
118     snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
119              d->cr->gid);
120     return 0;
121 }
122 
StartSendingMessages()123 void StartSendingMessages() {
124     auto lock = std::lock_guard{accept_messages_lock};
125     accept_messages = true;
126 }
127 
StopSendingMessages()128 void StopSendingMessages() {
129     auto lock = std::lock_guard{accept_messages_lock};
130     accept_messages = false;
131 }
132 
CanReadProperty(const std::string & source_context,const std::string & name)133 bool CanReadProperty(const std::string& source_context, const std::string& name) {
134     const char* target_context = nullptr;
135     property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
136 
137     PropertyAuditData audit_data;
138 
139     audit_data.name = name.c_str();
140 
141     ucred cr = {.pid = 0, .uid = 0, .gid = 0};
142     audit_data.cr = &cr;
143 
144     return selinux_check_access(source_context.c_str(), target_context, "file", "read",
145                                 &audit_data) == 0;
146 }
147 
CheckMacPerms(const std::string & name,const char * target_context,const char * source_context,const ucred & cr)148 static bool CheckMacPerms(const std::string& name, const char* target_context,
149                           const char* source_context, const ucred& cr) {
150     if (!target_context || !source_context) {
151         return false;
152     }
153 
154     PropertyAuditData audit_data;
155 
156     audit_data.name = name.c_str();
157     audit_data.cr = &cr;
158 
159     bool has_access = (selinux_check_access(source_context, target_context, "property_service",
160                                             "set", &audit_data) == 0);
161 
162     return has_access;
163 }
164 
PropertySet(const std::string & name,const std::string & value,std::string * error)165 static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {
166     size_t valuelen = value.size();
167 
168     if (!IsLegalPropertyName(name)) {
169         *error = "Illegal property name";
170         return PROP_ERROR_INVALID_NAME;
171     }
172 
173     if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
174         *error = result.error().message();
175         return PROP_ERROR_INVALID_VALUE;
176     }
177 
178     prop_info* pi = (prop_info*) __system_property_find(name.c_str());
179     if (pi != nullptr) {
180         // ro.* properties are actually "write-once".
181         if (StartsWith(name, "ro.")) {
182             *error = "Read-only property was already set";
183             return PROP_ERROR_READ_ONLY_PROPERTY;
184         }
185 
186         __system_property_update(pi, value.c_str(), valuelen);
187     } else {
188         int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
189         if (rc < 0) {
190             *error = "__system_property_add failed";
191             return PROP_ERROR_SET_FAILED;
192         }
193     }
194 
195     // Don't write properties to disk until after we have read all default
196     // properties to prevent them from being overwritten by default values.
197     if (persistent_properties_loaded && StartsWith(name, "persist.")) {
198         WritePersistentProperty(name, value);
199     }
200     // If init hasn't started its main loop, then it won't be handling property changed messages
201     // anyway, so there's no need to try to send them.
202     auto lock = std::lock_guard{accept_messages_lock};
203     if (accept_messages) {
204         PropertyChanged(name, value);
205     }
206     return PROP_SUCCESS;
207 }
208 
209 class AsyncRestorecon {
210   public:
TriggerRestorecon(const std::string & path)211     void TriggerRestorecon(const std::string& path) {
212         auto guard = std::lock_guard{mutex_};
213         paths_.emplace(path);
214 
215         if (!thread_started_) {
216             thread_started_ = true;
217             std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
218         }
219     }
220 
221   private:
ThreadFunction()222     void ThreadFunction() {
223         auto lock = std::unique_lock{mutex_};
224 
225         while (!paths_.empty()) {
226             auto path = paths_.front();
227             paths_.pop();
228 
229             lock.unlock();
230             if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
231                 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
232             }
233             android::base::SetProperty(kRestoreconProperty, path);
234             lock.lock();
235         }
236 
237         thread_started_ = false;
238     }
239 
240     std::mutex mutex_;
241     std::queue<std::string> paths_;
242     bool thread_started_ = false;
243 };
244 
245 class SocketConnection {
246   public:
SocketConnection(int socket,const ucred & cred)247     SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
248 
RecvUint32(uint32_t * value,uint32_t * timeout_ms)249     bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
250         return RecvFully(value, sizeof(*value), timeout_ms);
251     }
252 
RecvChars(char * chars,size_t size,uint32_t * timeout_ms)253     bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
254         return RecvFully(chars, size, timeout_ms);
255     }
256 
RecvString(std::string * value,uint32_t * timeout_ms)257     bool RecvString(std::string* value, uint32_t* timeout_ms) {
258         uint32_t len = 0;
259         if (!RecvUint32(&len, timeout_ms)) {
260             return false;
261         }
262 
263         if (len == 0) {
264             *value = "";
265             return true;
266         }
267 
268         // http://b/35166374: don't allow init to make arbitrarily large allocations.
269         if (len > 0xffff) {
270             LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
271             errno = ENOMEM;
272             return false;
273         }
274 
275         std::vector<char> chars(len);
276         if (!RecvChars(&chars[0], len, timeout_ms)) {
277             return false;
278         }
279 
280         *value = std::string(&chars[0], len);
281         return true;
282     }
283 
SendUint32(uint32_t value)284     bool SendUint32(uint32_t value) {
285         if (!socket_.ok()) {
286             return true;
287         }
288         int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0));
289         return result == sizeof(value);
290     }
291 
GetSourceContext(std::string * source_context) const292     bool GetSourceContext(std::string* source_context) const {
293         char* c_source_context = nullptr;
294         if (getpeercon(socket_, &c_source_context) != 0) {
295             return false;
296         }
297         *source_context = c_source_context;
298         freecon(c_source_context);
299         return true;
300     }
301 
Release()302     [[nodiscard]] int Release() { return socket_.release(); }
303 
cred()304     const ucred& cred() { return cred_; }
305 
306   private:
PollIn(uint32_t * timeout_ms)307     bool PollIn(uint32_t* timeout_ms) {
308         struct pollfd ufds[1];
309         ufds[0].fd = socket_;
310         ufds[0].events = POLLIN;
311         ufds[0].revents = 0;
312         while (*timeout_ms > 0) {
313             auto start_time = std::chrono::steady_clock::now();
314             int nr = poll(ufds, 1, *timeout_ms);
315             auto now = std::chrono::steady_clock::now();
316             auto time_elapsed =
317                 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
318             uint64_t millis = time_elapsed.count();
319             *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
320 
321             if (nr > 0) {
322                 return true;
323             }
324 
325             if (nr == 0) {
326                 // Timeout
327                 break;
328             }
329 
330             if (nr < 0 && errno != EINTR) {
331                 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
332                             << " to send property message";
333                 return false;
334             } else {  // errno == EINTR
335                 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
336                 // to avoid slowing init down by causing EINTR with under millisecond timeout.
337                 if (*timeout_ms > 0) {
338                     --(*timeout_ms);
339                 }
340             }
341         }
342 
343         LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
344                    << " to send property message.";
345         return false;
346     }
347 
RecvFully(void * data_ptr,size_t size,uint32_t * timeout_ms)348     bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
349         size_t bytes_left = size;
350         char* data = static_cast<char*>(data_ptr);
351         while (*timeout_ms > 0 && bytes_left > 0) {
352             if (!PollIn(timeout_ms)) {
353                 return false;
354             }
355 
356             int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT));
357             if (result <= 0) {
358                 PLOG(ERROR) << "sys_prop: recv error";
359                 return false;
360             }
361 
362             bytes_left -= result;
363             data += result;
364         }
365 
366         if (bytes_left != 0) {
367             LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
368         }
369 
370         return bytes_left == 0;
371     }
372 
373     unique_fd socket_;
374     ucred cred_;
375 
376     DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection);
377 };
378 
SendControlMessage(const std::string & msg,const std::string & name,pid_t pid,SocketConnection * socket,std::string * error)379 static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
380                                    SocketConnection* socket, std::string* error) {
381     auto lock = std::lock_guard{accept_messages_lock};
382     if (!accept_messages) {
383         *error = "Received control message after shutdown, ignoring";
384         return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
385     }
386 
387     // We must release the fd before sending it to init, otherwise there will be a race with init.
388     // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
389     int fd = -1;
390     if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
391         fd = socket->Release();
392     }
393 
394     bool queue_success = QueueControlMessage(msg, name, pid, fd);
395     if (!queue_success && fd != -1) {
396         uint32_t response = PROP_ERROR_HANDLE_CONTROL_MESSAGE;
397         TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
398         close(fd);
399     }
400 
401     return PROP_SUCCESS;
402 }
403 
CheckControlPropertyPerms(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr)404 bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
405                                const std::string& source_context, const ucred& cr) {
406     // We check the legacy method first but these properties are dontaudit, so we only log an audit
407     // if the newer method fails as well.  We only do this with the legacy ctl. properties.
408     if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
409         // The legacy permissions model is that ctl. properties have their name ctl.<action> and
410         // their value is the name of the service to apply that action to.  Permissions for these
411         // actions are based on the service, so we must create a fake name of ctl.<service> to
412         // check permissions.
413         auto control_string_legacy = "ctl." + value;
414         const char* target_context_legacy = nullptr;
415         const char* type_legacy = nullptr;
416         property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
417                                             &type_legacy);
418 
419         if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
420             return true;
421         }
422     }
423 
424     auto control_string_full = name + "$" + value;
425     const char* target_context_full = nullptr;
426     const char* type_full = nullptr;
427     property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
428                                         &type_full);
429 
430     return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
431 }
432 
433 // This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
CheckPermissions(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,std::string * error)434 uint32_t CheckPermissions(const std::string& name, const std::string& value,
435                           const std::string& source_context, const ucred& cr, std::string* error) {
436     if (!IsLegalPropertyName(name)) {
437         *error = "Illegal property name";
438         return PROP_ERROR_INVALID_NAME;
439     }
440 
441     if (StartsWith(name, "ctl.")) {
442         if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
443             *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
444                                   value.c_str());
445             return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
446         }
447 
448         return PROP_SUCCESS;
449     }
450 
451     const char* target_context = nullptr;
452     const char* type = nullptr;
453     property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
454 
455     if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
456         *error = "SELinux permission check failed";
457         return PROP_ERROR_PERMISSION_DENIED;
458     }
459 
460     if (!CheckType(type, value)) {
461         *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
462                               (type ?: "(null)"));
463         return PROP_ERROR_INVALID_VALUE;
464     }
465 
466     return PROP_SUCCESS;
467 }
468 
469 // This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
HandlePropertySet(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,SocketConnection * socket,std::string * error)470 uint32_t HandlePropertySet(const std::string& name, const std::string& value,
471                            const std::string& source_context, const ucred& cr,
472                            SocketConnection* socket, std::string* error) {
473     if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
474         return ret;
475     }
476 
477     if (StartsWith(name, "ctl.")) {
478         return SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error);
479     }
480 
481     // sys.powerctl is a special property that is used to make the device reboot.  We want to log
482     // any process that sets this property to be able to accurately blame the cause of a shutdown.
483     if (name == "sys.powerctl") {
484         std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
485         std::string process_cmdline;
486         std::string process_log_string;
487         if (ReadFileToString(cmdline_path, &process_cmdline)) {
488             // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
489             // path.
490             process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
491         }
492         LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
493                   << process_log_string;
494         if (value == "reboot,userspace" && !is_userspace_reboot_supported().value_or(false)) {
495             *error = "Userspace reboot is not supported by this device";
496             return PROP_ERROR_INVALID_VALUE;
497         }
498     }
499 
500     // If a process other than init is writing a non-empty value, it means that process is
501     // requesting that init performs a restorecon operation on the path specified by 'value'.
502     // We use a thread to do this restorecon operation to prevent holding up init, as it may take
503     // a long time to complete.
504     if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
505         static AsyncRestorecon async_restorecon;
506         async_restorecon.TriggerRestorecon(value);
507         return PROP_SUCCESS;
508     }
509 
510     return PropertySet(name, value, error);
511 }
512 
handle_property_set_fd()513 static void handle_property_set_fd() {
514     static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
515 
516     int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
517     if (s == -1) {
518         return;
519     }
520 
521     ucred cr;
522     socklen_t cr_size = sizeof(cr);
523     if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
524         close(s);
525         PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
526         return;
527     }
528 
529     SocketConnection socket(s, cr);
530     uint32_t timeout_ms = kDefaultSocketTimeout;
531 
532     uint32_t cmd = 0;
533     if (!socket.RecvUint32(&cmd, &timeout_ms)) {
534         PLOG(ERROR) << "sys_prop: error while reading command from the socket";
535         socket.SendUint32(PROP_ERROR_READ_CMD);
536         return;
537     }
538 
539     switch (cmd) {
540     case PROP_MSG_SETPROP: {
541         char prop_name[PROP_NAME_MAX];
542         char prop_value[PROP_VALUE_MAX];
543 
544         if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
545             !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
546           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
547           return;
548         }
549 
550         prop_name[PROP_NAME_MAX-1] = 0;
551         prop_value[PROP_VALUE_MAX-1] = 0;
552 
553         std::string source_context;
554         if (!socket.GetSourceContext(&source_context)) {
555             PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
556             return;
557         }
558 
559         const auto& cr = socket.cred();
560         std::string error;
561         uint32_t result =
562                 HandlePropertySet(prop_name, prop_value, source_context, cr, nullptr, &error);
563         if (result != PROP_SUCCESS) {
564             LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
565                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
566         }
567 
568         break;
569       }
570 
571     case PROP_MSG_SETPROP2: {
572         std::string name;
573         std::string value;
574         if (!socket.RecvString(&name, &timeout_ms) ||
575             !socket.RecvString(&value, &timeout_ms)) {
576           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
577           socket.SendUint32(PROP_ERROR_READ_DATA);
578           return;
579         }
580 
581         std::string source_context;
582         if (!socket.GetSourceContext(&source_context)) {
583             PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
584             socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
585             return;
586         }
587 
588         const auto& cr = socket.cred();
589         std::string error;
590         uint32_t result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
591         if (result != PROP_SUCCESS) {
592             LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
593                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
594         }
595         socket.SendUint32(result);
596         break;
597       }
598 
599     default:
600         LOG(ERROR) << "sys_prop: invalid command " << cmd;
601         socket.SendUint32(PROP_ERROR_INVALID_CMD);
602         break;
603     }
604 }
605 
InitPropertySet(const std::string & name,const std::string & value)606 uint32_t InitPropertySet(const std::string& name, const std::string& value) {
607     uint32_t result = 0;
608     ucred cr = {.pid = 1, .uid = 0, .gid = 0};
609     std::string error;
610     result = HandlePropertySet(name, value, kInitContext, cr, nullptr, &error);
611     if (result != PROP_SUCCESS) {
612         LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
613     }
614 
615     return result;
616 }
617 
618 static bool load_properties_from_file(const char*, const char*,
619                                       std::map<std::string, std::string>*);
620 
621 /*
622  * Filter is used to decide which properties to load: NULL loads all keys,
623  * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
624  */
LoadProperties(char * data,const char * filter,const char * filename,std::map<std::string,std::string> * properties)625 static void LoadProperties(char* data, const char* filter, const char* filename,
626                            std::map<std::string, std::string>* properties) {
627     char *key, *value, *eol, *sol, *tmp, *fn;
628     size_t flen = 0;
629 
630     static constexpr const char* const kVendorPathPrefixes[2] = {
631             "/vendor",
632             "/odm",
633     };
634 
635     const char* context = kInitContext;
636     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
637         for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
638             if (StartsWith(filename, vendor_path_prefix)) {
639                 context = kVendorContext;
640             }
641         }
642     }
643 
644     if (filter) {
645         flen = strlen(filter);
646     }
647 
648     sol = data;
649     while ((eol = strchr(sol, '\n'))) {
650         key = sol;
651         *eol++ = 0;
652         sol = eol;
653 
654         while (isspace(*key)) key++;
655         if (*key == '#') continue;
656 
657         tmp = eol - 2;
658         while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
659 
660         if (!strncmp(key, "import ", 7) && flen == 0) {
661             fn = key + 7;
662             while (isspace(*fn)) fn++;
663 
664             key = strchr(fn, ' ');
665             if (key) {
666                 *key++ = 0;
667                 while (isspace(*key)) key++;
668             }
669 
670             std::string raw_filename(fn);
671             auto expanded_filename = ExpandProps(raw_filename);
672 
673             if (!expanded_filename.ok()) {
674                 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
675                 continue;
676             }
677 
678             load_properties_from_file(expanded_filename->c_str(), key, properties);
679         } else {
680             value = strchr(key, '=');
681             if (!value) continue;
682             *value++ = 0;
683 
684             tmp = value - 2;
685             while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
686 
687             while (isspace(*value)) value++;
688 
689             if (flen > 0) {
690                 if (filter[flen - 1] == '*') {
691                     if (strncmp(key, filter, flen - 1) != 0) continue;
692                 } else {
693                     if (strcmp(key, filter) != 0) continue;
694                 }
695             }
696 
697             if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
698                 std::string{key} == kRestoreconProperty) {
699                 LOG(ERROR) << "Ignoring disallowed property '" << key
700                            << "' with special meaning in prop file '" << filename << "'";
701                 continue;
702             }
703 
704             ucred cr = {.pid = 1, .uid = 0, .gid = 0};
705             std::string error;
706             if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
707                 auto it = properties->find(key);
708                 if (it == properties->end()) {
709                     (*properties)[key] = value;
710                 } else if (it->second != value) {
711                     LOG(WARNING) << "Overriding previous 'ro.' property '" << key << "':'"
712                                  << it->second << "' with new value '" << value << "'";
713                     it->second = value;
714                 }
715             } else {
716                 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
717                            << "' in property file '" << filename << "': " << error;
718             }
719         }
720     }
721 }
722 
723 // Filter is used to decide which properties to load: NULL loads all keys,
724 // "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
load_properties_from_file(const char * filename,const char * filter,std::map<std::string,std::string> * properties)725 static bool load_properties_from_file(const char* filename, const char* filter,
726                                       std::map<std::string, std::string>* properties) {
727     Timer t;
728     auto file_contents = ReadFile(filename);
729     if (!file_contents.ok()) {
730         PLOG(WARNING) << "Couldn't load property file '" << filename
731                       << "': " << file_contents.error();
732         return false;
733     }
734     file_contents->push_back('\n');
735 
736     LoadProperties(file_contents->data(), filter, filename, properties);
737     LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
738     return true;
739 }
740 
741 // persist.sys.usb.config values can't be combined on build-time when property
742 // files are split into each partition.
743 // So we need to apply the same rule of build/make/tools/post_process_props.py
744 // on runtime.
update_sys_usb_config()745 static void update_sys_usb_config() {
746     bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
747     std::string config = android::base::GetProperty("persist.sys.usb.config", "");
748     // b/150130503, add (config == "none") condition here to prevent appending
749     // ",adb" if "none" is explicitly defined in default prop.
750     if (config.empty() || config == "none") {
751         InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
752     } else if (is_debuggable && config.find("adb") == std::string::npos &&
753                config.length() + 4 < PROP_VALUE_MAX) {
754         config.append(",adb");
755         InitPropertySet("persist.sys.usb.config", config);
756     }
757 }
758 
load_override_properties()759 static void load_override_properties() {
760     if (ALLOW_LOCAL_PROP_OVERRIDE) {
761         std::map<std::string, std::string> properties;
762         load_properties_from_file("/data/local.prop", nullptr, &properties);
763         for (const auto& [name, value] : properties) {
764             std::string error;
765             if (PropertySet(name, value, &error) != PROP_SUCCESS) {
766                 LOG(ERROR) << "Could not set '" << name << "' to '" << value
767                            << "' in /data/local.prop: " << error;
768             }
769         }
770     }
771 }
772 
773 // If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
774 // set, derive them from ro.product.${partition}.* properties
property_initialize_ro_product_props()775 static void property_initialize_ro_product_props() {
776     const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
777     const char* RO_PRODUCT_PROPS[] = {
778             "brand", "device", "manufacturer", "model", "name",
779     };
780     const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
781             "odm", "product", "system_ext", "system", "vendor",
782     };
783     const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
784     const std::string EMPTY = "";
785 
786     std::string ro_product_props_source_order =
787             GetProperty("ro.product.property_source_order", EMPTY);
788 
789     if (!ro_product_props_source_order.empty()) {
790         // Verify that all specified sources are valid
791         for (const auto& source : Split(ro_product_props_source_order, ",")) {
792             // Verify that the specified source is valid
793             bool is_allowed_source = false;
794             for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
795                 if (source == allowed_source) {
796                     is_allowed_source = true;
797                     break;
798                 }
799             }
800             if (!is_allowed_source) {
801                 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
802                               "using the default property source order";
803                 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
804                 break;
805             }
806         }
807     } else {
808         ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
809     }
810 
811     for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
812         std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
813         base_prop += ro_product_prop;
814 
815         std::string base_prop_val = GetProperty(base_prop, EMPTY);
816         if (!base_prop_val.empty()) {
817             continue;
818         }
819 
820         for (const auto& source : Split(ro_product_props_source_order, ",")) {
821             std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
822             target_prop += source;
823             target_prop += '.';
824             target_prop += ro_product_prop;
825 
826             std::string target_prop_val = GetProperty(target_prop, EMPTY);
827             if (!target_prop_val.empty()) {
828                 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
829                           << "' (from " << target_prop << ")";
830                 std::string error;
831                 uint32_t res = PropertySet(base_prop, target_prop_val, &error);
832                 if (res != PROP_SUCCESS) {
833                     LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
834                                << " (" << error << ")";
835                 }
836                 break;
837             }
838         }
839     }
840 }
841 
842 // If the ro.build.fingerprint property has not been set, derive it from constituent pieces
property_derive_build_fingerprint()843 static void property_derive_build_fingerprint() {
844     std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
845     if (!build_fingerprint.empty()) {
846         return;
847     }
848 
849     const std::string UNKNOWN = "unknown";
850     build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
851     build_fingerprint += '/';
852     build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
853     build_fingerprint += '/';
854     build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
855     build_fingerprint += ':';
856     build_fingerprint += GetProperty("ro.build.version.release", UNKNOWN);
857     build_fingerprint += '/';
858     build_fingerprint += GetProperty("ro.build.id", UNKNOWN);
859     build_fingerprint += '/';
860     build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
861     build_fingerprint += ':';
862     build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
863     build_fingerprint += '/';
864     build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
865 
866     LOG(INFO) << "Setting property 'ro.build.fingerprint' to '" << build_fingerprint << "'";
867 
868     std::string error;
869     uint32_t res = PropertySet("ro.build.fingerprint", build_fingerprint, &error);
870     if (res != PROP_SUCCESS) {
871         LOG(ERROR) << "Error setting property 'ro.build.fingerprint': err=" << res << " (" << error
872                    << ")";
873     }
874 }
875 
PropertyLoadBootDefaults()876 void PropertyLoadBootDefaults() {
877     // TODO(b/117892318): merge prop.default and build.prop files into one
878     // We read the properties and their values into a map, in order to always allow properties
879     // loaded in the later property files to override the properties in loaded in the earlier
880     // property files, regardless of if they are "ro." properties or not.
881     std::map<std::string, std::string> properties;
882     if (!load_properties_from_file("/system/etc/prop.default", nullptr, &properties)) {
883         // Try recovery path
884         if (!load_properties_from_file("/prop.default", nullptr, &properties)) {
885             // Try legacy path
886             load_properties_from_file("/default.prop", nullptr, &properties);
887         }
888     }
889     load_properties_from_file("/system/build.prop", nullptr, &properties);
890     load_properties_from_file("/system_ext/build.prop", nullptr, &properties);
891     load_properties_from_file("/vendor/default.prop", nullptr, &properties);
892     load_properties_from_file("/vendor/build.prop", nullptr, &properties);
893     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {
894         load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);
895     } else {
896         load_properties_from_file("/odm/default.prop", nullptr, &properties);
897         load_properties_from_file("/odm/build.prop", nullptr, &properties);
898     }
899     load_properties_from_file("/product/build.prop", nullptr, &properties);
900     load_properties_from_file("/factory/factory.prop", "ro.*", &properties);
901 
902     if (access(kDebugRamdiskProp, R_OK) == 0) {
903         LOG(INFO) << "Loading " << kDebugRamdiskProp;
904         load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
905     }
906 
907     for (const auto& [name, value] : properties) {
908         std::string error;
909         if (PropertySet(name, value, &error) != PROP_SUCCESS) {
910             LOG(ERROR) << "Could not set '" << name << "' to '" << value
911                        << "' while loading .prop files" << error;
912         }
913     }
914 
915     property_initialize_ro_product_props();
916     property_derive_build_fingerprint();
917 
918     update_sys_usb_config();
919 }
920 
LoadPropertyInfoFromFile(const std::string & filename,std::vector<PropertyInfoEntry> * property_infos)921 bool LoadPropertyInfoFromFile(const std::string& filename,
922                               std::vector<PropertyInfoEntry>* property_infos) {
923     auto file_contents = std::string();
924     if (!ReadFileToString(filename, &file_contents)) {
925         PLOG(ERROR) << "Could not read properties from '" << filename << "'";
926         return false;
927     }
928 
929     auto errors = std::vector<std::string>{};
930     bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
931     ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
932     // Individual parsing errors are reported but do not cause a failed boot, which is what
933     // returning false would do here.
934     for (const auto& error : errors) {
935         LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
936     }
937 
938     return true;
939 }
940 
CreateSerializedPropertyInfo()941 void CreateSerializedPropertyInfo() {
942     auto property_infos = std::vector<PropertyInfoEntry>();
943     if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
944         if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
945                                       &property_infos)) {
946             return;
947         }
948         // Don't check for failure here, so we always have a sane list of properties.
949         // E.g. In case of recovery, the vendor partition will not have mounted and we
950         // still need the system / platform properties to function.
951         if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
952             LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
953                                      &property_infos);
954         }
955         if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
956                                       &property_infos)) {
957             // Fallback to nonplat_* if vendor_* doesn't exist.
958             LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",
959                                      &property_infos);
960         }
961         if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
962             LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
963                                      &property_infos);
964         }
965         if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
966             LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
967         }
968     } else {
969         if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
970             return;
971         }
972         LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
973         if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {
974             // Fallback to nonplat_* if vendor_* doesn't exist.
975             LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
976         }
977         LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
978         LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
979     }
980 
981     auto serialized_contexts = std::string();
982     auto error = std::string();
983     if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
984                    &error)) {
985         LOG(ERROR) << "Unable to serialize property contexts: " << error;
986         return;
987     }
988 
989     constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
990     if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
991         PLOG(ERROR) << "Unable to write serialized property infos to file";
992     }
993     selinux_android_restorecon(kPropertyInfosPath, 0);
994 }
995 
ExportKernelBootProps()996 static void ExportKernelBootProps() {
997     constexpr const char* UNSET = "";
998     struct {
999         const char* src_prop;
1000         const char* dst_prop;
1001         const char* default_value;
1002     } prop_map[] = {
1003             // clang-format off
1004         { "ro.boot.serialno",   "ro.serialno",   UNSET, },
1005         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
1006         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
1007         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1008         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
1009         { "ro.boot.revision",   "ro.revision",   "0", },
1010             // clang-format on
1011     };
1012     for (const auto& prop : prop_map) {
1013         std::string value = GetProperty(prop.src_prop, prop.default_value);
1014         if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1015     }
1016 }
1017 
ProcessKernelDt()1018 static void ProcessKernelDt() {
1019     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1020         return;
1021     }
1022 
1023     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
1024     if (!dir) return;
1025 
1026     std::string dt_file;
1027     struct dirent* dp;
1028     while ((dp = readdir(dir.get())) != NULL) {
1029         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1030             !strcmp(dp->d_name, "name")) {
1031             continue;
1032         }
1033 
1034         std::string file_name = get_android_dt_dir() + dp->d_name;
1035 
1036         android::base::ReadFileToString(file_name, &dt_file);
1037         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1038 
1039         InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1040     }
1041 }
1042 
ProcessKernelCmdline()1043 static void ProcessKernelCmdline() {
1044     bool for_emulator = false;
1045     ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1046         if (key == "qemu") {
1047             for_emulator = true;
1048         } else if (StartsWith(key, "androidboot.")) {
1049             InitPropertySet("ro.boot." + key.substr(12), value);
1050         }
1051     });
1052 
1053     if (for_emulator) {
1054         ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1055             // In the emulator, export any kernel option with the "ro.kernel." prefix.
1056             InitPropertySet("ro.kernel." + key, value);
1057         });
1058     }
1059 }
1060 
PropertyInit()1061 void PropertyInit() {
1062     selinux_callback cb;
1063     cb.func_audit = PropertyAuditCallback;
1064     selinux_set_callback(SELINUX_CB_AUDIT, cb);
1065 
1066     mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1067     CreateSerializedPropertyInfo();
1068     if (__system_property_area_init()) {
1069         LOG(FATAL) << "Failed to initialize property area";
1070     }
1071     if (!property_info_area.LoadDefaultPath()) {
1072         LOG(FATAL) << "Failed to load serialized property info file";
1073     }
1074 
1075     // If arguments are passed both on the command line and in DT,
1076     // properties set in DT always have priority over the command-line ones.
1077     ProcessKernelDt();
1078     ProcessKernelCmdline();
1079 
1080     // Propagate the kernel variables to internal variables
1081     // used by init as well as the current required properties.
1082     ExportKernelBootProps();
1083 
1084     PropertyLoadBootDefaults();
1085 }
1086 
HandleInitSocket()1087 static void HandleInitSocket() {
1088     auto message = ReadMessage(init_socket);
1089     if (!message.ok()) {
1090         LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1091         return;
1092     }
1093 
1094     auto init_message = InitMessage{};
1095     if (!init_message.ParseFromString(*message)) {
1096         LOG(ERROR) << "Could not parse message from init";
1097         return;
1098     }
1099 
1100     switch (init_message.msg_case()) {
1101         case InitMessage::kLoadPersistentProperties: {
1102             load_override_properties();
1103             // Read persistent properties after all default values have been loaded.
1104             auto persistent_properties = LoadPersistentProperties();
1105             for (const auto& persistent_property_record : persistent_properties.properties()) {
1106                 InitPropertySet(persistent_property_record.name(),
1107                                 persistent_property_record.value());
1108             }
1109             InitPropertySet("ro.persistent_properties.ready", "true");
1110             persistent_properties_loaded = true;
1111             break;
1112         }
1113         default:
1114             LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1115     }
1116 }
1117 
PropertyServiceThread()1118 static void PropertyServiceThread() {
1119     Epoll epoll;
1120     if (auto result = epoll.Open(); !result.ok()) {
1121         LOG(FATAL) << result.error();
1122     }
1123 
1124     if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
1125         !result.ok()) {
1126         LOG(FATAL) << result.error();
1127     }
1128 
1129     if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
1130         LOG(FATAL) << result.error();
1131     }
1132 
1133     while (true) {
1134         auto pending_functions = epoll.Wait(std::nullopt);
1135         if (!pending_functions.ok()) {
1136             LOG(ERROR) << pending_functions.error();
1137         } else {
1138             for (const auto& function : *pending_functions) {
1139                 (*function)();
1140             }
1141         }
1142     }
1143 }
1144 
StartPropertyService(int * epoll_socket)1145 void StartPropertyService(int* epoll_socket) {
1146     InitPropertySet("ro.property_service.version", "2");
1147 
1148     int sockets[2];
1149     if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1150         PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1151     }
1152     *epoll_socket = from_init_socket = sockets[0];
1153     init_socket = sockets[1];
1154     StartSendingMessages();
1155 
1156     if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1157                                    false, 0666, 0, 0, {});
1158         result.ok()) {
1159         property_set_fd = *result;
1160     } else {
1161         LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
1162     }
1163 
1164     listen(property_set_fd, 8);
1165 
1166     auto new_thread = std::thread{PropertyServiceThread};
1167     property_service_thread.swap(new_thread);
1168 }
1169 
1170 }  // namespace init
1171 }  // namespace android
1172