property_service.c revision e4b7b294f37d9b64d6b7c1931e2c9bfb1a500d68
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
28#include <cutils/misc.h>
29#include <cutils/sockets.h>
30#include <cutils/multiuser.h>
31
32#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
33#include <sys/_system_properties.h>
34
35#include <sys/socket.h>
36#include <sys/un.h>
37#include <sys/select.h>
38#include <sys/types.h>
39#include <netinet/in.h>
40#include <sys/mman.h>
41#include <private/android_filesystem_config.h>
42
43#include <selinux/selinux.h>
44#include <selinux/label.h>
45
46#include "property_service.h"
47#include "init.h"
48#include "util.h"
49#include "log.h"
50
51#define PERSISTENT_PROPERTY_DIR  "/data/property"
52
53static int persistent_properties_loaded = 0;
54static int property_area_inited = 0;
55
56static int property_set_fd = -1;
57
58/* White list of permissions for setting property services. */
59struct {
60    const char *prefix;
61    unsigned int uid;
62    unsigned int gid;
63} property_perms[] = {
64    { "net.rmnet0.",      AID_RADIO,    0 },
65    { "net.gprs.",        AID_RADIO,    0 },
66    { "net.ppp",          AID_RADIO,    0 },
67    { "net.qmi",          AID_RADIO,    0 },
68    { "net.lte",          AID_RADIO,    0 },
69    { "net.cdma",         AID_RADIO,    0 },
70    { "ril.",             AID_RADIO,    0 },
71    { "gsm.",             AID_RADIO,    0 },
72    { "persist.radio",    AID_RADIO,    0 },
73    { "net.dns",          AID_RADIO,    0 },
74    { "sys.usb.config",   AID_RADIO,    0 },
75    { "net.",             AID_SYSTEM,   0 },
76    { "dev.",             AID_SYSTEM,   0 },
77    { "runtime.",         AID_SYSTEM,   0 },
78    { "hw.",              AID_SYSTEM,   0 },
79    { "sys.",             AID_SYSTEM,   0 },
80    { "sys.powerctl",     AID_SHELL,    0 },
81    { "service.",         AID_SYSTEM,   0 },
82    { "wlan.",            AID_SYSTEM,   0 },
83    { "gps.",             AID_GPS,      0 },
84    { "bluetooth.",       AID_BLUETOOTH,   0 },
85    { "dhcp.",            AID_SYSTEM,   0 },
86    { "dhcp.",            AID_DHCP,     0 },
87    { "debug.",           AID_SYSTEM,   0 },
88    { "debug.",           AID_SHELL,    0 },
89    { "log.",             AID_SHELL,    0 },
90    { "service.adb.root", AID_SHELL,    0 },
91    { "service.adb.tcp.port", AID_SHELL,    0 },
92    { "persist.logd.size",AID_SYSTEM,   0 },
93    { "persist.sys.",     AID_SYSTEM,   0 },
94    { "persist.service.", AID_SYSTEM,   0 },
95    { "persist.security.", AID_SYSTEM,   0 },
96    { "persist.gps.",      AID_GPS,      0 },
97    { "persist.service.bdroid.", AID_BLUETOOTH,   0 },
98    { "selinux."         , AID_SYSTEM,   0 },
99    { NULL, 0, 0 }
100};
101
102/*
103 * White list of UID that are allowed to start/stop services.
104 * Currently there are no user apps that require.
105 */
106struct {
107    const char *service;
108    unsigned int uid;
109    unsigned int gid;
110} control_perms[] = {
111    { "dumpstate",AID_SHELL, AID_LOG },
112    { "ril-daemon",AID_RADIO, AID_RADIO },
113     {NULL, 0, 0 }
114};
115
116typedef struct {
117    size_t size;
118    int fd;
119} workspace;
120
121static int init_workspace(workspace *w, size_t size)
122{
123    void *data;
124    int fd = open(PROP_FILENAME, O_RDONLY | O_NOFOLLOW);
125    if (fd < 0)
126        return -1;
127
128    w->size = size;
129    w->fd = fd;
130    return 0;
131}
132
133static workspace pa_workspace;
134
135static int init_property_area(void)
136{
137    if (property_area_inited)
138        return -1;
139
140    if(__system_property_area_init())
141        return -1;
142
143    if(init_workspace(&pa_workspace, 0))
144        return -1;
145
146    fcntl(pa_workspace.fd, F_SETFD, FD_CLOEXEC);
147
148    property_area_inited = 1;
149    return 0;
150}
151
152static int check_mac_perms(const char *name, char *sctx)
153{
154    if (is_selinux_enabled() <= 0)
155        return 1;
156
157    char *tctx = NULL;
158    const char *class = "property_service";
159    const char *perm = "set";
160    int result = 0;
161
162    if (!sctx)
163        goto err;
164
165    if (!sehandle_prop)
166        goto err;
167
168    if (selabel_lookup(sehandle_prop, &tctx, name, 1) != 0)
169        goto err;
170
171    if (selinux_check_access(sctx, tctx, class, perm, (void*) name) == 0)
172        result = 1;
173
174    freecon(tctx);
175 err:
176    return result;
177}
178
179static int check_control_mac_perms(const char *name, char *sctx)
180{
181    /*
182     *  Create a name prefix out of ctl.<service name>
183     *  The new prefix allows the use of the existing
184     *  property service backend labeling while avoiding
185     *  mislabels based on true property prefixes.
186     */
187    char ctl_name[PROP_VALUE_MAX+4];
188    int ret = snprintf(ctl_name, sizeof(ctl_name), "ctl.%s", name);
189
190    if (ret < 0 || (size_t) ret >= sizeof(ctl_name))
191        return 0;
192
193    return check_mac_perms(ctl_name, sctx);
194}
195
196/*
197 * Checks permissions for starting/stoping system services.
198 * AID_SYSTEM and AID_ROOT are always allowed.
199 *
200 * Returns 1 if uid allowed, 0 otherwise.
201 */
202static int check_control_perms(const char *name, unsigned int uid, unsigned int gid, char *sctx) {
203
204    int i;
205    if (uid == AID_SYSTEM || uid == AID_ROOT)
206      return check_control_mac_perms(name, sctx);
207
208    /* Search the ACL */
209    for (i = 0; control_perms[i].service; i++) {
210        if (strcmp(control_perms[i].service, name) == 0) {
211            if ((uid && control_perms[i].uid == uid) ||
212                (gid && control_perms[i].gid == gid)) {
213                return check_control_mac_perms(name, sctx);
214            }
215        }
216    }
217    return 0;
218}
219
220/*
221 * Checks permissions for setting system properties.
222 * Returns 1 if uid allowed, 0 otherwise.
223 */
224static int check_perms(const char *name, unsigned int uid, unsigned int gid, char *sctx)
225{
226    int i;
227    unsigned int app_id;
228
229    if(!strncmp(name, "ro.", 3))
230        name +=3;
231
232    if (uid == 0)
233        return check_mac_perms(name, sctx);
234
235    app_id = multiuser_get_app_id(uid);
236    if (app_id == AID_BLUETOOTH) {
237        uid = app_id;
238    }
239
240    for (i = 0; property_perms[i].prefix; i++) {
241        if (strncmp(property_perms[i].prefix, name,
242                    strlen(property_perms[i].prefix)) == 0) {
243            if ((uid && property_perms[i].uid == uid) ||
244                (gid && property_perms[i].gid == gid)) {
245
246                return check_mac_perms(name, sctx);
247            }
248        }
249    }
250
251    return 0;
252}
253
254int __property_get(const char *name, char *value)
255{
256    return __system_property_get(name, value);
257}
258
259static void write_persistent_property(const char *name, const char *value)
260{
261    char tempPath[PATH_MAX];
262    char path[PATH_MAX];
263    int fd;
264
265    snprintf(tempPath, sizeof(tempPath), "%s/.temp.XXXXXX", PERSISTENT_PROPERTY_DIR);
266    fd = mkstemp(tempPath);
267    if (fd < 0) {
268        ERROR("Unable to write persistent property to temp file %s errno: %d\n", tempPath, errno);
269        return;
270    }
271    write(fd, value, strlen(value));
272    fsync(fd);
273    close(fd);
274
275    snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);
276    if (rename(tempPath, path)) {
277        unlink(tempPath);
278        ERROR("Unable to rename persistent property file %s to %s\n", tempPath, path);
279    }
280}
281
282static bool is_legal_property_name(const char* name, size_t namelen)
283{
284    size_t i;
285    bool previous_was_dot = false;
286    if (namelen >= PROP_NAME_MAX) return false;
287    if (namelen < 1) return false;
288    if (name[0] == '.') return false;
289    if (name[namelen - 1] == '.') return false;
290
291    /* Only allow alphanumeric, plus '.', '-', or '_' */
292    /* Don't allow ".." to appear in a property name */
293    for (i = 0; i < namelen; i++) {
294        if (name[i] == '.') {
295            if (previous_was_dot == true) return false;
296            previous_was_dot = true;
297            continue;
298        }
299        previous_was_dot = false;
300        if (name[i] == '_' || name[i] == '-') continue;
301        if (name[i] >= 'a' && name[i] <= 'z') continue;
302        if (name[i] >= 'A' && name[i] <= 'Z') continue;
303        if (name[i] >= '0' && name[i] <= '9') continue;
304        return false;
305    }
306
307    return true;
308}
309
310int property_set(const char *name, const char *value)
311{
312    prop_info *pi;
313    int ret;
314
315    size_t namelen = strlen(name);
316    size_t valuelen = strlen(value);
317
318    if (!is_legal_property_name(name, namelen)) return -1;
319    if (valuelen >= PROP_VALUE_MAX) return -1;
320
321    pi = (prop_info*) __system_property_find(name);
322
323    if(pi != 0) {
324        /* ro.* properties may NEVER be modified once set */
325        if(!strncmp(name, "ro.", 3)) return -1;
326
327        __system_property_update(pi, value, valuelen);
328    } else {
329        ret = __system_property_add(name, namelen, value, valuelen);
330        if (ret < 0) {
331            ERROR("Failed to set '%s'='%s'\n", name, value);
332            return ret;
333        }
334    }
335    /* If name starts with "net." treat as a DNS property. */
336    if (strncmp("net.", name, strlen("net.")) == 0)  {
337        if (strcmp("net.change", name) == 0) {
338            return 0;
339        }
340       /*
341        * The 'net.change' property is a special property used track when any
342        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
343        * contains the last updated 'net.*' property.
344        */
345        property_set("net.change", name);
346    } else if (persistent_properties_loaded &&
347            strncmp("persist.", name, strlen("persist.")) == 0) {
348        /*
349         * Don't write properties to disk until after we have read all default properties
350         * to prevent them from being overwritten by default values.
351         */
352        write_persistent_property(name, value);
353    } else if (strcmp("selinux.reload_policy", name) == 0 &&
354               strcmp("1", value) == 0) {
355        selinux_reload_policy();
356    }
357    property_changed(name, value);
358    return 0;
359}
360
361void handle_property_set_fd()
362{
363    prop_msg msg;
364    int s;
365    int r;
366    int res;
367    struct ucred cr;
368    struct sockaddr_un addr;
369    socklen_t addr_size = sizeof(addr);
370    socklen_t cr_size = sizeof(cr);
371    char * source_ctx = NULL;
372
373    if ((s = accept(property_set_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
374        return;
375    }
376
377    /* Check socket options here */
378    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
379        close(s);
380        ERROR("Unable to receive socket options\n");
381        return;
382    }
383
384    r = TEMP_FAILURE_RETRY(recv(s, &msg, sizeof(msg), 0));
385    if(r != sizeof(prop_msg)) {
386        ERROR("sys_prop: mis-match msg size received: %d expected: %zu errno: %d\n",
387              r, sizeof(prop_msg), errno);
388        close(s);
389        return;
390    }
391
392    switch(msg.cmd) {
393    case PROP_MSG_SETPROP:
394        msg.name[PROP_NAME_MAX-1] = 0;
395        msg.value[PROP_VALUE_MAX-1] = 0;
396
397        if (!is_legal_property_name(msg.name, strlen(msg.name))) {
398            ERROR("sys_prop: illegal property name. Got: \"%s\"\n", msg.name);
399            close(s);
400            return;
401        }
402
403        getpeercon(s, &source_ctx);
404
405        if(memcmp(msg.name,"ctl.",4) == 0) {
406            // Keep the old close-socket-early behavior when handling
407            // ctl.* properties.
408            close(s);
409            if (check_control_perms(msg.value, cr.uid, cr.gid, source_ctx)) {
410                handle_control_message((char*) msg.name + 4, (char*) msg.value);
411            } else {
412                ERROR("sys_prop: Unable to %s service ctl [%s] uid:%d gid:%d pid:%d\n",
413                        msg.name + 4, msg.value, cr.uid, cr.gid, cr.pid);
414            }
415        } else {
416            if (check_perms(msg.name, cr.uid, cr.gid, source_ctx)) {
417                property_set((char*) msg.name, (char*) msg.value);
418            } else {
419                ERROR("sys_prop: permission denied uid:%d  name:%s\n",
420                      cr.uid, msg.name);
421            }
422
423            // Note: bionic's property client code assumes that the
424            // property server will not close the socket until *AFTER*
425            // the property is written to memory.
426            close(s);
427        }
428        freecon(source_ctx);
429        break;
430
431    default:
432        close(s);
433        break;
434    }
435}
436
437void get_property_workspace(int *fd, int *sz)
438{
439    *fd = pa_workspace.fd;
440    *sz = pa_workspace.size;
441}
442
443static void load_properties_from_file(const char *, const char *);
444
445/*
446 * Filter is used to decide which properties to load: NULL loads all keys,
447 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
448 */
449static void load_properties(char *data, const char *filter)
450{
451    char *key, *value, *eol, *sol, *tmp, *fn;
452    size_t flen = 0;
453
454    if (filter) {
455        flen = strlen(filter);
456    }
457
458    sol = data;
459    while ((eol = strchr(sol, '\n'))) {
460        key = sol;
461        *eol++ = 0;
462        sol = eol;
463
464        while (isspace(*key)) key++;
465        if (*key == '#') continue;
466
467        tmp = eol - 2;
468        while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
469
470        if (!strncmp(key, "import ", 7) && flen == 0) {
471            fn = key + 7;
472            while (isspace(*fn)) fn++;
473
474            key = strchr(fn, ' ');
475            if (key) {
476                *key++ = 0;
477                while (isspace(*key)) key++;
478            }
479
480            load_properties_from_file(fn, key);
481
482        } else {
483            value = strchr(key, '=');
484            if (!value) continue;
485            *value++ = 0;
486
487            tmp = value - 2;
488            while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
489
490            while (isspace(*value)) value++;
491
492            if (flen > 0) {
493                if (filter[flen - 1] == '*') {
494                    if (strncmp(key, filter, flen - 1)) continue;
495                } else {
496                    if (strcmp(key, filter)) continue;
497                }
498            }
499
500            property_set(key, value);
501        }
502    }
503}
504
505/*
506 * Filter is used to decide which properties to load: NULL loads all keys,
507 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
508 */
509static void load_properties_from_file(const char *fn, const char *filter)
510{
511    char *data;
512    unsigned sz;
513
514    data = read_file(fn, &sz);
515
516    if(data != 0) {
517        load_properties(data, filter);
518        free(data);
519    }
520}
521
522static void load_persistent_properties()
523{
524    DIR* dir = opendir(PERSISTENT_PROPERTY_DIR);
525    int dir_fd;
526    struct dirent*  entry;
527    char value[PROP_VALUE_MAX];
528    int fd, length;
529    struct stat sb;
530
531    if (dir) {
532        dir_fd = dirfd(dir);
533        while ((entry = readdir(dir)) != NULL) {
534            if (strncmp("persist.", entry->d_name, strlen("persist.")))
535                continue;
536#if HAVE_DIRENT_D_TYPE
537            if (entry->d_type != DT_REG)
538                continue;
539#endif
540            /* open the file and read the property value */
541            fd = openat(dir_fd, entry->d_name, O_RDONLY | O_NOFOLLOW);
542            if (fd < 0) {
543                ERROR("Unable to open persistent property file \"%s\" errno: %d\n",
544                      entry->d_name, errno);
545                continue;
546            }
547            if (fstat(fd, &sb) < 0) {
548                ERROR("fstat on property file \"%s\" failed errno: %d\n", entry->d_name, errno);
549                close(fd);
550                continue;
551            }
552
553            // File must not be accessible to others, be owned by root/root, and
554            // not be a hard link to any other file.
555            if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0)
556                    || (sb.st_uid != 0)
557                    || (sb.st_gid != 0)
558                    || (sb.st_nlink != 1)) {
559                ERROR("skipping insecure property file %s (uid=%u gid=%u nlink=%d mode=%o)\n",
560                      entry->d_name, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid,
561                      sb.st_nlink, sb.st_mode);
562                close(fd);
563                continue;
564            }
565
566            length = read(fd, value, sizeof(value) - 1);
567            if (length >= 0) {
568                value[length] = 0;
569                property_set(entry->d_name, value);
570            } else {
571                ERROR("Unable to read persistent property file %s errno: %d\n",
572                      entry->d_name, errno);
573            }
574            close(fd);
575        }
576        closedir(dir);
577    } else {
578        ERROR("Unable to open persistent property directory %s errno: %d\n", PERSISTENT_PROPERTY_DIR, errno);
579    }
580
581    persistent_properties_loaded = 1;
582}
583
584void property_init(void)
585{
586    init_property_area();
587}
588
589void property_load_boot_defaults(void)
590{
591    load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT, NULL);
592}
593
594int properties_inited(void)
595{
596    return property_area_inited;
597}
598
599static void load_override_properties() {
600#ifdef ALLOW_LOCAL_PROP_OVERRIDE
601    char debuggable[PROP_VALUE_MAX];
602    int ret;
603
604    ret = property_get("ro.debuggable", debuggable);
605    if (ret && (strcmp(debuggable, "1") == 0)) {
606        load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE, NULL);
607    }
608#endif /* ALLOW_LOCAL_PROP_OVERRIDE */
609}
610
611
612/* When booting an encrypted system, /data is not mounted when the
613 * property service is started, so any properties stored there are
614 * not loaded.  Vold triggers init to load these properties once it
615 * has mounted /data.
616 */
617void load_persist_props(void)
618{
619    load_override_properties();
620    /* Read persistent properties after all default values have been loaded. */
621    load_persistent_properties();
622}
623
624void load_all_props(void)
625{
626    load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
627    load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT, NULL);
628    load_properties_from_file(PROP_PATH_FACTORY, "ro.*");
629
630    load_override_properties();
631
632    /* Read persistent properties after all default values have been loaded. */
633    load_persistent_properties();
634}
635
636void start_property_service(void)
637{
638    int fd;
639
640    fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM, 0666, 0, 0, NULL);
641    if(fd < 0) return;
642    fcntl(fd, F_SETFD, FD_CLOEXEC);
643    fcntl(fd, F_SETFL, O_NONBLOCK);
644
645    listen(fd, 8);
646    property_set_fd = fd;
647}
648
649int get_property_set_fd()
650{
651    return property_set_fd;
652}
653