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  */
57 static const char*
string_copy(char * dst,size_t dstlen,const char * src,size_t srclen)58 string_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  */
79 static void*
map_file(const char * filename,size_t * filesize)80 map_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 
145 EXIT:
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 */
155 static void
unmap_file(void * address,size_t size)156 unmap_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  */
172 static int
check_directory_ownership(const char * path,uid_t uid)173 check_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     /* must be a real directory, not a symlink */
186     if (!S_ISDIR(st.st_mode))
187         goto BAD;
188 
189     /* must be owned by specific uid/gid */
190     if (st.st_uid != uid || st.st_gid != uid)
191         goto BAD;
192 
193     /* must not be readable or writable by others */
194     if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0)
195         goto BAD;
196 
197     /* everything ok */
198     return 0;
199 
200 BAD:
201     errno = EINVAL;
202     return -1;
203 }
204 
205 /* This function is used to check the data directory path for safety.
206  * We check that every sub-directory is owned by the 'system' user
207  * and exists and is not a symlink. We also check that the full directory
208  * path is properly owned by the user ID.
209  *
210  * Return 0 on success, -1 on error.
211  */
212 int
check_data_path(const char * dataPath,uid_t uid)213 check_data_path(const char* dataPath, uid_t  uid)
214 {
215     int  nn;
216 
217     /* the path should be absolute */
218     if (dataPath[0] != '/') {
219         errno = EINVAL;
220         return -1;
221     }
222 
223     /* look for all sub-paths, we do that by finding
224      * directory separators in the input path and
225      * checking each sub-path independently
226      */
227     for (nn = 1; dataPath[nn] != '\0'; nn++)
228     {
229         char subpath[PATH_MAX];
230 
231         /* skip non-separator characters */
232         if (dataPath[nn] != '/')
233             continue;
234 
235         /* handle trailing separator case */
236         if (dataPath[nn+1] == '\0') {
237             break;
238         }
239 
240         /* found a separator, check that dataPath is not too long. */
241         if (nn >= (int)(sizeof subpath)) {
242             errno = EINVAL;
243             return -1;
244         }
245 
246         /* reject any '..' subpath */
247         if (nn >= 3               &&
248             dataPath[nn-3] == '/' &&
249             dataPath[nn-2] == '.' &&
250             dataPath[nn-1] == '.') {
251             errno = EINVAL;
252             return -1;
253         }
254 
255         /* copy to 'subpath', then check ownership */
256         memcpy(subpath, dataPath, nn);
257         subpath[nn] = '\0';
258 
259         if (check_directory_ownership(subpath, AID_SYSTEM) < 0)
260             return -1;
261     }
262 
263     /* All sub-paths were checked, now verify that the full data
264      * directory is owned by the application uid
265      */
266     if (check_directory_ownership(dataPath, uid) < 0)
267         return -1;
268 
269     /* all clear */
270     return 0;
271 }
272 
273 /* Return TRUE iff a character is a space or tab */
274 static inline int
is_space(char c)275 is_space(char c)
276 {
277     return (c == ' ' || c == '\t');
278 }
279 
280 /* Skip any space or tab character from 'p' until 'end' is reached.
281  * Return new position.
282  */
283 static const char*
skip_spaces(const char * p,const char * end)284 skip_spaces(const char*  p, const char*  end)
285 {
286     while (p < end && is_space(*p))
287         p++;
288 
289     return p;
290 }
291 
292 /* Skip any non-space and non-tab character from 'p' until 'end'.
293  * Return new position.
294  */
295 static const char*
skip_non_spaces(const char * p,const char * end)296 skip_non_spaces(const char* p, const char* end)
297 {
298     while (p < end && !is_space(*p))
299         p++;
300 
301     return p;
302 }
303 
304 /* Find the first occurence of 'ch' between 'p' and 'end'
305  * Return its position, or 'end' if none is found.
306  */
307 static const char*
find_first(const char * p,const char * end,char ch)308 find_first(const char* p, const char* end, char ch)
309 {
310     while (p < end && *p != ch)
311         p++;
312 
313     return p;
314 }
315 
316 /* Check that the non-space string starting at 'p' and eventually
317  * ending at 'end' equals 'name'. Return new position (after name)
318  * on success, or NULL on failure.
319  *
320  * This function fails is 'name' is NULL, empty or contains any space.
321  */
322 static const char*
compare_name(const char * p,const char * end,const char * name)323 compare_name(const char* p, const char* end, const char* name)
324 {
325     /* 'name' must not be NULL or empty */
326     if (name == NULL || name[0] == '\0' || p == end)
327         return NULL;
328 
329     /* compare characters to those in 'name', excluding spaces */
330     while (*name) {
331         /* note, we don't check for *p == '\0' since
332          * it will be caught in the next conditional.
333          */
334         if (p >= end || is_space(*p))
335             goto BAD;
336 
337         if (*p != *name)
338             goto BAD;
339 
340         p++;
341         name++;
342     }
343 
344     /* must be followed by end of line or space */
345     if (p < end && !is_space(*p))
346         goto BAD;
347 
348     return p;
349 
350 BAD:
351     return NULL;
352 }
353 
354 /* Parse one or more whitespace characters starting from '*pp'
355  * until 'end' is reached. Updates '*pp' on exit.
356  *
357  * Return 0 on success, -1 on failure.
358  */
359 static int
parse_spaces(const char ** pp,const char * end)360 parse_spaces(const char** pp, const char* end)
361 {
362     const char* p = *pp;
363 
364     if (p >= end || !is_space(*p)) {
365         errno = EINVAL;
366         return -1;
367     }
368     p   = skip_spaces(p, end);
369     *pp = p;
370     return 0;
371 }
372 
373 /* Parse a positive decimal number starting from '*pp' until 'end'
374  * is reached. Adjust '*pp' on exit. Return decimal value or -1
375  * in case of error.
376  *
377  * If the value is larger than INT_MAX, -1 will be returned,
378  * and errno set to EOVERFLOW.
379  *
380  * If '*pp' does not start with a decimal digit, -1 is returned
381  * and errno set to EINVAL.
382  */
383 static int
parse_positive_decimal(const char ** pp,const char * end)384 parse_positive_decimal(const char** pp, const char* end)
385 {
386     const char* p = *pp;
387     int value = 0;
388     int overflow = 0;
389 
390     if (p >= end || *p < '0' || *p > '9') {
391         errno = EINVAL;
392         return -1;
393     }
394 
395     while (p < end) {
396         int      ch = *p;
397         unsigned d  = (unsigned)(ch - '0');
398         int      val2;
399 
400         if (d >= 10U) /* d is unsigned, no lower bound check */
401             break;
402 
403         val2 = value*10 + (int)d;
404         if (val2 < value)
405             overflow = 1;
406         value = val2;
407         p++;
408     }
409     *pp = p;
410 
411     if (overflow) {
412         errno = EOVERFLOW;
413         value = -1;
414     }
415     return value;
416 }
417 
418 /* Read the system's package database and extract information about
419  * 'pkgname'. Return 0 in case of success, or -1 in case of error.
420  *
421  * If the package is unknown, return -1 and set errno to ENOENT
422  * If the package database is corrupted, return -1 and set errno to EINVAL
423  */
424 int
get_package_info(const char * pkgName,uid_t userId,PackageInfo * info)425 get_package_info(const char* pkgName, uid_t userId, PackageInfo *info)
426 {
427     char*        buffer;
428     size_t       buffer_len;
429     const char*  p;
430     const char*  buffer_end;
431     int          result = -1;
432 
433     info->uid          = 0;
434     info->isDebuggable = 0;
435     info->dataDir[0]   = '\0';
436     info->seinfo[0]    = '\0';
437 
438     buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
439     if (buffer == NULL)
440         return -1;
441 
442     p          = buffer;
443     buffer_end = buffer + buffer_len;
444 
445     /* expect the following format on each line of the control file:
446      *
447      *  <pkgName> <uid> <debugFlag> <dataDir> <seinfo>
448      *
449      * where:
450      *  <pkgName>    is the package's name
451      *  <uid>        is the application-specific user Id (decimal)
452      *  <debugFlag>  is 1 if the package is debuggable, or 0 otherwise
453      *  <dataDir>    is the path to the package's data directory (e.g. /data/data/com.example.foo)
454      *  <seinfo>     is the seinfo label associated with the package
455      *
456      * The file is generated in com.android.server.PackageManagerService.Settings.writeLP()
457      */
458 
459     while (p < buffer_end) {
460         /* find end of current line and start of next one */
461         const char*  end  = find_first(p, buffer_end, '\n');
462         const char*  next = (end < buffer_end) ? end + 1 : buffer_end;
463         const char*  q;
464         int          uid, debugFlag;
465 
466         /* first field is the package name */
467         p = compare_name(p, end, pkgName);
468         if (p == NULL)
469             goto NEXT_LINE;
470 
471         /* skip spaces */
472         if (parse_spaces(&p, end) < 0)
473             goto BAD_FORMAT;
474 
475         /* second field is the pid */
476         uid = parse_positive_decimal(&p, end);
477         if (uid < 0)
478             return -1;
479 
480         info->uid = (uid_t) uid;
481 
482         /* skip spaces */
483         if (parse_spaces(&p, end) < 0)
484             goto BAD_FORMAT;
485 
486         /* third field is debug flag (0 or 1) */
487         debugFlag = parse_positive_decimal(&p, end);
488         switch (debugFlag) {
489         case 0:
490             info->isDebuggable = 0;
491             break;
492         case 1:
493             info->isDebuggable = 1;
494             break;
495         default:
496             goto BAD_FORMAT;
497         }
498 
499         /* skip spaces */
500         if (parse_spaces(&p, end) < 0)
501             goto BAD_FORMAT;
502 
503         /* fourth field is data directory path and must not contain
504          * spaces.
505          */
506         q = skip_non_spaces(p, end);
507         if (q == p)
508             goto BAD_FORMAT;
509 
510         /* If userId == 0 (i.e. user is device owner) we can use dataDir value
511          * from packages.list, otherwise compose data directory as
512          * /data/user/$uid/$packageId
513          */
514         if (userId == 0) {
515             p = string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
516         } else {
517             snprintf(info->dataDir,
518                      sizeof info->dataDir,
519                      "/data/user/%d/%s",
520                      userId,
521                      pkgName);
522             p = q;
523         }
524 
525         /* skip spaces */
526         if (parse_spaces(&p, end) < 0)
527             goto BAD_FORMAT;
528 
529         /* fifth field is the seinfo string */
530         q = skip_non_spaces(p, end);
531         if (q == p)
532             goto BAD_FORMAT;
533 
534         string_copy(info->seinfo, sizeof info->seinfo, p, q - p);
535 
536         /* Ignore the rest */
537         result = 0;
538         goto EXIT;
539 
540     NEXT_LINE:
541         p = next;
542     }
543 
544     /* the package is unknown */
545     errno = ENOENT;
546     result = -1;
547     goto EXIT;
548 
549 BAD_FORMAT:
550     errno = EINVAL;
551     result = -1;
552 
553 EXIT:
554     unmap_file(buffer, buffer_len);
555     return result;
556 }
557