property_service.cpp revision c68998441cdf32159912704fdd264b4750390012
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 <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <string.h>
21#include <ctype.h>
22#include <fcntl.h>
23#include <stdarg.h>
24#include <dirent.h>
25#include <limits.h>
26#include <errno.h>
27#include <sys/poll.h>
28
29#include <memory>
30
31#include <cutils/misc.h>
32#include <cutils/sockets.h>
33#include <cutils/multiuser.h>
34
35#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
36#include <sys/_system_properties.h>
37
38#include <sys/socket.h>
39#include <sys/un.h>
40#include <sys/select.h>
41#include <sys/types.h>
42#include <netinet/in.h>
43#include <sys/mman.h>
44#include <private/android_filesystem_config.h>
45
46#include <selinux/selinux.h>
47#include <selinux/label.h>
48
49#include <fs_mgr.h>
50#include <android-base/file.h>
51#include "bootimg.h"
52
53#include "property_service.h"
54#include "init.h"
55#include "util.h"
56#include "log.h"
57
58#define PERSISTENT_PROPERTY_DIR  "/data/property"
59#define FSTAB_PREFIX "/fstab."
60#define RECOVERY_MOUNT_POINT "/recovery"
61
62static int persistent_properties_loaded = 0;
63static bool property_area_initialized = false;
64
65static int property_set_fd = -1;
66
67void property_init() {
68    if (property_area_initialized) {
69        return;
70    }
71
72    property_area_initialized = true;
73
74    if (__system_property_area_init()) {
75        ERROR("Failed to initialize property area\n");
76        exit(1);
77    }
78}
79
80static int check_mac_perms(const char *name, char *sctx, struct ucred *cr)
81{
82    char *tctx = NULL;
83    int result = 0;
84    property_audit_data audit_data;
85
86    if (!sctx)
87        goto err;
88
89    if (!sehandle_prop)
90        goto err;
91
92    if (selabel_lookup(sehandle_prop, &tctx, name, 1) != 0)
93        goto err;
94
95    audit_data.name = name;
96    audit_data.cr = cr;
97
98    if (selinux_check_access(sctx, tctx, "property_service", "set", reinterpret_cast<void*>(&audit_data)) == 0)
99        result = 1;
100
101    freecon(tctx);
102 err:
103    return result;
104}
105
106static int check_control_mac_perms(const char *name, char *sctx, struct ucred *cr)
107{
108    /*
109     *  Create a name prefix out of ctl.<service name>
110     *  The new prefix allows the use of the existing
111     *  property service backend labeling while avoiding
112     *  mislabels based on true property prefixes.
113     */
114    char ctl_name[PROP_VALUE_MAX+4];
115    int ret = snprintf(ctl_name, sizeof(ctl_name), "ctl.%s", name);
116
117    if (ret < 0 || (size_t) ret >= sizeof(ctl_name))
118        return 0;
119
120    return check_mac_perms(ctl_name, sctx, cr);
121}
122
123/*
124 * Checks permissions for setting system properties.
125 * Returns 1 if uid allowed, 0 otherwise.
126 */
127static int check_perms(const char *name, char *sctx, struct ucred *cr)
128{
129    if(!strncmp(name, "ro.", 3))
130        name +=3;
131
132    return check_mac_perms(name, sctx, cr);
133}
134
135std::string property_get(const char* name) {
136    char value[PROP_VALUE_MAX] = {0};
137    __system_property_get(name, value);
138    return value;
139}
140
141static void write_persistent_property(const char *name, const char *value)
142{
143    char tempPath[PATH_MAX];
144    char path[PATH_MAX];
145    int fd;
146
147    snprintf(tempPath, sizeof(tempPath), "%s/.temp.XXXXXX", PERSISTENT_PROPERTY_DIR);
148    fd = mkstemp(tempPath);
149    if (fd < 0) {
150        ERROR("Unable to write persistent property to temp file %s: %s\n", tempPath, strerror(errno));
151        return;
152    }
153    write(fd, value, strlen(value));
154    fsync(fd);
155    close(fd);
156
157    snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);
158    if (rename(tempPath, path)) {
159        unlink(tempPath);
160        ERROR("Unable to rename persistent property file %s to %s\n", tempPath, path);
161    }
162}
163
164static bool is_legal_property_name(const char* name, size_t namelen)
165{
166    size_t i;
167    if (namelen >= PROP_NAME_MAX) return false;
168    if (namelen < 1) return false;
169    if (name[0] == '.') return false;
170    if (name[namelen - 1] == '.') return false;
171
172    /* Only allow alphanumeric, plus '.', '-', or '_' */
173    /* Don't allow ".." to appear in a property name */
174    for (i = 0; i < namelen; i++) {
175        if (name[i] == '.') {
176            // i=0 is guaranteed to never have a dot. See above.
177            if (name[i-1] == '.') return false;
178            continue;
179        }
180        if (name[i] == '_' || name[i] == '-') continue;
181        if (name[i] >= 'a' && name[i] <= 'z') continue;
182        if (name[i] >= 'A' && name[i] <= 'Z') continue;
183        if (name[i] >= '0' && name[i] <= '9') continue;
184        return false;
185    }
186
187    return true;
188}
189
190static int property_set_impl(const char* name, const char* value) {
191    size_t namelen = strlen(name);
192    size_t valuelen = strlen(value);
193
194    if (!is_legal_property_name(name, namelen)) return -1;
195    if (valuelen >= PROP_VALUE_MAX) return -1;
196
197    if (strcmp("selinux.reload_policy", name) == 0 && strcmp("1", value) == 0) {
198        if (selinux_reload_policy() != 0) {
199            ERROR("Failed to reload policy\n");
200        }
201    } else if (strcmp("selinux.restorecon_recursive", name) == 0 && valuelen > 0) {
202        if (restorecon_recursive(value) != 0) {
203            ERROR("Failed to restorecon_recursive %s\n", value);
204        }
205    }
206
207    prop_info* pi = (prop_info*) __system_property_find(name);
208
209    if(pi != 0) {
210        /* ro.* properties may NEVER be modified once set */
211        if(!strncmp(name, "ro.", 3)) return -1;
212
213        __system_property_update(pi, value, valuelen);
214    } else {
215        int rc = __system_property_add(name, namelen, value, valuelen);
216        if (rc < 0) {
217            return rc;
218        }
219    }
220    /* If name starts with "net." treat as a DNS property. */
221    if (strncmp("net.", name, strlen("net.")) == 0)  {
222        if (strcmp("net.change", name) == 0) {
223            return 0;
224        }
225       /*
226        * The 'net.change' property is a special property used track when any
227        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
228        * contains the last updated 'net.*' property.
229        */
230        property_set("net.change", name);
231    } else if (persistent_properties_loaded &&
232            strncmp("persist.", name, strlen("persist.")) == 0) {
233        /*
234         * Don't write properties to disk until after we have read all default properties
235         * to prevent them from being overwritten by default values.
236         */
237        write_persistent_property(name, value);
238    }
239    property_changed(name, value);
240    return 0;
241}
242
243int property_set(const char* name, const char* value) {
244    int rc = property_set_impl(name, value);
245    if (rc == -1) {
246        ERROR("property_set(\"%s\", \"%s\") failed\n", name, value);
247    }
248    return rc;
249}
250
251static void handle_property_set_fd()
252{
253    prop_msg msg;
254    int s;
255    int r;
256    struct ucred cr;
257    struct sockaddr_un addr;
258    socklen_t addr_size = sizeof(addr);
259    socklen_t cr_size = sizeof(cr);
260    char * source_ctx = NULL;
261    struct pollfd ufds[1];
262    const int timeout_ms = 2 * 1000;  /* Default 2 sec timeout for caller to send property. */
263    int nr;
264
265    if ((s = accept(property_set_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
266        return;
267    }
268
269    /* Check socket options here */
270    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
271        close(s);
272        ERROR("Unable to receive socket options\n");
273        return;
274    }
275
276    ufds[0].fd = s;
277    ufds[0].events = POLLIN;
278    ufds[0].revents = 0;
279    nr = TEMP_FAILURE_RETRY(poll(ufds, 1, timeout_ms));
280    if (nr == 0) {
281        ERROR("sys_prop: timeout waiting for uid=%d to send property message.\n", cr.uid);
282        close(s);
283        return;
284    } else if (nr < 0) {
285        ERROR("sys_prop: error waiting for uid=%d to send property message: %s\n", cr.uid, strerror(errno));
286        close(s);
287        return;
288    }
289
290    r = TEMP_FAILURE_RETRY(recv(s, &msg, sizeof(msg), MSG_DONTWAIT));
291    if(r != sizeof(prop_msg)) {
292        ERROR("sys_prop: mis-match msg size received: %d expected: %zu: %s\n",
293              r, sizeof(prop_msg), strerror(errno));
294        close(s);
295        return;
296    }
297
298    switch(msg.cmd) {
299    case PROP_MSG_SETPROP:
300        msg.name[PROP_NAME_MAX-1] = 0;
301        msg.value[PROP_VALUE_MAX-1] = 0;
302
303        if (!is_legal_property_name(msg.name, strlen(msg.name))) {
304            ERROR("sys_prop: illegal property name. Got: \"%s\"\n", msg.name);
305            close(s);
306            return;
307        }
308
309        getpeercon(s, &source_ctx);
310
311        if(memcmp(msg.name,"ctl.",4) == 0) {
312            // Keep the old close-socket-early behavior when handling
313            // ctl.* properties.
314            close(s);
315            if (check_control_mac_perms(msg.value, source_ctx, &cr)) {
316                handle_control_message((char*) msg.name + 4, (char*) msg.value);
317            } else {
318                ERROR("sys_prop: Unable to %s service ctl [%s] uid:%d gid:%d pid:%d\n",
319                        msg.name + 4, msg.value, cr.uid, cr.gid, cr.pid);
320            }
321        } else {
322            if (check_perms(msg.name, source_ctx, &cr)) {
323                property_set((char*) msg.name, (char*) msg.value);
324            } else {
325                ERROR("sys_prop: permission denied uid:%d  name:%s\n",
326                      cr.uid, msg.name);
327            }
328
329            // Note: bionic's property client code assumes that the
330            // property server will not close the socket until *AFTER*
331            // the property is written to memory.
332            close(s);
333        }
334        freecon(source_ctx);
335        break;
336
337    default:
338        close(s);
339        break;
340    }
341}
342
343static void load_properties_from_file(const char *, const char *);
344
345/*
346 * Filter is used to decide which properties to load: NULL loads all keys,
347 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
348 */
349static void load_properties(char *data, const char *filter)
350{
351    char *key, *value, *eol, *sol, *tmp, *fn;
352    size_t flen = 0;
353
354    if (filter) {
355        flen = strlen(filter);
356    }
357
358    sol = data;
359    while ((eol = strchr(sol, '\n'))) {
360        key = sol;
361        *eol++ = 0;
362        sol = eol;
363
364        while (isspace(*key)) key++;
365        if (*key == '#') continue;
366
367        tmp = eol - 2;
368        while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
369
370        if (!strncmp(key, "import ", 7) && flen == 0) {
371            fn = key + 7;
372            while (isspace(*fn)) fn++;
373
374            key = strchr(fn, ' ');
375            if (key) {
376                *key++ = 0;
377                while (isspace(*key)) key++;
378            }
379
380            load_properties_from_file(fn, key);
381
382        } else {
383            value = strchr(key, '=');
384            if (!value) continue;
385            *value++ = 0;
386
387            tmp = value - 2;
388            while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
389
390            while (isspace(*value)) value++;
391
392            if (flen > 0) {
393                if (filter[flen - 1] == '*') {
394                    if (strncmp(key, filter, flen - 1)) continue;
395                } else {
396                    if (strcmp(key, filter)) continue;
397                }
398            }
399
400            property_set(key, value);
401        }
402    }
403}
404
405/*
406 * Filter is used to decide which properties to load: NULL loads all keys,
407 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
408 */
409static void load_properties_from_file(const char* filename, const char* filter) {
410    Timer t;
411    std::string data;
412    if (read_file(filename, &data)) {
413        data.push_back('\n');
414        load_properties(&data[0], filter);
415    }
416    NOTICE("(Loading properties from %s took %.2fs.)\n", filename, t.duration());
417}
418
419static void load_persistent_properties() {
420    persistent_properties_loaded = 1;
421
422    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(PERSISTENT_PROPERTY_DIR), closedir);
423    if (!dir) {
424        ERROR("Unable to open persistent property directory \"%s\": %s\n",
425              PERSISTENT_PROPERTY_DIR, strerror(errno));
426        return;
427    }
428
429    struct dirent* entry;
430    while ((entry = readdir(dir.get())) != NULL) {
431        if (strncmp("persist.", entry->d_name, strlen("persist."))) {
432            continue;
433        }
434        if (entry->d_type != DT_REG) {
435            continue;
436        }
437
438        // Open the file and read the property value.
439        int fd = openat(dirfd(dir.get()), entry->d_name, O_RDONLY | O_NOFOLLOW);
440        if (fd == -1) {
441            ERROR("Unable to open persistent property file \"%s\": %s\n",
442                  entry->d_name, strerror(errno));
443            continue;
444        }
445
446        struct stat sb;
447        if (fstat(fd, &sb) == -1) {
448            ERROR("fstat on property file \"%s\" failed: %s\n", entry->d_name, strerror(errno));
449            close(fd);
450            continue;
451        }
452
453        // File must not be accessible to others, be owned by root/root, and
454        // not be a hard link to any other file.
455        if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || (sb.st_uid != 0) || (sb.st_gid != 0) ||
456                (sb.st_nlink != 1)) {
457            ERROR("skipping insecure property file %s (uid=%u gid=%u nlink=%u mode=%o)\n",
458                  entry->d_name, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid,
459                  (unsigned int)sb.st_nlink, sb.st_mode);
460            close(fd);
461            continue;
462        }
463
464        char value[PROP_VALUE_MAX];
465        int length = read(fd, value, sizeof(value) - 1);
466        if (length >= 0) {
467            value[length] = 0;
468            property_set(entry->d_name, value);
469        } else {
470            ERROR("Unable to read persistent property file %s: %s\n",
471                  entry->d_name, strerror(errno));
472        }
473        close(fd);
474    }
475}
476
477void property_load_boot_defaults() {
478    load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT, NULL);
479}
480
481bool properties_initialized() {
482    return property_area_initialized;
483}
484
485static void load_override_properties() {
486    if (ALLOW_LOCAL_PROP_OVERRIDE) {
487        std::string debuggable = property_get("ro.debuggable");
488        if (debuggable == "1") {
489            load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE, NULL);
490        }
491    }
492}
493
494/* When booting an encrypted system, /data is not mounted when the
495 * property service is started, so any properties stored there are
496 * not loaded.  Vold triggers init to load these properties once it
497 * has mounted /data.
498 */
499void load_persist_props(void) {
500    load_override_properties();
501    /* Read persistent properties after all default values have been loaded. */
502    load_persistent_properties();
503}
504
505void load_recovery_id_prop() {
506    std::string ro_hardware = property_get("ro.hardware");
507    if (ro_hardware.empty()) {
508        ERROR("ro.hardware not set - unable to load recovery id\n");
509        return;
510    }
511    std::string fstab_filename = FSTAB_PREFIX + ro_hardware;
512
513    std::unique_ptr<fstab, void(*)(fstab*)> tab(fs_mgr_read_fstab(fstab_filename.c_str()),
514            fs_mgr_free_fstab);
515    if (!tab) {
516        ERROR("unable to read fstab %s: %s\n", fstab_filename.c_str(), strerror(errno));
517        return;
518    }
519
520    fstab_rec* rec = fs_mgr_get_entry_for_mount_point(tab.get(), RECOVERY_MOUNT_POINT);
521    if (rec == NULL) {
522        ERROR("/recovery not specified in fstab\n");
523        return;
524    }
525
526    int fd = open(rec->blk_device, O_RDONLY);
527    if (fd == -1) {
528        ERROR("error opening block device %s: %s\n", rec->blk_device, strerror(errno));
529        return;
530    }
531
532    boot_img_hdr hdr;
533    if (android::base::ReadFully(fd, &hdr, sizeof(hdr))) {
534        std::string hex = bytes_to_hex(reinterpret_cast<uint8_t*>(hdr.id), sizeof(hdr.id));
535        property_set("ro.recovery_id", hex.c_str());
536    } else {
537        ERROR("error reading /recovery: %s\n", strerror(errno));
538    }
539
540    close(fd);
541}
542
543void load_system_props() {
544    load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
545    load_properties_from_file(PROP_PATH_VENDOR_BUILD, NULL);
546    load_properties_from_file(PROP_PATH_FACTORY, "ro.*");
547    load_recovery_id_prop();
548}
549
550void start_property_service() {
551    property_set_fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
552                                    0666, 0, 0, NULL);
553    if (property_set_fd == -1) {
554        ERROR("start_property_service socket creation failed: %s\n", strerror(errno));
555        exit(1);
556    }
557
558    listen(property_set_fd, 8);
559
560    register_epoll_handler(property_set_fd, handle_property_set_fd);
561}
562