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