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