1/*
2**
3** Copyright 2010, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17#include <errno.h>
18#include <fcntl.h>
19#include <stdio.h>
20#include <string.h>
21#include <sys/mman.h>
22#include <sys/stat.h>
23#include <unistd.h>
24
25#include <private/android_filesystem_config.h>
26#include "package.h"
27
28/*
29 *  WARNING WARNING WARNING WARNING
30 *
31 *  The following code runs as root on production devices, before
32 *  the run-as command has dropped the uid/gid. Hence be very
33 *  conservative and keep in mind the following:
34 *
35 *  - Performance does not matter here, clarity and safety of the code
36 *    does however. Documentation is a must.
37 *
38 *  - Avoid calling C library functions with complex implementations
39 *    like malloc() and printf(). You want to depend on simple system
40 *    calls instead, which behaviour is not going to be altered in
41 *    unpredictible ways by environment variables or system properties.
42 *
43 *  - Do not trust user input and/or the filesystem whenever possible.
44 *
45 */
46
47/* The file containing the list of installed packages on the system */
48#define PACKAGES_LIST_FILE  "/data/system/packages.list"
49
50/* Copy 'srclen' string bytes from 'src' into buffer 'dst' of size 'dstlen'
51 * This function always zero-terminate the destination buffer unless
52 * 'dstlen' is 0, even in case of overflow.
53 * Returns a pointer into the src string, leaving off where the copy
54 * has stopped. The copy will stop when dstlen, srclen or a null
55 * character on src has been reached.
56 */
57static const char*
58string_copy(char* dst, size_t dstlen, const char* src, size_t srclen)
59{
60    const char* srcend = src + srclen;
61    const char* dstend = dst + dstlen;
62
63    if (dstlen == 0)
64        return src;
65
66    dstend--; /* make room for terminating zero */
67
68    while (dst < dstend && src < srcend && *src != '\0')
69        *dst++ = *src++;
70
71    *dst = '\0'; /* zero-terminate result */
72    return src;
73}
74
75/* Open 'filename' and map it into our address-space.
76 * Returns buffer address, or NULL on error
77 * On exit, *filesize will be set to the file's size, or 0 on error
78 */
79static void*
80map_file(const char* filename, size_t* filesize)
81{
82    int  fd, ret, old_errno;
83    struct stat  st;
84    size_t  length = 0;
85    void*   address = NULL;
86    gid_t   oldegid;
87
88    *filesize = 0;
89
90    /*
91     * Temporarily switch effective GID to allow us to read
92     * the packages file
93     */
94
95    oldegid = getegid();
96    if (setegid(AID_PACKAGE_INFO) < 0) {
97        return NULL;
98    }
99
100    /* open the file for reading */
101    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
102    if (fd < 0) {
103        return NULL;
104    }
105
106    /* restore back to our old egid */
107    if (setegid(oldegid) < 0) {
108        goto EXIT;
109    }
110
111    /* get its size */
112    ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
113    if (ret < 0)
114        goto EXIT;
115
116    /* Ensure that the file is owned by the system user */
117    if ((st.st_uid != AID_SYSTEM) || (st.st_gid != AID_PACKAGE_INFO)) {
118        goto EXIT;
119    }
120
121    /* Ensure that the file has sane permissions */
122    if ((st.st_mode & S_IWOTH) != 0) {
123        goto EXIT;
124    }
125
126    /* Ensure that the size is not ridiculously large */
127    length = (size_t)st.st_size;
128    if ((off_t)length != st.st_size) {
129        errno = ENOMEM;
130        goto EXIT;
131    }
132
133    /* Memory-map the file now */
134    do {
135        address = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
136    } while (address == MAP_FAILED && errno == EINTR);
137    if (address == MAP_FAILED) {
138        address = NULL;
139        goto EXIT;
140    }
141
142    /* We're good, return size */
143    *filesize = length;
144
145EXIT:
146    /* close the file, preserve old errno for better diagnostics */
147    old_errno = errno;
148    close(fd);
149    errno = old_errno;
150
151    return address;
152}
153
154/* unmap the file, but preserve errno */
155static void
156unmap_file(void*  address, size_t  size)
157{
158    int old_errno = errno;
159    TEMP_FAILURE_RETRY(munmap(address, size));
160    errno = old_errno;
161}
162
163/* Check that a given directory:
164 * - exists
165 * - is owned by a given uid/gid
166 * - is a real directory, not a symlink
167 * - isn't readable or writable by others
168 *
169 * Return 0 on success, or -1 on error.
170 * errno is set to EINVAL in case of failed check.
171 */
172static int
173check_directory_ownership(const char* path, uid_t uid)
174{
175    int ret;
176    struct stat st;
177
178    do {
179        ret = lstat(path, &st);
180    } while (ret < 0 && errno == EINTR);
181
182    if (ret < 0)
183        return -1;
184
185    /* /data/user/0 is a known safe symlink */
186    if (strcmp("/data/user/0", path) == 0)
187        return 0;
188
189    /* must be a real directory, not a symlink */
190    if (!S_ISDIR(st.st_mode))
191        goto BAD;
192
193    /* must be owned by specific uid/gid */
194    if (st.st_uid != uid || st.st_gid != uid)
195        goto BAD;
196
197    /* must not be readable or writable by others */
198    if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0)
199        goto BAD;
200
201    /* everything ok */
202    return 0;
203
204BAD:
205    errno = EINVAL;
206    return -1;
207}
208
209/* This function is used to check the data directory path for safety.
210 * We check that every sub-directory is owned by the 'system' user
211 * and exists and is not a symlink. We also check that the full directory
212 * path is properly owned by the user ID.
213 *
214 * Return 0 on success, -1 on error.
215 */
216int
217check_data_path(const char* dataPath, uid_t  uid)
218{
219    int  nn;
220
221    /* the path should be absolute */
222    if (dataPath[0] != '/') {
223        errno = EINVAL;
224        return -1;
225    }
226
227    /* look for all sub-paths, we do that by finding
228     * directory separators in the input path and
229     * checking each sub-path independently
230     */
231    for (nn = 1; dataPath[nn] != '\0'; nn++)
232    {
233        char subpath[PATH_MAX];
234
235        /* skip non-separator characters */
236        if (dataPath[nn] != '/')
237            continue;
238
239        /* handle trailing separator case */
240        if (dataPath[nn+1] == '\0') {
241            break;
242        }
243
244        /* found a separator, check that dataPath is not too long. */
245        if (nn >= (int)(sizeof subpath)) {
246            errno = EINVAL;
247            return -1;
248        }
249
250        /* reject any '..' subpath */
251        if (nn >= 3               &&
252            dataPath[nn-3] == '/' &&
253            dataPath[nn-2] == '.' &&
254            dataPath[nn-1] == '.') {
255            errno = EINVAL;
256            return -1;
257        }
258
259        /* copy to 'subpath', then check ownership */
260        memcpy(subpath, dataPath, nn);
261        subpath[nn] = '\0';
262
263        if (check_directory_ownership(subpath, AID_SYSTEM) < 0)
264            return -1;
265    }
266
267    /* All sub-paths were checked, now verify that the full data
268     * directory is owned by the application uid
269     */
270    if (check_directory_ownership(dataPath, uid) < 0)
271        return -1;
272
273    /* all clear */
274    return 0;
275}
276
277/* Return TRUE iff a character is a space or tab */
278static inline int
279is_space(char c)
280{
281    return (c == ' ' || c == '\t');
282}
283
284/* Skip any space or tab character from 'p' until 'end' is reached.
285 * Return new position.
286 */
287static const char*
288skip_spaces(const char*  p, const char*  end)
289{
290    while (p < end && is_space(*p))
291        p++;
292
293    return p;
294}
295
296/* Skip any non-space and non-tab character from 'p' until 'end'.
297 * Return new position.
298 */
299static const char*
300skip_non_spaces(const char* p, const char* end)
301{
302    while (p < end && !is_space(*p))
303        p++;
304
305    return p;
306}
307
308/* Find the first occurence of 'ch' between 'p' and 'end'
309 * Return its position, or 'end' if none is found.
310 */
311static const char*
312find_first(const char* p, const char* end, char ch)
313{
314    while (p < end && *p != ch)
315        p++;
316
317    return p;
318}
319
320/* Check that the non-space string starting at 'p' and eventually
321 * ending at 'end' equals 'name'. Return new position (after name)
322 * on success, or NULL on failure.
323 *
324 * This function fails is 'name' is NULL, empty or contains any space.
325 */
326static const char*
327compare_name(const char* p, const char* end, const char* name)
328{
329    /* 'name' must not be NULL or empty */
330    if (name == NULL || name[0] == '\0' || p == end)
331        return NULL;
332
333    /* compare characters to those in 'name', excluding spaces */
334    while (*name) {
335        /* note, we don't check for *p == '\0' since
336         * it will be caught in the next conditional.
337         */
338        if (p >= end || is_space(*p))
339            goto BAD;
340
341        if (*p != *name)
342            goto BAD;
343
344        p++;
345        name++;
346    }
347
348    /* must be followed by end of line or space */
349    if (p < end && !is_space(*p))
350        goto BAD;
351
352    return p;
353
354BAD:
355    return NULL;
356}
357
358/* Parse one or more whitespace characters starting from '*pp'
359 * until 'end' is reached. Updates '*pp' on exit.
360 *
361 * Return 0 on success, -1 on failure.
362 */
363static int
364parse_spaces(const char** pp, const char* end)
365{
366    const char* p = *pp;
367
368    if (p >= end || !is_space(*p)) {
369        errno = EINVAL;
370        return -1;
371    }
372    p   = skip_spaces(p, end);
373    *pp = p;
374    return 0;
375}
376
377/* Parse a positive decimal number starting from '*pp' until 'end'
378 * is reached. Adjust '*pp' on exit. Return decimal value or -1
379 * in case of error.
380 *
381 * If the value is larger than INT_MAX, -1 will be returned,
382 * and errno set to EOVERFLOW.
383 *
384 * If '*pp' does not start with a decimal digit, -1 is returned
385 * and errno set to EINVAL.
386 */
387static int
388parse_positive_decimal(const char** pp, const char* end)
389{
390    const char* p = *pp;
391    int value = 0;
392    int overflow = 0;
393
394    if (p >= end || *p < '0' || *p > '9') {
395        errno = EINVAL;
396        return -1;
397    }
398
399    while (p < end) {
400        int      ch = *p;
401        unsigned d  = (unsigned)(ch - '0');
402        int      val2;
403
404        if (d >= 10U) /* d is unsigned, no lower bound check */
405            break;
406
407        val2 = value*10 + (int)d;
408        if (val2 < value)
409            overflow = 1;
410        value = val2;
411        p++;
412    }
413    *pp = p;
414
415    if (overflow) {
416        errno = EOVERFLOW;
417        value = -1;
418    }
419    return value;
420}
421
422/* Read the system's package database and extract information about
423 * 'pkgname'. Return 0 in case of success, or -1 in case of error.
424 *
425 * If the package is unknown, return -1 and set errno to ENOENT
426 * If the package database is corrupted, return -1 and set errno to EINVAL
427 */
428int
429get_package_info(const char* pkgName, uid_t userId, PackageInfo *info)
430{
431    char*        buffer;
432    size_t       buffer_len;
433    const char*  p;
434    const char*  buffer_end;
435    int          result = -1;
436
437    info->uid          = 0;
438    info->isDebuggable = 0;
439    info->dataDir[0]   = '\0';
440    info->seinfo[0]    = '\0';
441
442    buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
443    if (buffer == NULL)
444        return -1;
445
446    p          = buffer;
447    buffer_end = buffer + buffer_len;
448
449    /* expect the following format on each line of the control file:
450     *
451     *  <pkgName> <uid> <debugFlag> <dataDir> <seinfo>
452     *
453     * where:
454     *  <pkgName>    is the package's name
455     *  <uid>        is the application-specific user Id (decimal)
456     *  <debugFlag>  is 1 if the package is debuggable, or 0 otherwise
457     *  <dataDir>    is the path to the package's data directory (e.g. /data/data/com.example.foo)
458     *  <seinfo>     is the seinfo label associated with the package
459     *
460     * The file is generated in com.android.server.PackageManagerService.Settings.writeLP()
461     */
462
463    while (p < buffer_end) {
464        /* find end of current line and start of next one */
465        const char*  end  = find_first(p, buffer_end, '\n');
466        const char*  next = (end < buffer_end) ? end + 1 : buffer_end;
467        const char*  q;
468        int          uid, debugFlag;
469
470        /* first field is the package name */
471        p = compare_name(p, end, pkgName);
472        if (p == NULL)
473            goto NEXT_LINE;
474
475        /* skip spaces */
476        if (parse_spaces(&p, end) < 0)
477            goto BAD_FORMAT;
478
479        /* second field is the pid */
480        uid = parse_positive_decimal(&p, end);
481        if (uid < 0)
482            return -1;
483
484        info->uid = (uid_t) uid;
485
486        /* skip spaces */
487        if (parse_spaces(&p, end) < 0)
488            goto BAD_FORMAT;
489
490        /* third field is debug flag (0 or 1) */
491        debugFlag = parse_positive_decimal(&p, end);
492        switch (debugFlag) {
493        case 0:
494            info->isDebuggable = 0;
495            break;
496        case 1:
497            info->isDebuggable = 1;
498            break;
499        default:
500            goto BAD_FORMAT;
501        }
502
503        /* skip spaces */
504        if (parse_spaces(&p, end) < 0)
505            goto BAD_FORMAT;
506
507        /* fourth field is data directory path and must not contain
508         * spaces.
509         */
510        q = skip_non_spaces(p, end);
511        if (q == p)
512            goto BAD_FORMAT;
513
514        /* If userId == 0 (i.e. user is device owner) we can use dataDir value
515         * from packages.list, otherwise compose data directory as
516         * /data/user/$uid/$packageId
517         */
518        if (userId == 0) {
519            p = string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
520        } else {
521            snprintf(info->dataDir,
522                     sizeof info->dataDir,
523                     "/data/user/%d/%s",
524                     userId,
525                     pkgName);
526            p = q;
527        }
528
529        /* skip spaces */
530        if (parse_spaces(&p, end) < 0)
531            goto BAD_FORMAT;
532
533        /* fifth field is the seinfo string */
534        q = skip_non_spaces(p, end);
535        if (q == p)
536            goto BAD_FORMAT;
537
538        string_copy(info->seinfo, sizeof info->seinfo, p, q - p);
539
540        /* Ignore the rest */
541        result = 0;
542        goto EXIT;
543
544    NEXT_LINE:
545        p = next;
546    }
547
548    /* the package is unknown */
549    errno = ENOENT;
550    result = -1;
551    goto EXIT;
552
553BAD_FORMAT:
554    errno = EINVAL;
555    result = -1;
556
557EXIT:
558    unmap_file(buffer, buffer_len);
559    return result;
560}
561