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