diff --git a/aosp/bionic/libc/SYSCALLS.TXT b/aosp/bionic/libc/SYSCALLS.TXT new file mode 100644 index 0000000000000000000000000000000000000000..d5cef1e4f3c2497ed3c470eb0db038c38adb6ba4 --- /dev/null +++ b/aosp/bionic/libc/SYSCALLS.TXT @@ -0,0 +1,377 @@ +# This file is used to automatically generate bionic's system call stubs. +# +# Each non-blank, non-comment line has the following format: +# +# return_type func_name[|alias_list][:syscall_name[:socketcall_id]]([parameter_list]) arch_list +# +# where: +# arch_list ::= "all" | arches +# arches ::= arch | arch "," arches +# arch ::= "arm" | "arm64" | "riscv64" | "x86" | "x86_64" | "lp32" | "lp64" +# +# Note: +# - syscall_name corresponds to the name of the syscall, which may differ from +# the exported function name (example: the exit syscall is implemented by the _exit() +# function, which is not the same as the standard C exit() function which calls it) +# +# - alias_list is optional comma separated list of function aliases. +# +# - The call_id parameter, given that func_name and syscall_name have +# been provided, allows the user to specify dispatch style syscalls. +# For example, socket() syscall on i386 actually becomes: +# socketcall(__NR_socket, 1, *(rest of args on stack)). +# +# - Each parameter type is assumed to be stored in 32 bits. +# +# This file is processed by a python script named gensyscalls.py, run via +# genrules in Android.bp. + +# Calls that have historical 16-bit variants camping on the best names (CONFIG_UID16). +uid_t getuid:getuid32() lp32 +uid_t getuid:getuid() lp64 +gid_t getgid:getgid32() lp32 +gid_t getgid:getgid() lp64 +uid_t geteuid:geteuid32() lp32 +uid_t geteuid:geteuid() lp64 +gid_t getegid:getegid32() lp32 +gid_t getegid:getegid() lp64 +uid_t getresuid:getresuid32(uid_t* ruid, uid_t* euid, uid_t* suid) lp32 +uid_t getresuid:getresuid(uid_t* ruid, uid_t* euid, uid_t* suid) lp64 +gid_t getresgid:getresgid32(gid_t* rgid, gid_t* egid, gid_t* sgid) lp32 +gid_t getresgid:getresgid(gid_t* rgid, gid_t* egid, gid_t* sgid) lp64 +int getgroups:getgroups32(int, gid_t*) lp32 +int getgroups:getgroups(int, gid_t*) lp64 +int setgid:setgid32(gid_t) lp32 +int setgid:setgid(gid_t) lp64 +int setuid:setuid32(uid_t) lp32 +int setuid:setuid(uid_t) lp64 +int setreuid:setreuid32(uid_t, uid_t) lp32 +int setreuid:setreuid(uid_t, uid_t) lp64 +int setresuid:setresuid32(uid_t, uid_t, uid_t) lp32 +int setresuid:setresuid(uid_t, uid_t, uid_t) lp64 +int setresgid:setresgid32(gid_t, gid_t, gid_t) lp32 +int setresgid:setresgid(gid_t, gid_t, gid_t) lp64 +int setfsgid:setfsgid32(gid_t) lp32 +int setfsgid:setfsgid(gid_t) lp64 +int setfsuid:setfsuid32(uid_t) lp32 +int setfsuid:setfsuid(uid_t) lp64 + +ssize_t readahead(int, off64_t, size_t) all +pid_t getpgid(pid_t) all +pid_t getppid() all +pid_t getsid(pid_t) all +pid_t setsid() all +int kill(pid_t, int) all +int tgkill(pid_t tgid, pid_t tid, int sig) all + +void* __brk:brk(void*) all +int __execve:execve(const char*, char* const*, char* const*) all +int __ptrace:ptrace(int request, int pid, void* addr, void* data) all + +# +int getrusage(int, struct rusage*) all +int __getpriority:getpriority(int, id_t) all +int setpriority(int, id_t, int) all +# On LP64, rlimit and rlimit64 are the same. +# On 32-bit systems we use prlimit64 to implement the rlimit64 functions. +int getrlimit:ugetrlimit(int, struct rlimit*) lp32 +int getrlimit|getrlimit64(int, struct rlimit*) lp64 +int setrlimit(int, const struct rlimit*) lp32 +int setrlimit|setrlimit64(int, const struct rlimit*) lp64 +int prlimit64|prlimit(pid_t, int, struct rlimit64*, const struct rlimit64*) lp64 +int prlimit64(pid_t, int, struct rlimit64*, const struct rlimit64*) lp32 + +int setgroups:setgroups32(int, const gid_t*) lp32 +int setgroups:setgroups(int, const gid_t*) lp64 +int setpgid(pid_t, pid_t) all +int setregid:setregid32(gid_t, gid_t) lp32 +int setregid:setregid(gid_t, gid_t) lp64 +int chroot(const char*) all +int prctl(int, unsigned long, unsigned long, unsigned long, unsigned long) all +long __arch_prctl:arch_prctl(int, unsigned long) x86_64 +int capget(cap_user_header_t header, cap_user_data_t data) all +int capset(cap_user_header_t header, const cap_user_data_t data) all +int sigaltstack(const stack_t*, stack_t*) all +int acct(const char* filepath) all + +# file descriptors +ssize_t read(int, void*, size_t) all +ssize_t write(int, const void*, size_t) all +ssize_t pread64(int, void*, size_t, off64_t) lp32 +ssize_t pread64|pread(int, void*, size_t, off_t) lp64 +ssize_t pwrite64(int, void*, size_t, off64_t) lp32 +ssize_t pwrite64|pwrite(int, void*, size_t, off_t) lp64 + +# On LP32, preadv/pwritev don't use off64_t --- they use pairs of 32-bit +# arguments to avoid problems on architectures like arm32 where 64-bit arguments +# must be in a register pair starting with an even-numbered register. +# See linux/fs/read_write.c and https://lwn.net/Articles/311630/. +# Note that there's an unused always-0 second long even on LP64! +ssize_t __preadv64:preadv(int, const struct iovec*, int, long, long) all +ssize_t __pwritev64:pwritev(int, const struct iovec*, int, long, long) all +ssize_t __preadv64v2:preadv2(int, const struct iovec*, int, long, long, int) all +ssize_t __pwritev64v2:pwritev2(int, const struct iovec*, int, long, long, int) all + +int __close:close(int) all +int close_range(unsigned int, unsigned int, int) all +ssize_t copy_file_range(int, off64_t*, int, off64_t*, size_t, unsigned int) all +pid_t __getpid:getpid() all +int memfd_create(const char*, unsigned) all +int munmap(void*, size_t) all +void* __mremap:mremap(void*, size_t, size_t, int, void*) all +int msync(const void*, size_t, int) all +int mprotect(const void*, size_t, int) all +int madvise(void*, size_t, int) all +ssize_t process_madvise(int, const struct iovec*, size_t, int, unsigned int) all +int mlock(const void* addr, size_t len) all +int mlock2(const void* addr, size_t len, int flags) all +int munlock(const void* addr, size_t len) all +int mlockall(int flags) all +int munlockall() all +int mincore(void* start, size_t length, unsigned char* vec) all +int __ioctl:ioctl(int, int, void*) all +ssize_t readv(int, const struct iovec*, int) all +ssize_t writev(int, const struct iovec*, int) all +int __fcntl64:fcntl64(int, int, void*) lp32 +int __fcntl:fcntl(int, int, void*) lp64 +int flock(int, int) all +int __fchmod:fchmod(int, mode_t) all +int __pipe2:pipe2(int*, int) all +int __dup:dup(int) all +int __dup3:dup3(int, int, int) all +int fsync(int) all +int fdatasync(int) all +int fchown:fchown32(int, uid_t, gid_t) lp32 +int fchown:fchown(int, uid_t, gid_t) lp64 +void sync(void) all +int syncfs(int) all +int __fsetxattr:fsetxattr(int, const char*, const void*, size_t, int) all +ssize_t __fgetxattr:fgetxattr(int, const char*, void*, size_t) all +ssize_t __flistxattr:flistxattr(int, char*, size_t) all +int fremovexattr(int, const char*) all + +int __getdents64:getdents64(unsigned int, struct dirent*, unsigned int) all + +int __openat:openat(int, const char*, int, mode_t) all +int __faccessat:faccessat(int, const char*, int) all +int __fchmodat:fchmodat(int, const char*, mode_t) all +int fchownat(int, const char*, uid_t, gid_t, int) all +int fstatat64|fstatat:fstatat64(int, const char*, struct stat*, int) lp32 +int fstatat64|fstatat:newfstatat(int, const char*, struct stat*, int) lp64 +int linkat(int, const char*, int, const char*, int) all +int mkdirat(int, const char*, mode_t) all +int mknodat(int, const char*, mode_t, dev_t) all +ssize_t readlinkat(int, const char*, char*, size_t) all +int renameat2(int, const char*, int, const char*, unsigned) all +int symlinkat(const char*, int, const char*) all +int unlinkat(int, const char*, int) all +int utimensat(int, const char*, const struct timespec times[2], int) all + +# Paired off_t/off64_t system calls. On 64-bit systems, +# sizeof(off_t) == sizeof(off64_t), so there we emit two symbols that are +# aliases. On 32-bit systems, we have two different system calls. +# That means that every system call in this section should take three lines. +off_t lseek(int, off_t, int) lp32 +int __llseek:_llseek(int, unsigned long, unsigned long, off64_t*, int) lp32 +off_t lseek|lseek64(int, off_t, int) lp64 +int ftruncate64(int, off64_t) lp32 +int ftruncate|ftruncate64(int, off_t) lp64 +ssize_t sendfile(int out_fd, int in_fd, off_t* offset, size_t count) lp32 +ssize_t sendfile64(int out_fd, int in_fd, off64_t* offset, size_t count) lp32 +ssize_t sendfile|sendfile64(int out_fd, int in_fd, off_t* offset, size_t count) lp64 +int truncate(const char*, off_t) lp32 +int truncate64(const char*, off64_t) lp32 +int truncate|truncate64(const char*, off_t) lp64 +# (mmap only gets two lines because we only used the 64-bit variant on 32-bit systems.) +void* __mmap2:mmap2(void*, size_t, int, int, int, long) lp32 +void* mmap|mmap64(void*, size_t, int, int, int, off_t) lp64 +# (fallocate only gets two lines because there is no 32-bit variant.) +int fallocate64:fallocate(int, int, off64_t, off64_t) lp32 +int fallocate|fallocate64(int, int, off_t, off_t) lp64 + +# posix_fadvise64 is awkward: arm has shuffled arguments, +# the POSIX functions don't set errno, and no architecture has posix_fadvise. +int __arm_fadvise64_64:arm_fadvise64_64(int, int, off64_t, off64_t) arm +int __fadvise64:fadvise64_64(int, off64_t, off64_t, int) x86 +int __fadvise64:fadvise64(int, off64_t, off64_t, int) lp64 + +int __fstatfs64:fstatfs64(int, size_t, struct statfs*) lp32 +int __fstatfs:fstatfs(int, struct statfs*) lp64 +int __statfs64:statfs64(const char*, size_t, struct statfs*) lp32 +int __statfs:statfs(const char*, struct statfs*) lp64 + +int fstat64|fstat:fstat64(int, struct stat*) lp32 +int fstat64|fstat:fstat(int, struct stat*) lp64 + +# file system +int chdir(const char*) all +int mount(const char*, const char*, const char*, unsigned long, const void*) all +int umount2(const char*, int) all +int __getcwd:getcwd(char* buf, size_t size) all +int fchdir(int) all +int setxattr(const char*, const char*, const void*, size_t, int) all +int lsetxattr(const char*, const char*, const void*, size_t, int) all +ssize_t getxattr(const char*, const char*, void*, size_t) all +ssize_t lgetxattr(const char*, const char*, void*, size_t) all +ssize_t listxattr(const char*, char*, size_t) all +ssize_t llistxattr(const char*, char*, size_t) all +int removexattr(const char*, const char*) all +int lremovexattr(const char*, const char*) all +int statx(int, const char*, int, unsigned, struct statx*) all +int swapon(const char*, int) all +int swapoff(const char*) all + +# time +int settimeofday(const struct timeval*, const struct timezone*) all +clock_t times(struct tms*) all +int nanosleep(const struct timespec*, struct timespec*) all +int clock_settime(clockid_t, const struct timespec*) all +int __clock_nanosleep:clock_nanosleep(clockid_t, int, const struct timespec*, struct timespec*) all +int getitimer(int, struct itimerval*) all +int setitimer(int, const struct itimerval*, struct itimerval*) all +int __timer_create:timer_create(clockid_t clockid, struct sigevent* evp, __kernel_timer_t* timerid) all +int __timer_settime:timer_settime(__kernel_timer_t, int, const struct itimerspec*, struct itimerspec*) all +int __timer_gettime:timer_gettime(__kernel_timer_t, struct itimerspec*) all +int __timer_getoverrun:timer_getoverrun(__kernel_timer_t) all +int __timer_delete:timer_delete(__kernel_timer_t) all +int timerfd_create(clockid_t, int) all +int timerfd_settime(int, int, const struct itimerspec*, struct itimerspec*) all +int timerfd_gettime(int, struct itimerspec*) all +int adjtimex(struct timex*) all +int clock_adjtime(clockid_t, struct timex*) all + +# signals +int __sigaction:sigaction(int, const struct sigaction*, struct sigaction*) lp32 +int __rt_sigaction:rt_sigaction(int, const struct sigaction*, struct sigaction*, size_t) all +int __rt_sigpending:rt_sigpending(sigset64_t*, size_t) all +int __rt_sigprocmask:rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t) all +int __rt_sigsuspend:rt_sigsuspend(const sigset64_t*, size_t) all +int __rt_sigtimedwait:rt_sigtimedwait(const sigset64_t*, siginfo_t*, const timespec*, size_t) all +int __rt_sigqueueinfo:rt_sigqueueinfo(pid_t, int, siginfo_t*) all +int __signalfd4:signalfd4(int, const sigset64_t*, size_t, int) all + +# sockets +int __socket:socket(int, int, int) arm,lp64 +int __socketpair:socketpair(int, int, int, int*) arm,lp64 +int bind(int, struct sockaddr*, socklen_t) arm,lp64 +int __connect:connect(int, struct sockaddr*, socklen_t) arm,lp64 +int listen(int, int) arm,lp64 +int __accept4:accept4(int, struct sockaddr*, socklen_t*, int) arm,lp64 +int getsockname(int, struct sockaddr*, socklen_t*) arm,lp64 +int getpeername(int, struct sockaddr*, socklen_t*) arm,lp64 +ssize_t __sendto:sendto(int, const void*, size_t, int, const struct sockaddr*, socklen_t) arm,lp64 +ssize_t recvfrom(int, void*, size_t, unsigned int, struct sockaddr*, socklen_t*) arm,lp64 +int shutdown(int, int) arm,lp64 +int setsockopt(int, int, int, const void*, socklen_t) arm,lp64 +int getsockopt(int, int, int, void*, socklen_t*) arm,lp64 +ssize_t __recvmsg:recvmsg(int, struct msghdr*, unsigned int) arm,lp64 +ssize_t __sendmsg:sendmsg(int, const struct msghdr*, unsigned int) arm,lp64 +int __recvmmsg:recvmmsg(int, struct mmsghdr*, unsigned int, int, const struct timespec*) arm,lp64 +int __sendmmsg:sendmmsg(int, struct mmsghdr*, unsigned int, int) arm,lp64 + +# sockets for x86. These are done as an "indexed" call to socketcall syscall. +int __socket:socketcall:1(int, int, int) x86 +int bind:socketcall:2(int, struct sockaddr*, int) x86 +int __connect:socketcall:3(int, struct sockaddr*, socklen_t) x86 +int listen:socketcall:4(int, int) x86 +int getsockname:socketcall:6(int, struct sockaddr*, socklen_t*) x86 +int getpeername:socketcall:7(int, struct sockaddr*, socklen_t*) x86 +int __socketpair:socketcall:8(int, int, int, int*) x86 +ssize_t __sendto:socketcall:11(int, const void*, size_t, int, const struct sockaddr*, socklen_t) x86 +ssize_t recvfrom:socketcall:12(int, void*, size_t, unsigned int, struct sockaddr*, socklen_t*) x86 +int shutdown:socketcall:13(int, int) x86 +int setsockopt:socketcall:14(int, int, int, const void*, socklen_t) x86 +int getsockopt:socketcall:15(int, int, int, void*, socklen_t*) x86 +int __sendmsg:socketcall:16(int, const struct msghdr*, unsigned int) x86 +int __recvmsg:socketcall:17(int, struct msghdr*, unsigned int) x86 +int __accept4:socketcall:18(int, struct sockaddr*, socklen_t*, int) x86 +int __recvmmsg:socketcall:19(int, struct mmsghdr*, unsigned int, int, const struct timespec*) x86 +int __sendmmsg:socketcall:20(int, struct mmsghdr*, unsigned int, int) x86 + +# scheduler & real-time +int sched_setscheduler(pid_t pid, int policy, const struct sched_param* param) all +int sched_getscheduler(pid_t pid) all +int sched_yield(void) all +int sched_setparam(pid_t pid, const struct sched_param* param) all +int sched_getparam(pid_t pid, struct sched_param* param) all +int sched_get_priority_max(int policy) all +int sched_get_priority_min(int policy) all +int sched_rr_get_interval(pid_t pid, struct timespec* interval) all +int sched_setaffinity(pid_t pid, size_t setsize, const cpu_set_t* set) all +int setns(int, int) all +int unshare(int) all +int __sched_getaffinity:sched_getaffinity(pid_t pid, size_t setsize, cpu_set_t* set) all +int __getcpu:getcpu(unsigned*, unsigned*, void*) all + +# other +int uname(struct utsname*) all +mode_t umask(mode_t) all +int __reboot:reboot(int, int, int, void*) all +int init_module(void*, unsigned long, const char*) all +int delete_module(const char*, unsigned int) all +int klogctl:syslog(int, char*, int) all +int sysinfo(struct sysinfo*) all +int personality(unsigned long) all + +int bpf(int, union bpf_attr *, unsigned int) all + +ssize_t tee(int, int, size_t, unsigned int) all +ssize_t splice(int, off64_t*, int, off64_t*, size_t, unsigned int) all +ssize_t vmsplice(int, const struct iovec*, size_t, unsigned int) all + +int __epoll_create1:epoll_create1(int) all +int epoll_ctl(int, int op, int, struct epoll_event*) all +int __epoll_pwait:epoll_pwait(int, struct epoll_event*, int, int, const sigset64_t*, size_t) all +int __epoll_pwait2:epoll_pwait2(int, struct epoll_event*, int, const timespec64*, const sigset64_t*, size_t) all + +int __eventfd:eventfd2(unsigned int, int) all + +void __exit_group:exit_group(int) all +void __exit:exit(int) all + +int inotify_init1(int) all +int inotify_add_watch(int, const char*, unsigned int) all +int inotify_rm_watch(int, unsigned int) all + +int __pselect6:pselect6(int, fd_set*, fd_set*, fd_set*, timespec*, void*) all +int __ppoll:ppoll(pollfd*, unsigned int, timespec*, const sigset64_t*, size_t) all + +ssize_t process_vm_readv(pid_t, const struct iovec*, unsigned long, const struct iovec*, unsigned long, unsigned long) all +ssize_t process_vm_writev(pid_t, const struct iovec*, unsigned long, const struct iovec*, unsigned long, unsigned long) all + +int quotactl(int, const char*, int, char*) all + +int __set_tid_address:set_tid_address(int*) all + +int setdomainname(const char*, size_t) all +int sethostname(const char*, size_t) all + +int __sync_file_range:sync_file_range(int, off64_t, off64_t, unsigned int) x86,lp64 +int __sync_file_range2:sync_file_range2(int, unsigned int, off64_t, off64_t) arm + +pid_t wait4(pid_t, int*, int, struct rusage*) all +int __waitid:waitid(int, pid_t, siginfo_t*, int, void*) all + +# ARM-specific +int __set_tls:__ARM_NR_set_tls(void*) arm +int cacheflush:__ARM_NR_cacheflush(long start, long end, long flags) arm + +# riscv64-specific +int __riscv_flush_icache:riscv_flush_icache(void*, void*, unsigned long) riscv64 + +# x86-specific +int __set_thread_area:set_thread_area(void*) x86 + +# vdso stuff. +int __clock_getres:clock_getres(clockid_t, struct timespec*) all +int __clock_gettime:clock_gettime(clockid_t, struct timespec*) all +int __gettimeofday:gettimeofday(struct timeval*, struct timezone*) all + +# +ssize_t getrandom(void*, size_t, unsigned) all + +# +int __pidfd_open:pidfd_open(pid_t, unsigned int) all +int __pidfd_getfd:pidfd_getfd(int, int, unsigned int) all +int pidfd_send_signal(int, int, siginfo_t*, unsigned int) all +int kcmp(pid_t pid1, pid_t pid2, int type, unsigned long idx1, unsigned long idx2) all diff --git a/aosp/external/selinux/libselinux/include/selinux/selinux.h b/aosp/external/selinux/libselinux/include/selinux/selinux.h index bd0a4d97d65f2b2ee8fa38d6f1b0b5c7ebd9c0e0..115f818e46a185227684e05d782c3e12eda14b32 100644 --- a/aosp/external/selinux/libselinux/include/selinux/selinux.h +++ b/aosp/external/selinux/libselinux/include/selinux/selinux.h @@ -5,10 +5,10 @@ #include #ifndef aosp_hack -#define aosp_hack() if (1) return +#define aosp_hack() if (!is_selinux_enabled()) return #endif #ifndef aosp_hack_p -#define aosp_hack_p(p) if (1) return p +#define aosp_hack_p(p) if (!is_selinux_enabled()) return p #endif #ifdef __cplusplus diff --git a/aosp/external/selinux/libselinux/src/getpeercon.c b/aosp/external/selinux/libselinux/src/getpeercon.c index e91ab771202f7c5548f8037e91cc443058801133..cd8d036872041a060faaa07e5f7bab5c25902138 100644 --- a/aosp/external/selinux/libselinux/src/getpeercon.c +++ b/aosp/external/selinux/libselinux/src/getpeercon.c @@ -15,10 +15,7 @@ int getpeercon_raw(int fd, char ** context) { char *buf; socklen_t size; - //ssize_t ret; - (void)fd; - - char log[] = "unconfined"; + ssize_t ret; size = INITCONTEXTLEN + 1; buf = malloc(size); @@ -26,10 +23,13 @@ int getpeercon_raw(int fd, char ** context) return -1; memset(buf, 0, size); - memcpy(buf, log, sizeof(log)); - *context = buf; - return 0; -#if 0 + if (!is_selinux_enabled()) { + char log[] = "unconfined"; + memcpy(buf, log, sizeof(log)); + *context = buf; + return 0; + } + ret = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &size); if (ret < 0 && errno == ERANGE) { char *newbuf; @@ -48,7 +48,6 @@ int getpeercon_raw(int fd, char ** context) else *context = buf; return ret; -#endif } diff --git a/aosp/external/selinux/libselinux/src/init.c b/aosp/external/selinux/libselinux/src/init.c index 978adf6c6c8345936b8bbbe98759d8626d51f569..439da41748c824bbaafbb24304b1e912cbee026c 100644 --- a/aosp/external/selinux/libselinux/src/init.c +++ b/aosp/external/selinux/libselinux/src/init.c @@ -139,7 +139,6 @@ void fini_selinuxmnt(void) void set_selinuxmnt(const char *mnt) { - aosp_hack(); selinux_mnt = strdup(mnt); } diff --git a/aosp/frameworks/av/drm/drmserver/DrmManagerService.cpp b/aosp/frameworks/av/drm/drmserver/DrmManagerService.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eac65b870efc7feca880ecc06eb4301a7aaa50c8 --- /dev/null +++ b/aosp/frameworks/av/drm/drmserver/DrmManagerService.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//#define LOG_NDEBUG 0 +#define LOG_TAG "DrmManagerService(Native)" +#include + +#include +#include + +#include +#include +#include +#include +#include +#include "DrmManagerService.h" +#include "DrmManager.h" + +#include + +using namespace android; + +static int selinux_enabled; +static char *drmserver_context; +static Vector trustedUids; + +const char *const DrmManagerService::drm_perm_labels[] = { + "consumeRights", + "setPlaybackStatus", + "openDecryptSession", + "closeDecryptSession", + "initializeDecryptUnit", + "decrypt", + "finalizeDecryptUnit", + "pread" +}; + +const char *DrmManagerService::get_perm_label(drm_perm_t perm) { + unsigned int index = perm; + + if (index >= (sizeof(drm_perm_labels) / sizeof(drm_perm_labels[0]))) { + ALOGE("SELinux: Failed to retrieve permission label(perm=%d).\n", perm); + abort(); + } + return drm_perm_labels[index]; +} + +bool DrmManagerService::selinuxIsProtectedCallAllowed(pid_t spid, const char* ssid, drm_perm_t perm) { + if (selinux_enabled <= 0) { + return true; + } + + char *sctx = NULL; + const char *selinux_class = "drmservice"; + const char *str_perm = get_perm_label(perm); + + if (ssid == NULL) { + android_errorWriteLog(0x534e4554, "121035042"); + + if (getpidcon(spid, &sctx) != 0) { + ALOGE("SELinux: getpidcon(pid=%d) failed.\n", spid); + return false; + } + } + + bool allowed = (selinux_check_access(ssid ? ssid : sctx, drmserver_context, + selinux_class, str_perm, NULL) == 0); + freecon(sctx); + + return allowed; +} + +bool DrmManagerService::isProtectedCallAllowed(drm_perm_t perm) { + // TODO + // Following implementation is just for reference. + // Each OEM manufacturer should implement/replace with their own solutions. + IPCThreadState* ipcState = IPCThreadState::self(); + uid_t uid = ipcState->getCallingUid(); + pid_t spid = ipcState->getCallingPid(); + const char* ssid = ipcState->getCallingSid(); + + for (unsigned int i = 0; i < trustedUids.size(); ++i) { + if (trustedUids[i] == uid) { + return selinuxIsProtectedCallAllowed(spid, ssid, perm); + } + } + return false; +} + +void DrmManagerService::instantiate() { + ALOGV("instantiate"); + sp service = new DrmManagerService(); + service->setRequestingSid(is_selinux_enabled()); + defaultServiceManager()->addService(String16("drm.drmManager"), service); + + if (0 >= trustedUids.size()) { + // TODO + // Following implementation is just for reference. + // Each OEM manufacturer should implement/replace with their own solutions. + + // Add trusted uids here + trustedUids.push(AID_MEDIA); + } + + selinux_enabled = is_selinux_enabled(); + if (selinux_enabled > 0 && getcon(&drmserver_context) != 0) { + ALOGE("SELinux: DrmManagerService failed to get context for DrmManagerService. Aborting.\n"); + abort(); + } + + union selinux_callback cb; + cb.func_log = selinux_log_callback; + selinux_set_callback(SELINUX_CB_LOG, cb); +} + +DrmManagerService::DrmManagerService() : + mDrmManager(NULL) { + ALOGV("created"); + mDrmManager = new DrmManager(); + mDrmManager->initMetricsLooper(); + mDrmManager->loadPlugIns(); +} + +DrmManagerService::~DrmManagerService() { + ALOGV("Destroyed"); + mDrmManager->unloadPlugIns(); + mDrmManager = NULL; +} + +int DrmManagerService::addUniqueId(bool isNative) { + return mDrmManager->addUniqueId(isNative); +} + +void DrmManagerService::removeUniqueId(int uniqueId) { + mDrmManager->removeUniqueId(uniqueId); +} + +void DrmManagerService::addClient(int uniqueId) { + mDrmManager->addClient(uniqueId); +} + +void DrmManagerService::removeClient(int uniqueId) { + mDrmManager->removeClient(uniqueId); +} + +status_t DrmManagerService::setDrmServiceListener( + int uniqueId, const sp& drmServiceListener) { + ALOGV("Entering setDrmServiceListener"); + mDrmManager->setDrmServiceListener(uniqueId, drmServiceListener); + return DRM_NO_ERROR; +} + +DrmConstraints* DrmManagerService::getConstraints( + int uniqueId, const String8* path, const int action) { + ALOGV("Entering getConstraints from content"); + return mDrmManager->getConstraints(uniqueId, path, action); +} + +DrmMetadata* DrmManagerService::getMetadata(int uniqueId, const String8* path) { + ALOGV("Entering getMetadata from content"); + return mDrmManager->getMetadata(uniqueId, path); +} + +bool DrmManagerService::canHandle(int uniqueId, const String8& path, const String8& mimeType) { + ALOGV("Entering canHandle"); + return mDrmManager->canHandle(uniqueId, path, mimeType); +} + +DrmInfoStatus* DrmManagerService::processDrmInfo(int uniqueId, const DrmInfo* drmInfo) { + ALOGV("Entering processDrmInfo"); + return mDrmManager->processDrmInfo(uniqueId, drmInfo); +} + +DrmInfo* DrmManagerService::acquireDrmInfo(int uniqueId, const DrmInfoRequest* drmInfoRequest) { + ALOGV("Entering acquireDrmInfo"); + return mDrmManager->acquireDrmInfo(uniqueId, drmInfoRequest); +} + +status_t DrmManagerService::saveRights( + int uniqueId, const DrmRights& drmRights, + const String8& rightsPath, const String8& contentPath) { + ALOGV("Entering saveRights"); + return mDrmManager->saveRights(uniqueId, drmRights, rightsPath, contentPath); +} + +String8 DrmManagerService::getOriginalMimeType(int uniqueId, const String8& path, int fd) { + ALOGV("Entering getOriginalMimeType"); + return mDrmManager->getOriginalMimeType(uniqueId, path, fd); +} + +int DrmManagerService::getDrmObjectType( + int uniqueId, const String8& path, const String8& mimeType) { + ALOGV("Entering getDrmObjectType"); + return mDrmManager->getDrmObjectType(uniqueId, path, mimeType); +} + +int DrmManagerService::checkRightsStatus( + int uniqueId, const String8& path, int action) { + ALOGV("Entering checkRightsStatus"); + return mDrmManager->checkRightsStatus(uniqueId, path, action); +} + +status_t DrmManagerService::consumeRights( + int uniqueId, sp& decryptHandle, int action, bool reserve) { + ALOGV("Entering consumeRights"); + if (!isProtectedCallAllowed(CONSUME_RIGHTS)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->consumeRights(uniqueId, decryptHandle, action, reserve); +} + +status_t DrmManagerService::setPlaybackStatus( + int uniqueId, sp& decryptHandle, int playbackStatus, int64_t position) { + ALOGV("Entering setPlaybackStatus"); + if (!isProtectedCallAllowed(SET_PLAYBACK_STATUS)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->setPlaybackStatus(uniqueId, decryptHandle, playbackStatus, position); +} + +bool DrmManagerService::validateAction( + int uniqueId, const String8& path, + int action, const ActionDescription& description) { + ALOGV("Entering validateAction"); + return mDrmManager->validateAction(uniqueId, path, action, description); +} + +status_t DrmManagerService::removeRights(int uniqueId, const String8& path) { + ALOGV("Entering removeRights"); + return mDrmManager->removeRights(uniqueId, path); +} + +status_t DrmManagerService::removeAllRights(int uniqueId) { + ALOGV("Entering removeAllRights"); + return mDrmManager->removeAllRights(uniqueId); +} + +int DrmManagerService::openConvertSession(int uniqueId, const String8& mimeType) { + ALOGV("Entering openConvertSession"); + return mDrmManager->openConvertSession(uniqueId, mimeType); +} + +DrmConvertedStatus* DrmManagerService::convertData( + int uniqueId, int convertId, const DrmBuffer* inputData) { + ALOGV("Entering convertData"); + return mDrmManager->convertData(uniqueId, convertId, inputData); +} + +DrmConvertedStatus* DrmManagerService::closeConvertSession(int uniqueId, int convertId) { + ALOGV("Entering closeConvertSession"); + return mDrmManager->closeConvertSession(uniqueId, convertId); +} + +status_t DrmManagerService::getAllSupportInfo( + int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray) { + ALOGV("Entering getAllSupportInfo"); + return mDrmManager->getAllSupportInfo(uniqueId, length, drmSupportInfoArray); +} + +sp DrmManagerService::openDecryptSession( + int uniqueId, int fd, off64_t offset, off64_t length, const char* mime) { + ALOGV("Entering DrmManagerService::openDecryptSession"); + if (isProtectedCallAllowed(OPEN_DECRYPT_SESSION)) { + return mDrmManager->openDecryptSession(uniqueId, fd, offset, length, mime); + } + + return NULL; +} + +sp DrmManagerService::openDecryptSession( + int uniqueId, const char* uri, const char* mime) { + ALOGV("Entering DrmManagerService::openDecryptSession with uri"); + if (isProtectedCallAllowed(OPEN_DECRYPT_SESSION)) { + return mDrmManager->openDecryptSession(uniqueId, uri, mime); + } + + return NULL; +} + +sp DrmManagerService::openDecryptSession( + int uniqueId, const DrmBuffer& buf, const String8& mimeType) { + ALOGV("Entering DrmManagerService::openDecryptSession for streaming"); + if (isProtectedCallAllowed(OPEN_DECRYPT_SESSION)) { + return mDrmManager->openDecryptSession(uniqueId, buf, mimeType); + } + + return NULL; +} + +status_t DrmManagerService::closeDecryptSession(int uniqueId, sp& decryptHandle) { + ALOGV("Entering closeDecryptSession"); + if (!isProtectedCallAllowed(CLOSE_DECRYPT_SESSION)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->closeDecryptSession(uniqueId, decryptHandle); +} + +status_t DrmManagerService::initializeDecryptUnit(int uniqueId, sp& decryptHandle, + int decryptUnitId, const DrmBuffer* headerInfo) { + ALOGV("Entering initializeDecryptUnit"); + if (!isProtectedCallAllowed(INITIALIZE_DECRYPT_UNIT)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->initializeDecryptUnit(uniqueId,decryptHandle, decryptUnitId, headerInfo); +} + +status_t DrmManagerService::decrypt( + int uniqueId, sp& decryptHandle, int decryptUnitId, + const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) { + ALOGV("Entering decrypt"); + if (!isProtectedCallAllowed(DECRYPT)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->decrypt(uniqueId, decryptHandle, decryptUnitId, encBuffer, decBuffer, IV); +} + +status_t DrmManagerService::finalizeDecryptUnit( + int uniqueId, sp& decryptHandle, int decryptUnitId) { + ALOGV("Entering finalizeDecryptUnit"); + if (!isProtectedCallAllowed(FINALIZE_DECRYPT_UNIT)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->finalizeDecryptUnit(uniqueId, decryptHandle, decryptUnitId); +} + +ssize_t DrmManagerService::pread(int uniqueId, sp& decryptHandle, + void* buffer, ssize_t numBytes, off64_t offset) { + ALOGV("Entering pread"); + if (!isProtectedCallAllowed(PREAD)) { + return DRM_ERROR_NO_PERMISSION; + } + return mDrmManager->pread(uniqueId, decryptHandle, buffer, numBytes, offset); +} + +status_t DrmManagerService::dump(int fd, const Vector& args) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + if (checkCallingPermission(String16("android.permission.DUMP")) == false) { + snprintf(buffer, SIZE, "Permission Denial: " + "can't dump DrmManagerService from pid=%d, uid=%d\n", + IPCThreadState::self()->getCallingPid(), + IPCThreadState::self()->getCallingUid()); + result.append(buffer); + } else { +#if DRM_MEMORY_LEAK_TRACK + bool dumpMem = false; + for (size_t i = 0; i < args.size(); i++) { + if (args[i] == String16("-m")) { + dumpMem = true; + } + } + if (dumpMem) { + result.append("\nDumping memory:\n"); + std::string s = dumpMemoryAddresses(100 /* limit */); + result.append(s.c_str(), s.size()); + } +#else + (void)args; +#endif + } + write(fd, result.c_str(), result.size()); + return NO_ERROR; +} + diff --git a/aosp/frameworks/av/media/module/extractors/mpeg2/Android.bp b/aosp/frameworks/av/media/module/extractors/mpeg2/Android.bp new file mode 100644 index 0000000000000000000000000000000000000000..5a20918e22cd300a9243df8867582c1de57409c7 --- /dev/null +++ b/aosp/frameworks/av/media/module/extractors/mpeg2/Android.bp @@ -0,0 +1,88 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_extractors_mpeg2_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_mpeg2_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + +cc_library { + name: "libmpeg2extractor", + + host_supported: true, + target: { + darwin: { + enabled: false, + }, + android: { + shared_libs: ["libvndksupport#29", "libselinux"], + }, + }, + + defaults: ["extractor-defaults"], + + srcs: [ + "ExtractorBundle.cpp", + "MPEG2PSExtractor.cpp", + "MPEG2TSExtractor.cpp", + ], + + export_include_dirs: [ + "include", + ], + + shared_libs: [ + "libbase", + "libcgrouprc#29", + ], + + header_libs: [ + "libaudioclient_headers", + "libbase_headers", + "libstagefright_headers", + "libmedia_datasource_headers", + ], + + static_libs: [ + "android.hardware.cas@1.0", + "android.hardware.cas.native@1.0", + "android.hidl.allocator@1.0", + "android.hidl.memory@1.0", + "android.hidl.token@1.0", + "android.hidl.token@1.0-utils", + "libcutils", + "libhidlbase", + "libhidlmemory", + "libjsoncpp", + "libmedia_helper", + "libprocessgroup", + "libstagefright_esds", + "libstagefright_foundation_without_imemory", + "libstagefright_mpeg2extractor", + "libstagefright_mpeg2support_nocrypto", + "libutils", + ], + + apex_available: [ + "com.android.media", + "test_com.android.media", + ], + + static: { + apex_available: [ + // Needed for unit tests + "//apex_available:platform", + ], + }, +} diff --git a/aosp/frameworks/base/cmds/am/src/com/android/commands/am/Am.java b/aosp/frameworks/base/cmds/am/src/com/android/commands/am/Am.java new file mode 100644 index 0000000000000000000000000000000000000000..b4a428734bf82c3046e6eeb5f199f87a6d061985 --- /dev/null +++ b/aosp/frameworks/base/cmds/am/src/com/android/commands/am/Am.java @@ -0,0 +1,215 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.commands.am; + +import android.app.ActivityManager; +import android.app.IActivityManager; +import android.content.pm.IPackageManager; +import android.os.ParcelFileDescriptor; +import android.os.RemoteException; +import android.os.ResultReceiver; +import android.os.SELinux; +import android.os.ServiceManager; +import android.os.ShellCallback; +import android.os.UserHandle; +import android.util.AndroidException; + +import com.android.internal.os.BaseCommand; + +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; + +public class Am extends BaseCommand { + + private IActivityManager mAm; + private IPackageManager mPm; + + Am() { + svcInit(); + } + + /** + * Command-line entry point. + * + * @param args The command-line arguments + */ + public static void main(String[] args) { + (new Am()).run(args); + } + + private void svcInit() { + mAm = ActivityManager.getService(); + if (mAm == null) { + System.err.println(NO_SYSTEM_ERROR_CODE); + return; + } + + mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package")); + if (mPm == null) { + System.err.println(NO_SYSTEM_ERROR_CODE); + return; + } + } + + @Override + public void onShowUsage(PrintStream out) { + try { + runAmCmd(new String[] { "help" }); + } catch (AndroidException e) { + e.printStackTrace(System.err); + } + } + + @Override + public void onRun() throws Exception { + String op = nextArgRequired(); + + if (op.equals("instrument")) { + runInstrument(); + } else { + runAmCmd(getRawArgs()); + } + } + + int parseUserArg(String arg) { + int userId; + if ("all".equals(arg)) { + userId = UserHandle.USER_ALL; + } else if ("current".equals(arg) || "cur".equals(arg)) { + userId = UserHandle.USER_CURRENT; + } else { + userId = Integer.parseInt(arg); + } + return userId; + } + + static final class MyShellCallback extends ShellCallback { + boolean mActive = true; + + @Override public ParcelFileDescriptor onOpenFile(String path, String seLinuxContext, + String mode) { + if (!mActive) { + System.err.println("Open attempt after active for: " + path); + return null; + } + File file = new File(path); + //System.err.println("Opening file: " + file.getAbsolutePath()); + //Log.i("Am", "Opening file: " + file.getAbsolutePath()); + final ParcelFileDescriptor fd; + try { + fd = ParcelFileDescriptor.open(file, + ParcelFileDescriptor.MODE_CREATE | + ParcelFileDescriptor.MODE_TRUNCATE | + ParcelFileDescriptor.MODE_WRITE_ONLY); + } catch (FileNotFoundException e) { + String msg = "Unable to open file " + path + ": " + e; + System.err.println(msg); + throw new IllegalArgumentException(msg); + } + if (SELinux.isSELinuxEnabled() && seLinuxContext != null) { + final String tcon = SELinux.getFileContext(file.getAbsolutePath()); + if (!SELinux.checkSELinuxAccess(seLinuxContext, tcon, "file", "write")) { + try { + fd.close(); + } catch (IOException e) { + } + String msg = "System server has no access to file context " + tcon; + System.err.println(msg + " (from path " + file.getAbsolutePath() + + ", context " + seLinuxContext + ")"); + throw new IllegalArgumentException(msg); + } + } + return fd; + } + } + + void runAmCmd(String[] args) throws AndroidException { + final MyShellCallback cb = new MyShellCallback(); + try { + mAm.asBinder().shellCommand(FileDescriptor.in, FileDescriptor.out, FileDescriptor.err, + args, cb, new ResultReceiver(null) { }); + } catch (RemoteException e) { + System.err.println(NO_SYSTEM_ERROR_CODE); + throw new AndroidException("Can't call activity manager; is the system running?"); + } finally { + cb.mActive = false; + } + } + + public void runInstrument() throws Exception { + Instrument instrument = new Instrument(mAm, mPm); + + String opt; + while ((opt=nextOption()) != null) { + if (opt.equals("-p")) { + instrument.profileFile = nextArgRequired(); + } else if (opt.equals("-w")) { + instrument.wait = true; + } else if (opt.equals("-r")) { + instrument.rawMode = true; + } else if (opt.equals("-m")) { + instrument.protoStd = true; + } else if (opt.equals("-f")) { + instrument.protoFile = true; + if (peekNextArg() != null && !peekNextArg().startsWith("-")) + instrument.logPath = nextArg(); + } else if (opt.equals("-e")) { + final String argKey = nextArgRequired(); + final String argValue = nextArgRequired(); + instrument.args.putString(argKey, argValue); + } else if (opt.equals("--no_window_animation") + || opt.equals("--no-window-animation")) { + instrument.noWindowAnimation = true; + } else if (opt.equals("--no-hidden-api-checks")) { + instrument.disableHiddenApiChecks = true; + } else if (opt.equals("--no-test-api-access")) { + instrument.disableTestApiChecks = false; + } else if (opt.equals("--no-isolated-storage")) { + instrument.disableIsolatedStorage = true; + } else if (opt.equals("--no-logcat")) { + instrument.captureLogcat = false; + } else if (opt.equals("--user")) { + instrument.userId = parseUserArg(nextArgRequired()); + } else if (opt.equals("--abi")) { + instrument.abi = nextArgRequired(); + } else if (opt.equals("--no-restart")) { + instrument.noRestart = true; + } else if (opt.equals("--always-check-signature")) { + instrument.alwaysCheckSignature = true; + } else if (opt.equals("--instrument-sdk-sandbox")) { + instrument.instrumentSdkSandbox = true; + } else if (opt.equals("--instrument-sdk-in-sandbox")) { + instrument.instrumentSdkSandbox = true; + instrument.instrumentSdkInSandbox = true; + } else { + System.err.println("Error: Unknown option: " + opt); + return; + } + } + + if (instrument.userId == UserHandle.USER_ALL) { + System.err.println("Error: Can't start instrumentation with user 'all'"); + return; + } + + instrument.componentNameArg = nextArgRequired(); + instrument.run(); + } +} diff --git a/aosp/frameworks/base/core/java/android/os/SELinux.java b/aosp/frameworks/base/core/java/android/os/SELinux.java new file mode 100644 index 0000000000000000000000000000000000000000..b40499eafb534a58c952941f155a006585af86db --- /dev/null +++ b/aosp/frameworks/base/core/java/android/os/SELinux.java @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.os; + +import android.compat.annotation.UnsupportedAppUsage; +import android.util.Slog; + +import java.io.File; +import java.io.FileDescriptor; +import java.io.IOException; + +/** + * This class provides access to the centralized jni bindings for + * SELinux interaction. + * {@hide} + */ +public class SELinux { + private static final String TAG = "SELinux"; + + /** Keep in sync with ./external/selinux/libselinux/include/selinux/android.h */ + private static final int SELINUX_ANDROID_RESTORECON_NOCHANGE = 1; + private static final int SELINUX_ANDROID_RESTORECON_VERBOSE = 2; + private static final int SELINUX_ANDROID_RESTORECON_RECURSE = 4; + private static final int SELINUX_ANDROID_RESTORECON_FORCE = 8; + private static final int SELINUX_ANDROID_RESTORECON_DATADATA = 16; + private static final int SELINUX_ANDROID_RESTORECON_SKIPCE = 32; + private static final int SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS = 64; + private static final int SELINUX_ANDROID_RESTORECON_SKIP_SEHASH = 128; + + /** + * Get context associated with path by file_contexts. + * @param path path to the regular file to get the security context for. + * @return a String representing the security context or null on failure. + */ + public static final native String fileSelabelLookup(String path); + + /** + * Determine whether SELinux is disabled or enabled. + * @return a boolean indicating whether SELinux is enabled. + */ + @UnsupportedAppUsage + public static final native boolean isSELinuxEnabled(); + + /** + * Determine whether SELinux is permissive or enforcing. + * @return a boolean indicating whether SELinux is enforcing. + */ + @UnsupportedAppUsage + public static final native boolean isSELinuxEnforced(); + + /** + * Sets the security context for newly created file objects. + * @param context a security context given as a String. + * @return a boolean indicating whether the operation succeeded. + */ + public static final native boolean setFSCreateContext(String context); + + /** + * Change the security context of an existing file object. + * @param path representing the path of file object to relabel. + * @param context new security context given as a String. + * @return a boolean indicating whether the operation succeeded. + */ + public static final native boolean setFileContext(String path, String context); + + /** + * Get the security context of a file object. + * @param path the pathname of the file object. + * @return a security context given as a String. + */ + @UnsupportedAppUsage + public static final native String getFileContext(String path); + + /** + * Get the security context of a peer socket. + * @param fd FileDescriptor class of the peer socket. + * @return a String representing the peer socket security context. + */ + public static final native String getPeerContext(FileDescriptor fd); + + /** + * Get the security context of a file descriptor of a file. + * @param fd FileDescriptor of a file. + * @return a String representing the file descriptor security context. + */ + public static final native String getFileContext(FileDescriptor fd); + + /** + * Gets the security context of the current process. + * @return a String representing the security context of the current process. + */ + @UnsupportedAppUsage + public static final native String getContext(); + + /** + * Gets the security context of a given process id. + * @param pid an int representing the process id to check. + * @return a String representing the security context of the given pid. + */ + @UnsupportedAppUsage + public static final native String getPidContext(int pid); + + /** + * Check permissions between two security contexts. + * @param scon The source or subject security context. + * @param tcon The target or object security context. + * @param tclass The object security class name. + * @param perm The permission name. + * @return a boolean indicating whether permission was granted. + */ + @UnsupportedAppUsage + public static final native boolean checkSELinuxAccess(String scon, String tcon, String tclass, String perm); + + /** + * Restores a file to its default SELinux security context. + * If the system is not compiled with SELinux, then {@code true} + * is automatically returned. + * If SELinux is compiled in, but disabled, then {@code true} is + * returned. + * + * @param pathname The pathname of the file to be relabeled. + * @return a boolean indicating whether the relabeling succeeded. + * @exception NullPointerException if the pathname is a null object. + */ + public static boolean restorecon(String pathname) throws NullPointerException { + if (!isSELinuxEnabled()) { return true; } + if (pathname == null) { throw new NullPointerException(); } + return native_restorecon(pathname, 0); + } + + /** + * Restores a file to its default SELinux security context. + * If the system is not compiled with SELinux, then {@code true} + * is automatically returned. + * If SELinux is compiled in, but disabled, then {@code true} is + * returned. + * + * @param pathname The pathname of the file to be relabeled. + * @return a boolean indicating whether the relabeling succeeded. + */ + private static native boolean native_restorecon(String pathname, int flags); + + /** + * Restores a file to its default SELinux security context. + * If the system is not compiled with SELinux, then {@code true} + * is automatically returned. + * If SELinux is compiled in, but disabled, then {@code true} is + * returned. + * + * @param file The File object representing the path to be relabeled. + * @return a boolean indicating whether the relabeling succeeded. + * @exception NullPointerException if the file is a null object. + */ + public static boolean restorecon(File file) throws NullPointerException { + if (!isSELinuxEnabled()) { return true; } + try { + return native_restorecon(file.getCanonicalPath(), 0); + } catch (IOException e) { + Slog.e(TAG, "Error getting canonical path. Restorecon failed for " + + file.getPath(), e); + return false; + } + } + + /** + * Recursively restores all files under the given path to their default + * SELinux security context. If the system is not compiled with SELinux, + * then {@code true} is automatically returned. If SELinux is compiled in, + * but disabled, then {@code true} is returned. + * + * @return a boolean indicating whether the relabeling succeeded. + */ + @UnsupportedAppUsage + public static boolean restoreconRecursive(File file) { + if (!isSELinuxEnabled()) { return true; } + try { + return native_restorecon(file.getCanonicalPath(), + SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH); + } catch (IOException e) { + Slog.e(TAG, "Error getting canonical path. Restorecon failed for " + + file.getPath(), e); + return false; + } + } +} diff --git a/aosp/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp b/aosp/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp index d178d407236a08287b12396feb9e15e12560a0b3..d68c7bb47363d91b5c48c711f1e7b056cb0c96d6 100644 --- a/aosp/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp +++ b/aosp/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp @@ -2155,7 +2155,7 @@ static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids, // TODO(b/117874058): Remove hardcoded label here. static const char* kSystemServerLabel = "u:r:system_server:s0"; - if (selinux_android_setcon(kSystemServerLabel) != 0) { + if (is_selinux_enabled() && selinux_android_setcon(kSystemServerLabel) != 0) { fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel)); } } @@ -2810,9 +2810,11 @@ static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jc // security_getenforce is not allowed on app process. Initialize and cache // the value before zygote forks. - gIsSecurityEnforced = security_getenforce(); + gIsSecurityEnforced = (security_getenforce() > 0); - selinux_android_seapp_context_init(); + if (is_selinux_enabled()) { + selinux_android_seapp_context_init(); + } /* * Storage Initialization diff --git a/aosp/frameworks/native/cmds/installd/InstalldNativeService.cpp b/aosp/frameworks/native/cmds/installd/InstalldNativeService.cpp index ea9aaab3e0f7effa8e4f76aaf5d00d544063e142..c67c5e5180d9bf504bd469abcb8af56f1c930a1d 100644 --- a/aosp/frameworks/native/cmds/installd/InstalldNativeService.cpp +++ b/aosp/frameworks/native/cmds/installd/InstalldNativeService.cpp @@ -523,6 +523,10 @@ private: */ static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid, bool existing) { + if (!is_selinux_enabled()) { + return 0; + } + ScopedTrace tracer("restorecon-lazy"); if (!existing) { ScopedTrace tracer("new-path"); @@ -810,6 +814,17 @@ void fix_app_path(const char *name, uid_t uid, gid_t gid) { } } +void fix_app_profile_path(const std::string &packageName, uid_t userId, uid_t uid, int32_t appId) { + const std::string profile_dir = + create_primary_current_profile_package_dir_path(userId, packageName); + fix_app_path(profile_dir.c_str(), uid, uid); + + int sharedAppGid = multiuser_get_shared_gid(userId, appId); + const std::string ref_profile_path = + create_primary_reference_profile_package_dir_path(packageName); + fix_app_path(ref_profile_path.c_str(), AID_SYSTEM, sharedAppGid); +} + static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid, int32_t previousUid, int32_t cacheGid, const std::string& seInfo, mode_t targetMode, @@ -840,21 +855,21 @@ static binder::Status createAppDataDirs(const std::string& path, int32_t uid, in } // Consider restorecon over contents if label changed - if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) { + if (is_selinux_enabled() && restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) { return error("Failed to restorecon " + path); } // If the parent dir exists, the restorecon would already have been done // as a part of the recursive restorecon above if (parent_dir_exists && !cache_exists - && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) { + && is_selinux_enabled() && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) { return error("Failed to restorecon " + cache_path); } // If the parent dir exists, the restorecon would already have been done // as a part of the recursive restorecon above if (parent_dir_exists && !code_cache_exists - && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) { + && is_selinux_enabled() && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) { return error("Failed to restorecon " + code_cache_path); } return ok(); @@ -934,7 +949,8 @@ binder::Status InstalldNativeService::createAppDataLocked( } if (!prepare_app_profile_dir(packageName, appId, userId)) { - return error("Failed to prepare profiles for " + packageName); + fix_app_profile_path(packageName, userId, uid, appId); + LOG(WARNING) << "Attemp to fix app profile " << packageName.c_str(); } if (deDataInode != nullptr) { @@ -3561,7 +3577,7 @@ binder::Status InstalldNativeService::createOatDir(const std::string& packageNam if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) { return error("Failed to prepare " + oatDir); } - if (selinux_android_restorecon(oat_dir, 0)) { + if (is_selinux_enabled() && selinux_android_restorecon(oat_dir, 0)) { return error("Failed to restorecon " + oatDir); } snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set); diff --git a/aosp/frameworks/native/cmds/servicemanager/Access.cpp b/aosp/frameworks/native/cmds/servicemanager/Access.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1701e55c80b37b8d7dd7ea5141c8fb6eb7515fc0 --- /dev/null +++ b/aosp/frameworks/native/cmds/servicemanager/Access.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Access.h" + +#include +#include +#include +#include +#include + +namespace android { + +#ifdef VENDORSERVICEMANAGER +constexpr bool kIsVendor = true; +#else +constexpr bool kIsVendor = false; +#endif + +#ifdef __ANDROID__ +static std::string getPidcon(pid_t pid) { + android_errorWriteLog(0x534e4554, "121035042"); + + char* lookup = nullptr; + if (getpidcon(pid, &lookup) < 0) { + LOG(ERROR) << "SELinux: getpidcon(pid=" << pid << ") failed to retrieve pid context"; + return ""; + } + std::string result = lookup; + freecon(lookup); + return result; +} + +static struct selabel_handle* getSehandle() { + static struct selabel_handle* gSehandle = nullptr; + if (gSehandle != nullptr && selinux_status_updated()) { + selabel_close(gSehandle); + gSehandle = nullptr; + } + + if (gSehandle == nullptr) { + gSehandle = kIsVendor + ? selinux_android_vendor_service_context_handle() + : selinux_android_service_context_handle(); + } + + CHECK(gSehandle != nullptr); + return gSehandle; +} + +struct AuditCallbackData { + const Access::CallingContext* context; + const std::string* tname; +}; + +static int auditCallback(void *data, security_class_t /*cls*/, char *buf, size_t len) { + const AuditCallbackData* ad = reinterpret_cast(data); + + if (!ad) { + LOG(ERROR) << "No service manager audit data"; + return 0; + } + + snprintf(buf, len, "pid=%d uid=%d name=%s", ad->context->debugPid, ad->context->uid, + ad->tname->c_str()); + return 0; +} +#endif + +Access::Access() { +#ifdef __ANDROID__ + if (is_selinux_enabled()) { + union selinux_callback cb; + + cb.func_audit = auditCallback; + selinux_set_callback(SELINUX_CB_AUDIT, cb); + + cb.func_log = kIsVendor ? selinux_vendor_log_callback : selinux_log_callback; + selinux_set_callback(SELINUX_CB_LOG, cb); + + CHECK(getcon(&mThisProcessContext) == 0); + } +#endif +} + +Access::~Access() { + freecon(mThisProcessContext); +} + +Access::CallingContext Access::getCallingContext() { +#ifdef __ANDROID__ + IPCThreadState* ipc = IPCThreadState::self(); + + const char* callingSid; + if (is_selinux_enabled()) + callingSid = ipc->getCallingSid(); + else + callingSid = ""; + pid_t callingPid = ipc->getCallingPid(); + + return CallingContext { + .debugPid = callingPid, + .uid = ipc->getCallingUid(), + .sid = callingSid ? std::string(callingSid) : getPidcon(callingPid), + }; +#else + return CallingContext(); +#endif +} + +bool Access::canFind(const CallingContext& ctx,const std::string& name) { + return actionAllowedFromLookup(ctx, name, "find"); +} + +bool Access::canAdd(const CallingContext& ctx, const std::string& name) { + return actionAllowedFromLookup(ctx, name, "add"); +} + +bool Access::canList(const CallingContext& ctx) { + return actionAllowed(ctx, mThisProcessContext, "list", "service_manager"); +} + +bool Access::actionAllowed(const CallingContext& sctx, const char* tctx, const char* perm, + const std::string& tname) { + if (!is_selinux_enabled()) { + return true; + } +#ifdef __ANDROID__ + const char* tclass = "service_manager"; + + AuditCallbackData data = { + .context = &sctx, + .tname = &tname, + }; + + return 0 == selinux_check_access(sctx.sid.c_str(), tctx, tclass, perm, + reinterpret_cast(&data)); +#else + (void)sctx; + (void)tctx; + (void)perm; + (void)tname; + + return true; +#endif +} + +bool Access::actionAllowedFromLookup(const CallingContext& sctx, const std::string& name, const char *perm) { + if (!is_selinux_enabled()) { + return true; + } +#ifdef __ANDROID__ + char *tctx = nullptr; + if (selabel_lookup(getSehandle(), &tctx, name.c_str(), SELABEL_CTX_ANDROID_SERVICE) != 0) { + LOG(ERROR) << "SELinux: No match for " << name << " in service_contexts.\n"; + return false; + } + + bool allowed = actionAllowed(sctx, tctx, perm, name); + freecon(tctx); + return allowed; +#else + (void)sctx; + (void)name; + (void)perm; + (void)kIsVendor; + + return true; +#endif +} + +} // android diff --git a/aosp/frameworks/native/libs/binder/Android.bp b/aosp/frameworks/native/libs/binder/Android.bp new file mode 100644 index 0000000000000000000000000000000000000000..65294905d1674ec794dbdbd4ff35973041c758ac --- /dev/null +++ b/aosp/frameworks/native/libs/binder/Android.bp @@ -0,0 +1,745 @@ +// Copyright (C) 2009 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_native_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_native_license"], +} + +cc_library_headers { + name: "libbinder_headers_base", + export_include_dirs: ["include"], + vendor_available: true, + recovery_available: true, + host_supported: true, + native_bridge_supported: true, + + header_libs: [ + "libbinder_headers_platform_shared", + ], + export_header_lib_headers: [ + "libbinder_headers_platform_shared", + ], + apex_available: [ + "//apex_available:platform", + "com.android.media", + "com.android.media.swcodec", + ], + min_sdk_version: "29", + target: { + darwin: { + enabled: false, + }, + }, + visibility: [ + ":__subpackages__", + ], +} + +cc_library_headers { + name: "libbinder_headers", + vendor_available: true, + recovery_available: true, + host_supported: true, + native_bridge_supported: true, + + header_libs: [ + "libbase_headers", + "libbinder_headers_base", + "libcutils_headers", + "libutils_headers", + ], + export_header_lib_headers: [ + "libbase_headers", + "libbinder_headers_base", + "libcutils_headers", + "libutils_headers", + ], + apex_available: [ + "//apex_available:platform", + "com.android.media", + "com.android.media.swcodec", + ], + min_sdk_version: "29", + target: { + darwin: { + enabled: false, + }, + }, +} + +// These interfaces are android-specific implementation unrelated to binder +// transport itself and should be moved to AIDL or in domain-specific libs. +// +// Currently, these are only on system android (not vendor, not host) +// TODO(b/183654927) - move these into separate libraries + +filegroup { + name: "libbinder_device_interface_sources", + srcs: [ + "IPermissionController.cpp", + "PermissionCache.cpp", + "PermissionController.cpp", + ], +} + +cc_defaults { + name: "libbinder_common_defaults", + host_supported: true, + + srcs: [ + "Binder.cpp", + "BpBinder.cpp", + "Debug.cpp", + "FdTrigger.cpp", + "IInterface.cpp", + "IResultReceiver.cpp", + "Parcel.cpp", + "ParcelFileDescriptor.cpp", + "RecordedTransaction.cpp", + "RpcSession.cpp", + "RpcServer.cpp", + "RpcState.cpp", + "RpcTransportRaw.cpp", + "Stability.cpp", + "Status.cpp", + "TextOutput.cpp", + "Utils.cpp", + "file.cpp", + ], + + header_libs: [ + "libbinder_headers_base", + ], + + cflags: [ + "-Wextra", + "-Wextra-semi", + "-Werror", + "-Wzero-as-null-pointer-constant", + "-Wreorder-init-list", + "-Wunused-const-variable", + "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION", + "-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION", + ], +} + +cc_defaults { + name: "libbinder_android_defaults", + + // TODO(b/31559095): get headers from bionic on host + include_dirs: [ + "bionic/libc/kernel/android/uapi/", + "bionic/libc/kernel/uapi/", + ], + + srcs: [ + "OS_android.cpp", + "OS_unix_base.cpp", + ], + + target: { + host: { + srcs: [ + "UtilsHost.cpp", + ], + }, + }, + + aidl: { + export_aidl_headers: true, + }, + + product_variables: { + debuggable: { + cflags: [ + "-DBINDER_RPC_DEV_SERVERS", + "-DBINDER_ENABLE_RECORDING", + ], + }, + }, + + shared_libs: [ + "libcutils", + "liblog", + "libutils", + "libselinux", + ], + + static_libs: [ + "libbase", + ], + + header_libs: [ + "jni_headers", + "libbinder_headers", + ], + + export_header_lib_headers: [ + "libbinder_headers", + ], + + sanitize: { + misc_undefined: ["integer"], + }, + + tidy: true, + tidy_flags: [ + // Only check our headers + "--header-filter=^.*frameworks/native/libs/binder/.*.h$", + ], + tidy_checks: [ + "-performance-no-int-to-ptr", + ], + tidy_checks_as_errors: [ + // Explicitly list the checks that should not occur in this module. + "abseil-*", + "android-*", + "bugprone-*", + "-bugprone-branch-clone", // b/155034972 + "cert-*", + "clang-analyzer-*", + "google-*", + "misc-*", + "performance*", + "-performance-move-const-arg", // b/273486801 + "portability*", + ], + lto: { + thin: true, + }, +} + +cc_library_headers { + name: "trusty_mock_headers", + host_supported: true, + + export_include_dirs: [ + "trusty/include", + "trusty/include_mock", + ], + + visibility: [ + ":__subpackages__", + ], +} + +cc_defaults { + name: "trusty_mock_defaults", + host_supported: true, + + header_libs: [ + "libbinder_headers_base", + "liblog_stub", + "trusty_mock_headers", + ], + + shared_libs: [ + "libutils_binder_sdk", + ], + + cflags: [ + "-DBINDER_RPC_SINGLE_THREADED", + "-DBINDER_ENABLE_LIBLOG_ASSERT", + "-DBINDER_DISABLE_NATIVE_HANDLE", + "-DBINDER_DISABLE_BLOB", + "-DBINDER_NO_LIBBASE", + // TODO: switch to "vendor: true" rather than copying this + // Trusty libbinder uses vendor stability for its binders + "-D__ANDROID_VENDOR__", + "-D__ANDROID_VNDK__", + "-U__ANDROID__", + "-D__TRUSTY__", + "-DTRUSTY_USERSPACE", + // Flags from the Trusty build system + "-Werror", + "-Wsign-compare", + "-Wno-unused-function", + "-Wno-unused-label", + "-fno-common", + "-fno-omit-frame-pointer", + "-fno-threadsafe-statics", + ], + rtti: false, + + visibility: [ + ":__subpackages__", + ], +} + +cc_library_shared { + name: "libbinder_on_trusty_mock", + defaults: [ + "libbinder_common_defaults", + "trusty_mock_defaults", + ], + + srcs: [ + // Trusty-specific files + "trusty/OS.cpp", + "trusty/RpcServerTrusty.cpp", + "trusty/RpcTransportTipcTrusty.cpp", + "trusty/TrustyStatus.cpp", + "trusty/socket.cpp", + ], +} + +cc_defaults { + name: "libbinder_kernel_defaults", + srcs: [ + "BufferedTextOutput.cpp", + "IPCThreadState.cpp", + "IServiceManager.cpp", + "ProcessState.cpp", + "Static.cpp", + ":libbinder_aidl", + ":libbinder_device_interface_sources", + ], + target: { + vendor: { + exclude_srcs: [ + ":libbinder_device_interface_sources", + ], + }, + host: { + srcs: [ + "ServiceManagerHost.cpp", + ], + }, + android: { + shared_libs: [ + "libapexsupport", + "libvndksupport", + ], + }, + recovery: { + exclude_shared_libs: [ + "libapexsupport", + "libvndksupport", + ], + }, + native_bridge: { + exclude_shared_libs: [ + "libapexsupport", + "libvndksupport", + ], + }, + }, + cflags: [ + "-DBINDER_WITH_KERNEL_IPC", + ], +} + +cc_library { + name: "libbinder", + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + "libbinder_kernel_defaults", + ], + + version_script: "libbinder.map", + + // for vndbinder + vendor_available: true, + vndk: { + enabled: true, + }, + recovery_available: true, + double_loadable: true, + // TODO(b/153609531): remove when no longer needed. + native_bridge_supported: true, + + // libbinder does not offer a stable wire protocol. + // if a second copy of it is installed, then it may break after security + // or dessert updates. Instead, apex users should use libbinder_ndk. + apex_available: [ + "//apex_available:platform", + ], + + srcs: [ + "IMemory.cpp", + "IShellCallback.cpp", + "LazyServiceRegistrar.cpp", + "MemoryBase.cpp", + "MemoryDealer.cpp", + "MemoryHeapBase.cpp", + "ParcelableHolder.cpp", + "PersistableBundle.cpp", + ], + + target: { + android: { + // NOT static to keep the wire protocol unfrozen + static: { + enabled: false, + }, + }, + darwin: { + enabled: false, + }, + recovery: { + exclude_header_libs: [ + "jni_headers", + ], + }, + }, + + afdo: true, +} + +cc_library_host_shared { + name: "libbinder_sdk", + + defaults: [ + "libbinder_common_defaults", + ], + + shared_libs: [ + "libutils_binder_sdk", + ], + + cflags: [ + "-DBINDER_ENABLE_LIBLOG_ASSERT", + "-DBINDER_DISABLE_NATIVE_HANDLE", + "-DBINDER_DISABLE_BLOB", + "-DBINDER_NO_LIBBASE", + ], + + header_libs: [ + "liblog_stub", + ], + + srcs: [ + "OS_non_android_linux.cpp", + "OS_unix_base.cpp", + ], + + visibility: [ + ":__subpackages__", + ], + + target: { + windows: { + enabled: false, + }, + }, +} + +cc_library_static { + name: "libbinder_rpc_no_kernel", + vendor_available: true, + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + ], + visibility: [ + ":__subpackages__", + ], +} + +cc_library_static { + name: "libbinder_rpc_no_blob", + vendor_available: true, + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + "libbinder_kernel_defaults", + ], + cflags: [ + "-DBINDER_DISABLE_BLOB", + ], + visibility: [ + ":__subpackages__", + ], +} + +cc_library_static { + name: "libbinder_rpc_no_native_handle", + vendor_available: true, + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + "libbinder_kernel_defaults", + ], + cflags: [ + "-DBINDER_DISABLE_NATIVE_HANDLE", + ], + visibility: [ + ":__subpackages__", + ], +} + +cc_library_static { + name: "libbinder_rpc_single_threaded", + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + "libbinder_kernel_defaults", + ], + cflags: [ + "-DBINDER_RPC_SINGLE_THREADED", + ], + visibility: [ + ":__subpackages__", + ], +} + +cc_library_static { + name: "libbinder_rpc_single_threaded_no_kernel", + defaults: [ + "libbinder_common_defaults", + "libbinder_android_defaults", + ], + cflags: [ + "-DBINDER_RPC_SINGLE_THREADED", + ], + visibility: [ + ":__subpackages__", + ], +} + +cc_defaults { + name: "libbinder_tls_shared_deps", + shared_libs: [ + "libbinder", + "libcrypto", + "liblog", + "libssl", + "libutils", + ], +} + +cc_defaults { + name: "libbinder_tls_defaults", + defaults: ["libbinder_tls_shared_deps"], + vendor_available: true, + host_supported: true, + + header_libs: [ + "libbinder_headers", + ], + export_header_lib_headers: [ + "libbinder_headers", + ], + export_shared_lib_headers: [ + "libssl", + ], + export_include_dirs: ["include_tls"], + static_libs: [ + "libbase", + ], + srcs: [ + "RpcTransportTls.cpp", + "RpcTlsUtils.cpp", + ], +} + +cc_library_shared { + name: "libbinder_tls", + defaults: ["libbinder_tls_defaults"], +} + +cc_library { + name: "libbinder_trusty", + vendor: true, + srcs: [ + "RpcTransportTipcAndroid.cpp", + "RpcTrusty.cpp", + ], + + shared_libs: [ + "libbinder", + "liblog", + "libtrusty", + "libutils", + ], + static_libs: [ + "libbase", + ], + export_include_dirs: ["include_trusty"], + + // Most of Android doesn't need this library and shouldn't use it, + // so we restrict its visibility to the Trusty-specific packages. + visibility: [ + ":__subpackages__", + "//system/core/trusty:__subpackages__", + "//vendor:__subpackages__", + ], +} + +// For testing +cc_library_static { + name: "libbinder_tls_static", + defaults: ["libbinder_tls_defaults"], + visibility: [ + ":__subpackages__", + ], +} + +// AIDL interface between libbinder and framework.jar +filegroup { + name: "libbinder_aidl", + srcs: [ + "aidl/android/os/ConnectionInfo.aidl", + "aidl/android/os/IClientCallback.aidl", + "aidl/android/os/IServiceCallback.aidl", + "aidl/android/os/IServiceManager.aidl", + "aidl/android/os/ServiceDebugInfo.aidl", + ], + path: "aidl", +} + +aidl_interface { + name: "packagemanager_aidl", + unstable: true, + local_include_dir: "aidl", + host_supported: true, + srcs: [ + "aidl/android/content/pm/IPackageManagerNative.aidl", + "aidl/android/content/pm/IStagedApexObserver.aidl", + "aidl/android/content/pm/ApexStagedEvent.aidl", + "aidl/android/content/pm/StagedApexInfo.aidl", + ], + backend: { + rust: { + apex_available: [ + "com.android.virt", + ], + enabled: true, + }, + }, +} + +aidl_interface { + name: "libbinder_aidl_test_stub", + unstable: true, + local_include_dir: "aidl", + srcs: [":libbinder_aidl"], + vendor_available: true, + backend: { + java: { + enabled: false, + }, + }, + visibility: [ + ":__subpackages__", + "//system/tools/aidl:__subpackages__", + ], +} + +// TODO(b/184872979): remove once the Rust API is created. +cc_library { + name: "libbinder_rpc_unstable", + srcs: ["libbinder_rpc_unstable.cpp"], + shared_libs: [ + "libbase", + "libbinder", + "libbinder_ndk", + "liblog", + "libutils", + ], + export_include_dirs: ["include_rpc_unstable"], + + // enumerate stable entry points, for apex use + stubs: { + symbol_file: "libbinder_rpc_unstable.map.txt", + }, + + // This library is intentionally limited to these targets, and it will be removed later. + // Do not expand the visibility. + visibility: [ + ":__subpackages__", + "//packages/modules/Virtualization:__subpackages__", + "//device/google/cuttlefish/shared/minidroid:__subpackages__", + "//system/software_defined_vehicle:__subpackages__", + ], +} + +// libbinder historically contained additional interfaces that provided specific +// functionality in the platform but have nothing to do with binder itself. These +// are moved out of libbinder in order to avoid the overhead of their vtables. +// If you are working on or own one of these interfaces, the responsible things +// to would be: +// - give them a new home +// - convert them to AIDL instead of having manually written parceling code + +cc_library { + name: "libbatterystats_aidl", + host_supported: true, + srcs: [ + "IBatteryStats.cpp", + ], + export_include_dirs: ["include_batterystats"], + shared_libs: [ + "libbinder", + "libutils", + ], +} + +cc_library { + name: "libprocessinfoservice_aidl", + host_supported: true, + srcs: [ + "IProcessInfoService.cpp", + "ProcessInfoService.cpp", + ], + export_include_dirs: ["include_processinfo"], + shared_libs: [ + "libbinder", + "libutils", + "liblog", + ], +} + +cc_library { + name: "libactivitymanager_aidl", + srcs: [ + "ActivityManager.cpp", + "IActivityManager.cpp", + "IUidObserver.cpp", + ":activity_manager_procstate_aidl", + ], + export_include_dirs: ["include_activitymanager"], + shared_libs: [ + "libbinder", + "libutils", + "liblog", + ], + aidl: { + export_aidl_headers: true, + }, +} + +cc_binary { + name: "servicedispatcher", + host_supported: false, + srcs: [ + "servicedispatcher.cpp", + ], + shared_libs: [ + "libbase", + "libbinder", + "liblog", + "libutils", + "android.debug_aidl-cpp", + ], + static_libs: [ + "libc++fs", + ], +} diff --git a/aosp/frameworks/native/libs/binder/Binder.cpp b/aosp/frameworks/native/libs/binder/Binder.cpp index 1dd1f942831ed4a8a8bcafefe2d6998c0eeb7e38..85b082a73183928a72e1278c636e5958a673c327 100644 --- a/aosp/frameworks/native/libs/binder/Binder.cpp +++ b/aosp/frameworks/native/libs/binder/Binder.cpp @@ -32,6 +32,7 @@ #include #include +#include #ifdef __linux__ #include @@ -506,7 +507,9 @@ void BBinder::setRequestingSid(bool requestingSid) "setRequestingSid() should not be called after a binder object " "is parceled/sent to another process"); - requestingSid = false; + if (!is_selinux_enabled()) { + requestingSid = false; + } Extras* e = mExtras.load(std::memory_order_acquire); diff --git a/aosp/frameworks/native/libs/binder/IPCThreadState.cpp b/aosp/frameworks/native/libs/binder/IPCThreadState.cpp index 50d1b6be8c5289aefab2554ff510c20af1b5c8d9..352184c88c1c6e7bfc96498bb6ade6dc83bd6544 100644 --- a/aosp/frameworks/native/libs/binder/IPCThreadState.cpp +++ b/aosp/frameworks/native/libs/binder/IPCThreadState.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include "binder_module.h" @@ -1376,8 +1377,13 @@ status_t IPCThreadState::executeCommand(int32_t cmd) clearPropagateWorkSource(); mCallingPid = tr.sender_pid; - // mCallingSid = reinterpret_cast(tr_secctx.secctx); - mCallingSid = "KBOX_HACKED"; +#if defined(__ANDROID__) + if (is_selinux_enabled()) { + mCallingSid = reinterpret_cast(tr_secctx.secctx); + } else { + mCallingSid = ""; + } +#endif mCallingUid = tr.sender_euid; mHasExplicitIdentity = false; mLastTransactionBinderFlags = tr.flags; diff --git a/aosp/frameworks/native/libs/binder/ProcessState.cpp b/aosp/frameworks/native/libs/binder/ProcessState.cpp index 08e26e04d389b788d99ec4f52b4c17e5b0fce66a..2fdece438826c88028b08d993eb5675a7cdd00b5 100644 --- a/aosp/frameworks/native/libs/binder/ProcessState.cpp +++ b/aosp/frameworks/native/libs/binder/ProcessState.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2) #define DEFAULT_MAX_BINDER_THREADS 15 @@ -208,14 +209,14 @@ bool ProcessState::becomeContextManager() { std::unique_lock _l(mLock); -#if 0 - flat_binder_object obj { - .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX, - }; + flat_binder_object obj; + if (is_selinux_enabled()) { + obj.flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX; + } else { + memset(&obj, 0, sizeof(obj)); + } int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj); -#endif - int result = 1; // fallback to original method if (result != 0) { diff --git a/aosp/packages/modules/Bluetooth/android/app/Android.bp b/aosp/packages/modules/Bluetooth/android/app/Android.bp index 835fb9f9317ac8d5beb46f9eec0ce7dc765d920f..a4d1eb47e037ebfb96d5d88eabb2f9cbe0a6c9f0 100644 --- a/aosp/packages/modules/Bluetooth/android/app/Android.bp +++ b/aosp/packages/modules/Bluetooth/android/app/Android.bp @@ -156,6 +156,7 @@ cc_library_shared { "libnativehelper", "libstatssocket", "libvndksupport", + "libselinux", ], sanitize: { scs: true, diff --git a/aosp/packages/modules/NeuralNetworks/runtime/Android.bp b/aosp/packages/modules/NeuralNetworks/runtime/Android.bp new file mode 100644 index 0000000000000000000000000000000000000000..f6b8daf31d2915a624567fefa37469a0ee8a0b42 --- /dev/null +++ b/aosp/packages/modules/NeuralNetworks/runtime/Android.bp @@ -0,0 +1,357 @@ +/* + * Copyright 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package { + default_applicable_licenses: [ + "packages_modules_NeuralNetworks_runtime_license", + ], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "packages_modules_NeuralNetworks_runtime_license", + package_name: "Android Neural Networks API Runtime", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + "SPDX-license-identifier-MPL", + "SPDX-license-identifier-MPL-2.0", + ], + license_text: [ + "NOTICE", + ], +} + +cc_library_headers { + name: "libneuralnetworks_headers", + host_supported: true, + vendor_available: true, + export_include_dirs: ["include"], + min_sdk_version: "30", + apex_available: [ + "com.android.neuralnetworks", + "test_com.android.neuralnetworks", // Due to the dependency from libneuralnetworks_common + // that is available to the platform + + "//apex_available:platform", + ], +} + +cc_library_headers { + name: "libneuralnetworks_headers_ndk", + host_supported: true, + export_include_dirs: ["include"], + sdk_version: "current", +} + +cc_library_headers { + name: "libneuralnetworks_private_headers", + host_supported: true, + export_include_dirs: ["."], +} + +cc_defaults { + name: "libneuralnetworks_defaults", + defaults: ["neuralnetworks_use_latest_utils_hal_aidl"], + host_supported: true, + use_version_lib: true, + // b/109953668, disable OpenMP + // openmp: true, + srcs: [ + "AppInfoFetcher.cpp", + "BurstBuilder.cpp", + "CompilationBuilder.cpp", + "ExecutionBuilder.cpp", + "ExecutionCallback.cpp", + "ExecutionPlan.cpp", + "Manager.cpp", + "Memory.cpp", + "ModelArchHasher.cpp", + "ModelArgumentInfo.cpp", + "ModelBuilder.cpp", + "NeuralNetworks.cpp", + "ServerFlag.cpp", + "Telemetry.cpp", + "TypeManager.cpp", + ], + target: { + android: { + version_script: "libneuralnetworks.map.txt", + generated_sources: ["statslog_neuralnetworks.cpp"], + generated_headers: ["statslog_neuralnetworks.h"], + srcs: [ + "TelemetryStatsd.cpp", + ], + shared_libs: [ + "libnativewindow", + "libstatssocket", + "libvndksupport", + "libselinux", + ], + whole_static_libs: [ + "libprocpartition", + ], + }, + host: { + cflags: [ + "-D__INTRODUCED_IN(n)=", + ], + }, + }, + + // TODO(pszczepaniak, b/144488395): Use system libnativewindow, + // this would remove half of dependencies here. + static_libs: [ + "android.hardware.neuralnetworks@1.0", + "android.hardware.neuralnetworks@1.1", + "android.hardware.neuralnetworks@1.2", + "android.hardware.neuralnetworks@1.3", + "android.hidl.allocator@1.0", + "android.hidl.memory@1.0", + "libaidlcommonsupport", + "libbase", + "libcrypto_static", + "libcutils", + "libfmq", + "libhidlbase", + "libhidlmemory", + "libjsoncpp", + "libmath", + "libneuralnetworks_common", + "libprocessgroup", + "libtextclassifier_hash_static", + "libutils", + "neuralnetworks_types", + "neuralnetworks_utils_hal_service", + "server_configurable_flags", + ], + + stl: "libc++_static", + + shared_libs: [ + "libbinder_ndk", + "libcgrouprc", + "liblog", + "libneuralnetworks_packageinfo", + ], + + header_libs: [ + "libneuralnetworks_headers", + ], + + export_header_lib_headers: [ + "libneuralnetworks_headers", + ], +} + +cc_defaults { + name: "libneuralnetworks_v2_defaults", + defaults: ["libneuralnetworks_defaults"], + srcs: [ + "FlatbufferModelBuilder.cpp", + "NeuralNetworksV2.cpp", + "operation_converters/AddOperationConverter.cpp", + "operation_converters/ArithmeticOperationConverter.cpp", + "operation_converters/Conv2DOperationConverter.cpp", + "operation_converters/DepthwiseConv2DOperationConverter.cpp", + "operation_converters/LogisticOperationConverter.cpp", + "operation_converters/OperationConverterResolver.cpp", + "operation_converters/SubGraphContext.cpp", + ], + + exclude_srcs: [ + "NeuralNetworks.cpp", + ], + + static_libs: [ + "libtflite_static", + ], + + include_dirs: [ + "external/flatbuffers/include", + "external/tensorflow", + ], +} + +cc_library_shared { + name: "libneuralnetworks", + llndk: { + symbol_file: "libneuralnetworks.map.txt", + override_export_include_dirs: ["include"], + }, + defaults: [ + "libneuralnetworks_defaults", + "neuralnetworks_defaults", + ], + min_sdk_version: "30", + apex_available: [ + "com.android.neuralnetworks", + "test_com.android.neuralnetworks", + ], + stubs: { + versions: [ + "30", + "31", + ], + symbol_file: "libneuralnetworks.map.txt", + }, +} + +// Required for tests (b/147158681) +cc_library_static { + name: "libneuralnetworks_static", + defaults: [ + "libneuralnetworks_defaults", + "neuralnetworks_defaults", + ], + apex_available: ["//apex_available:platform"], +} + +// Required for tests (b/147158681) +cc_library_static { + name: "libneuralnetworks_static_experimental", + defaults: [ + "libneuralnetworks_defaults", + "neuralnetworks_defaults", + ], + exclude_static_libs: [ + "libneuralnetworks_common", + "neuralnetworks_types", + "server_configurable_flags", + ], + static_libs: [ + "libneuralnetworks_common_experimental", + "neuralnetworks_types_experimental", + ], + cflags: ["-DNN_EXPERIMENTAL_FEATURE"], + apex_available: ["//apex_available:platform"], +} + +cc_library_static { + name: "libneuralnetworks_v2_static_experimental", + defaults: [ + "libneuralnetworks_v2_defaults", + "neuralnetworks_defaults", + ], + exclude_static_libs: [ + "libneuralnetworks_common", + "neuralnetworks_types", + "server_configurable_flags", + ], + static_libs: [ + "libneuralnetworks_common_experimental", + "neuralnetworks_types_experimental", + ], + cflags: ["-DNN_EXPERIMENTAL_FEATURE"], +} + +cc_library_static { + name: "libneuralnetworks_cl", + defaults: [ + "neuralnetworks_cl_defaults", + "neuralnetworks_defaults", + ], + host_supported: false, + apex_available: ["//apex_available:platform"], + // b/109953668, disable OpenMP + // openmp: true, + srcs: [ + "BurstBuilder.cpp", + "CompilationBuilder.cpp", + "ExecutionBuilder.cpp", + "ExecutionCallback.cpp", + "ExecutionPlan.cpp", + "Manager.cpp", + "Memory.cpp", + "ModelArchHasher.cpp", + "ModelArgumentInfo.cpp", + "ModelBuilder.cpp", + "NeuralNetworks.cpp", + "ServerFlag.cpp", + "SupportLibraryDiagnostic.cpp", + "Telemetry.cpp", + "TypeManager.cpp", + ], + static_libs: [ + "libbase_ndk", + "libcrypto_static", + "libneuralnetworks_common_cl", + "neuralnetworks_types_cl", + ], + shared_libs: [ + "libnativewindow", + ], + header_libs: [ + "libneuralnetworks_headers_ndk", + "neuralnetworks_supportlibrary_types_ndk", + ], + export_header_lib_headers: [ + "libneuralnetworks_headers_ndk", + ], +} + +ndk_headers { + name: "libneuralnetworks_ndk_headers", + from: "include", + to: "android", + srcs: [ + "include/NeuralNetworks.h", + "include/NeuralNetworksTypes.h", + ], + license: "NOTICE", +} + +ndk_library { + name: "libneuralnetworks", + symbol_file: "libneuralnetworks.map.txt", + // Android O-MR1 + first_version: "27", + export_header_libs: [ + "libneuralnetworks_ndk_headers", + ], +} + +genrule { + name: "statslog_neuralnetworks.h", + tools: ["stats-log-api-gen"], + cmd: "$(location stats-log-api-gen) --header $(genDir)/statslog_neuralnetworks.h --module neuralnetworks --namespace android,nn,stats", + out: [ + "statslog_neuralnetworks.h", + ], +} + +genrule { + name: "statslog_neuralnetworks.cpp", + tools: ["stats-log-api-gen"], + cmd: "$(location stats-log-api-gen) --cpp $(genDir)/statslog_neuralnetworks.cpp --module neuralnetworks --namespace android,nn,stats --importHeader statslog_neuralnetworks.h", + out: [ + "statslog_neuralnetworks.cpp", + ], +} diff --git a/aosp/packages/modules/adb/daemon/main.cpp b/aosp/packages/modules/adb/daemon/main.cpp index 4cedaf463139d610cb0cdf93534eaba604856a12..27134036e3b677d89c6ec55eb45880ad4e202ff4 100644 --- a/aosp/packages/modules/adb/daemon/main.cpp +++ b/aosp/packages/modules/adb/daemon/main.cpp @@ -155,7 +155,7 @@ static void drop_privileges(int server_port) { minijail_enter(jail.get()); if (root_seclabel != nullptr) { - if (selinux_android_setcon(root_seclabel) < 0) { + if (is_selinux_enabled() && selinux_android_setcon(root_seclabel) < 0) { // If we failed to become root, don't try again to avoid a // restart loop. android::base::SetProperty("service.adb.root", "0"); diff --git a/aosp/system/core/init/init.cpp b/aosp/system/core/init/init.cpp index 297588bd39c4d7aca6f451e630812772766cffab..d50a7f5036c5f642b264fcbb943659ab4ddd5f4b 100644 --- a/aosp/system/core/init/init.cpp +++ b/aosp/system/core/init/init.cpp @@ -896,11 +896,11 @@ static void RecordStageBoottimes(const boot_clock::time_point& second_stage_star SetProperty("ro.boottime.init.first_stage", std::to_string(selinux_start_time_ns - first_stage_start_time_ns)); -#if 0 - SetProperty("ro.boottime.init.selinux", - std::to_string(second_stage_start_time.time_since_epoch().count() - - selinux_start_time_ns)); -#endif + if (is_selinux_enabled()) { + SetProperty("ro.boottime.init.selinux", + std::to_string(second_stage_start_time.time_since_epoch().count() - + selinux_start_time_ns)); + } if (auto init_module_time_str = getenv(kEnvInitModuleDurationMs); init_module_time_str) { SetProperty("ro.boottime.init.modules", init_module_time_str); unsetenv(kEnvInitModuleDurationMs); @@ -966,8 +966,9 @@ int SecondStageMain(int argc, char** argv) { // InitKernelLogging(argv); LOG(INFO) << "init second stage started!"; - SelinuxSetupKernelLogging(); - + if (is_selinux_enabled()) { + SelinuxSetupKernelLogging(); + } // Update $PATH in the case the second stage init is newer than first stage init, where it is // first set. if (setenv("PATH", _PATH_DEFPATH, 1) != 0) { @@ -1023,9 +1024,17 @@ int SecondStageMain(int argc, char** argv) { MountExtraFilesystems(); // Now set up SELinux for second stage. - SelabelInitialize(); - SelinuxRestoreContext(); - + if (is_selinux_enabled()) { + SelabelInitialize(); + SelinuxRestoreContext(); + } + if (is_selinux_enabled()) { + if (setcon("u:r:init:s0") < 0) { + LOG(INFO) << "set context for init failed."; + } else { + LOG(INFO) << "set context for init success."; + } + } Epoll epoll; if (auto result = epoll.Open(); !result.ok()) { PLOG(FATAL) << result.error(); @@ -1062,7 +1071,9 @@ int SecondStageMain(int argc, char** argv) { PLOG(FATAL) << "SetupMountNamespaces failed"; } - InitializeSubcontext(); + if (is_selinux_enabled()) { + InitializeSubcontext(); + } ActionManager& am = ActionManager::GetInstance(); ServiceList& sm = ServiceList::GetInstance(); diff --git a/aosp/system/core/init/property_service.cpp b/aosp/system/core/init/property_service.cpp index d2ebb049a94f7f515d04a0db3ec6d8a7c9aa766c..ba82a2178d024485fb79d63637dbba59275d3c8f 100644 --- a/aosp/system/core/init/property_service.cpp +++ b/aosp/system/core/init/property_service.cpp @@ -176,6 +176,12 @@ bool CanReadProperty(const std::string& source_context, const std::string& name) static bool CheckMacPerms(const std::string& name, const char* target_context, const char* source_context, const ucred& cr) { + (void)name; + (void)target_context; + (void)source_context; + (void)cr; + return true; +#if 0 if (!target_context || !source_context) { return false; } @@ -188,6 +194,7 @@ static bool CheckMacPerms(const std::string& name, const char* target_context, auto lock = std::lock_guard{selinux_check_access_lock}; return selinux_check_access(source_context, target_context, "property_service", "set", &audit_data) == 0; +#endif } void NotifyPropertyChange(const std::string& name, const std::string& value) { @@ -285,6 +292,10 @@ class SocketConnection { } bool GetSourceContext(std::string* source_context) const { + if (!is_selinux_enabled()) { + *source_context = ""; + return true; + } char* c_source_context = nullptr; if (getpeercon(socket_.get(), &c_source_context) != 0) { return false; @@ -525,7 +536,7 @@ uint32_t CheckPermissions(const std::string& name, const std::string& value, const char* type = nullptr; property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type); - if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) { + if (is_selinux_enabled() && !CheckMacPerms(name, target_context, source_context.c_str(), cr)) { *error = "SELinux permission check failed"; return PROP_ERROR_PERMISSION_DENIED; } diff --git a/aosp/system/core/init/selinux.cpp b/aosp/system/core/init/selinux.cpp index 50d7c48b1eac08fcfa4bcce916f33732f5bfc196..81cabb35acf7c4616d2313c801f5a3b29a79bdc8 100644 --- a/aosp/system/core/init/selinux.cpp +++ b/aosp/system/core/init/selinux.cpp @@ -105,7 +105,9 @@ EnforcingStatus StatusFromProperty() { } bool IsEnforcing() { - aosp_hack_p(false); + if (!is_selinux_enabled()) + return false; + if (ALLOW_PERMISSIVE_SELINUX) { return StatusFromProperty() == SELINUX_ENFORCING; } @@ -506,6 +508,52 @@ void SelinuxSetEnforcement() { } } +// selinux namespace接口 +const char namespace_interface[] = "/sys/fs/selinux/ns"; +// aosp11使用的selinux namespace名字复用为aosp9,保持aosp9的命名空间不动。 +const char selinux_namespace[] = "aosp9"; + +/** + * @brief 创建容器使用的selinux namespace,等同于命令:echo aosp11 > /sys/fs/selinux/unshare, + * 因为namespace跟进程init关联,所以安卓所有的进程(均为init的子孙进程)都处在同样的namespace下面; + */ +void InitSelinuxNamespace() { + int fd = open(namespace_interface, O_RDWR | O_NOFOLLOW); + if (fd < 0) { + LOG(ERROR) << "error open " << namespace_interface << ", errno " << errno; + return; + } + int ret = write(fd, selinux_namespace, strlen(selinux_namespace)); + if (ret == -1) { + LOG(ERROR) << "error write " << namespace_interface << ", errno " << errno; + } else { + LOG(INFO) << "init selinux namespace " << selinux_namespace; + } + close(fd); +} + +/** + * @brief 读取当前的selinux namespace,主要用来校验namespace生效,等同于命令:cat /sys/fs/selinux/unshare + * + */ +void ReadSelinuxNamespace() { + int fd = open(namespace_interface, O_RDWR | O_NOFOLLOW); + if (fd < 0) { + LOG(ERROR) << "error open " << namespace_interface << ", errno " << errno; + return; + } + const int namepaceLength = 51; + char ns[namepaceLength] = { 0 }; + int ret = read(fd, ns, namepaceLength - 1); + if (ret == -1) { + LOG(ERROR) << "error read " << namespace_interface << ", errno " << errno; + } else { + LOG(INFO) << "read selinux namespace " << ns; + } + close(fd); +} + + constexpr size_t kKlogMessageSize = 1024; void SelinuxAvcLog(char* buf) { @@ -537,34 +585,23 @@ int RestoreconIfExists(const char* path, unsigned int flags) { } // namespace +/** + * @brief 精简版本SelinuxInitialize,不做加载SELinux策略的动作,只设置selinux_mnt变量 + * + */ +void SelinuxInitializeWithoutLoadPolicy() { + Timer t; + + LOG(INFO) << "Skip Loading SELinux policy"; + set_selinuxmnt("/sys/fs/selinux"); + // init's first stage can't set properties, so pass the time to the second stage. + setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1); +} + void SelinuxRestoreContext() { LOG(INFO) << "Running restorecon..."; - selinux_android_restorecon("/dev", 0); - selinux_android_restorecon("/dev/console", 0); - selinux_android_restorecon("/dev/kmsg", 0); - if constexpr (WORLD_WRITABLE_KMSG) { - selinux_android_restorecon("/dev/kmsg_debug", 0); - } - selinux_android_restorecon("/dev/null", 0); - selinux_android_restorecon("/dev/ptmx", 0); - selinux_android_restorecon("/dev/socket", 0); - selinux_android_restorecon("/dev/random", 0); - selinux_android_restorecon("/dev/urandom", 0); - selinux_android_restorecon("/dev/__properties__", 0); - - selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE); - selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE); - selinux_android_restorecon("/dev/device-mapper", 0); - - selinux_android_restorecon("/apex", 0); - selinux_android_restorecon("/bootstrap-apex", 0); - selinux_android_restorecon("/linkerconfig", 0); - - // adb remount, snapshot-based updates, and DSUs all create files during - // first-stage init. - RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0); - RestoreconIfExists("/metadata/gsi", - SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH); + selinux_android_restorecon("/", SELINUX_ANDROID_RESTORECON_RECURSE); + selinux_android_restorecon("/dev", SELINUX_ANDROID_RESTORECON_RECURSE); } int SelinuxKlogCallback(int type, const char* fmt, ...) { @@ -776,7 +813,10 @@ void LoadSelinuxPolicyAndroid() { int SetupSelinux(char** argv) { SetStdioToDevNull(argv); InitKernelLogging(argv); - + if (is_selinux_enabled()) { + InitSelinuxNamespace(); + ReadSelinuxNamespace(); + } if (REBOOT_BOOTLOADER_ON_PANIC) { InstallRebootSignalHandlers(); } diff --git a/aosp/system/core/init/selinux.h b/aosp/system/core/init/selinux.h new file mode 100644 index 0000000000000000000000000000000000000000..8533788c383f3a57575f8b7a829560c400aa0716 --- /dev/null +++ b/aosp/system/core/init/selinux.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +namespace android { +namespace init { + +// Initialize SELinux, then exec init to run in the init SELinux context. +int SetupSelinux(char** argv); + +void SelinuxInitializeWithoutLoadPolicy(); + +// Restore the proper security context to files and directories on ramdisk, and +// those that were created before initial sepolicy load. +// This must happen before /dev is populated by ueventd. +void SelinuxRestoreContext(); + +// Set up SELinux logging to be written to kmsg, to match init's logging. +void SelinuxSetupKernelLogging(); + +// Return the Android API level with which the vendor SEPolicy was compiled. +// Used for version checks such as whether or not vendor_init should be used. +int SelinuxGetVendorAndroidVersion(); + +static constexpr char kEnvSelinuxStartedAt[] = "SELINUX_STARTED_AT"; + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/service.cpp b/aosp/system/core/init/service.cpp index 001f8aa20fab2c833d11bbf55a95e09b60a1bcbc..54e6f41383a621a845b5ea08cc5c9890bee93f6f 100644 --- a/aosp/system/core/init/service.cpp +++ b/aosp/system/core/init/service.cpp @@ -84,7 +84,6 @@ static std::string monitorSvcProps[MONITOR_SVCS_COUNT] = { "sys.zygote.has_reboot" }; -#if 0 static Result ComputeContextFromExecutable(const std::string& service_path) { std::string computed_context; @@ -122,7 +121,6 @@ static Result ComputeContextFromExecutable(const std::string& servi } return computed_context; } -#endif static bool ExpandArgsAndExecv(const std::vector& args, bool sigstop) { std::vector expanded_args; @@ -250,7 +248,7 @@ void Service::SetProcessAttributesAndCaps(InterprocessFifo setsid_finished) { LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error(); } - if (!seclabel_.empty()) { + if (is_selinux_enabled() && !seclabel_.empty()) { if (setexeccon(seclabel_.c_str()) < 0) { PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_; } @@ -636,17 +634,19 @@ Result Service::Start() { } std::string scon; -#if 0 - if (!seclabel_.empty()) { - scon = seclabel_; - } else { - auto result = ComputeContextFromExecutable(args_[0]); - if (!result.ok()) { - return result.error(); + if (is_selinux_enabled()) { + if (!seclabel_.empty()) { + scon = seclabel_; + } else { + auto result = ComputeContextFromExecutable(args_[0]); + if (!result.ok()) { + LOG(ERROR) << "starting service " << name_ << " failed : " << result.error(); + //return result.error(); + } else { + scon = *result; + } } - scon = *result; } -#endif if (!mount_namespace_.has_value()) { // remember from which mount namespace the service should start @@ -655,7 +655,7 @@ Result Service::Start() { post_data_ = ServiceList::GetInstance().IsPostData(); - LOG(INFO) << "starting service '" << name_ << "'..."; + LOG(INFO) << "starting service '" << name_ << "' with scontext: " << scon; for (int i = 0; i < MONITOR_SVCS_COUNT; i++) { if (name_ == monitorSvcs[i]) { diff --git a/aosp/system/core/init/subcontext.cpp b/aosp/system/core/init/subcontext.cpp index 3ef4eca1f9996c11a224677664a8984ca5041230..2fec001244c91e42fce014d98878b320d26a201f 100644 --- a/aosp/system/core/init/subcontext.cpp +++ b/aosp/system/core/init/subcontext.cpp @@ -180,7 +180,9 @@ int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map auto context = std::string(argv[2]); auto init_fd = std::atoi(argv[3]); - SelabelInitialize(); + if (is_selinux_enabled()) { + SelabelInitialize(); + } trigger_shutdown = [](const std::string& command) { shutdown_command = command; }; @@ -215,7 +217,8 @@ void Subcontext::Fork() { // We don't switch contexts if we're running the unit tests. We don't use std::optional, // since we still need a real context string to pass to the builtin functions. if (context_ != kTestContext) { - if (setexeccon(context_.c_str()) < 0) { + LOG(INFO) << "setexeccon for process " << getpid() << " " << context_ << ""; + if (is_selinux_enabled() && setexeccon(context_.c_str()) < 0) { PLOG(FATAL) << "Could not set execcon for '" << context_ << "'"; } } @@ -346,7 +349,6 @@ Result> Subcontext::ExpandArgs(const std::vector +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "devices.h" +#include "firmware_handler.h" +#include "modalias_handler.h" +#include "selabel.h" +#include "selinux.h" +#include "uevent_handler.h" +#include "uevent_listener.h" +#include "ueventd_parser.h" +#include "util.h" + +// At a high level, ueventd listens for uevent messages generated by the kernel through a netlink +// socket. When ueventd receives such a message it handles it by taking appropriate actions, +// which can typically be creating a device node in /dev, setting file permissions, setting selinux +// labels, etc. +// Ueventd also handles loading of firmware that the kernel requests, and creates symlinks for block +// and character devices. + +// When ueventd starts, it regenerates uevents for all currently registered devices by traversing +// /sys and writing 'add' to each 'uevent' file that it finds. This causes the kernel to generate +// and resend uevent messages for all of the currently registered devices. This is done, because +// ueventd would not have been running when these devices were registered and therefore was unable +// to receive their uevent messages and handle them appropriately. This process is known as +// 'cold boot'. + +// 'init' currently waits synchronously on the cold boot process of ueventd before it continues +// its boot process. For this reason, cold boot should be as quick as possible. One way to achieve +// a speed up here is to parallelize the handling of ueventd messages, which consume the bulk of the +// time during cold boot. + +// Handling of uevent messages has two unique properties: +// 1) It can be done in isolation; it doesn't need to read or write any status once it is started. +// 2) It uses setegid() and setfscreatecon() so either care (aka locking) must be taken to ensure +// that no file system operations are done while the uevent process has an abnormal egid or +// fscreatecon or this handling must happen in a separate process. +// Given the above two properties, it is best to fork() subprocesses to handle the uevents. This +// reduces the overhead and complexity that would be required in a solution with threads and locks. +// In testing, a racy multithreaded solution has the same performance as the fork() solution, so +// there is no reason to deal with the complexity of the former. + +// One other important caveat during the boot process is the handling of SELinux restorecon. +// Since many devices have child devices, calling selinux_android_restorecon() recursively for each +// device when its uevent is handled, results in multiple restorecon operations being done on a +// given file. It is more efficient to simply do restorecon recursively on /sys during cold boot, +// than to do restorecon on each device as its uevent is handled. This only applies to cold boot; +// once that has completed, restorecon is done for each device as its uevent is handled. + +// With all of the above considered, the cold boot process has the below steps: +// 1) ueventd regenerates uevents by doing the /sys traversal and listens to the netlink socket for +// the generated uevents. It writes these uevents into a queue represented by a vector. +// +// 2) ueventd forks 'n' separate uevent handler subprocesses and has each of them to handle the +// uevents in the queue based on a starting offset (their process number) and a stride (the total +// number of processes). Note that no IPC happens at this point and only const functions from +// DeviceHandler should be called from this context. +// +// 3) In parallel to the subprocesses handling the uevents, the main thread of ueventd calls +// selinux_android_restorecon() recursively on /sys/class, /sys/block, and /sys/devices. +// +// 4) Once the restorecon operation finishes, the main thread calls waitpid() to wait for all +// subprocess handlers to complete and exit. Once this happens, it marks coldboot as having +// completed. +// +// At this point, ueventd is single threaded, poll()'s and then handles any future uevents. + +// Lastly, it should be noted that uevents that occur during the coldboot process are handled +// without issue after the coldboot process completes. This is because the uevent listener is +// paused while the uevent handler and restorecon actions take place. Once coldboot completes, +// the uevent listener resumes in polling mode and will handle the uevents that occurred during +// coldboot. + +namespace android { +namespace init { + +class ColdBoot { + public: + ColdBoot(UeventListener& uevent_listener, + std::vector>& uevent_handlers, + bool enable_parallel_restorecon, + std::vector parallel_restorecon_queue) + : uevent_listener_(uevent_listener), + uevent_handlers_(uevent_handlers), + num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4), + enable_parallel_restorecon_(enable_parallel_restorecon), + parallel_restorecon_queue_(parallel_restorecon_queue) {} + + void Run(); + + private: + void UeventHandlerMain(unsigned int process_num, unsigned int total_processes); + void RegenerateUevents(); + void ForkSubProcesses(); + void WaitForSubProcesses(); + void RestoreConHandler(unsigned int process_num, unsigned int total_processes); + void GenerateRestoreCon(const std::string& directory); + + UeventListener& uevent_listener_; + std::vector>& uevent_handlers_; + + unsigned int num_handler_subprocesses_; + bool enable_parallel_restorecon_; + + std::vector uevent_queue_; + + std::set subprocess_pids_; + + std::vector restorecon_queue_; + + std::vector parallel_restorecon_queue_; +}; + +void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) { + for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) { + auto& uevent = uevent_queue_[i]; + + for (auto& uevent_handler : uevent_handlers_) { + uevent_handler->HandleUevent(uevent); + } + } +} + +void ColdBoot::RestoreConHandler(unsigned int process_num, unsigned int total_processes) { + android::base::Timer t_process; + + for (unsigned int i = process_num; i < restorecon_queue_.size(); i += total_processes) { + android::base::Timer t; + auto& dir = restorecon_queue_[i]; + + selinux_android_restorecon(dir.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE); + + //Mark a dir restorecon operation for 50ms, + //Maybe you can add this dir to the ueventd.rc script to parallel processing + if (t.duration() > 50ms) { + LOG(INFO) << "took " << t.duration().count() <<"ms restorecon '" + << dir.c_str() << "' on process '" << process_num <<"'"; + } + } + + //Calculate process restorecon time + LOG(VERBOSE) << "took " << t_process.duration().count() << "ms on process '" + << process_num << "'"; +} + +void ColdBoot::GenerateRestoreCon(const std::string& directory) { + std::unique_ptr dir(opendir(directory.c_str()), &closedir); + + if (!dir) { + PLOG(WARNING) << "opendir " << directory.c_str(); + return; + } + + struct dirent* dent; + while ((dent = readdir(dir.get())) != NULL) { + if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue; + + struct stat st; + if (fstatat(dirfd(dir.get()), dent->d_name, &st, 0) == -1) continue; + + if (S_ISDIR(st.st_mode)) { + std::string fullpath = directory + "/" + dent->d_name; + auto parallel_restorecon = + std::find(parallel_restorecon_queue_.begin(), + parallel_restorecon_queue_.end(), fullpath); + if (parallel_restorecon == parallel_restorecon_queue_.end()) { + restorecon_queue_.emplace_back(fullpath); + } + } + } +} + +void ColdBoot::RegenerateUevents() { + uevent_listener_.RegenerateUevents([this](const Uevent& uevent) { + uevent_queue_.emplace_back(uevent); + return ListenerAction::kContinue; + }); +} + +void ColdBoot::ForkSubProcesses() { + for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) { + auto pid = fork(); + if (pid < 0) { + PLOG(FATAL) << "fork() failed!"; + } + + if (pid == 0) { + UeventHandlerMain(i, num_handler_subprocesses_); + if (enable_parallel_restorecon_) { + RestoreConHandler(i, num_handler_subprocesses_); + } + _exit(EXIT_SUCCESS); + } + + subprocess_pids_.emplace(pid); + } +} + +void ColdBoot::WaitForSubProcesses() { + // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets + // stuck. + // + // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when + // init reaps it, and the cold boot process will start again. If this continues to fail, then + // since ueventd is marked as a critical service, init will reboot to bootloader. + // + // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for + // cold boot and will reboot to the bootloader if ueventd does not complete in time. + while (!subprocess_pids_.empty()) { + int status; + pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0)); + if (pid == -1) { + PLOG(ERROR) << "waitpid() failed"; + continue; + } + + auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid); + if (it == subprocess_pids_.end()) continue; + + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == EXIT_SUCCESS) { + subprocess_pids_.erase(it); + } else { + LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status); + } + } else if (WIFSIGNALED(status)) { + LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status); + } + } +} + +void ColdBoot::Run() { + android::base::Timer cold_boot_timer; + + RegenerateUevents(); + + if (enable_parallel_restorecon_) { + if (parallel_restorecon_queue_.empty()) { + parallel_restorecon_queue_.emplace_back("/sys"); + // takes long time for /sys/devices, parallelize it + parallel_restorecon_queue_.emplace_back("/sys/devices"); + LOG(INFO) << "Parallel processing directory is not set, set the default"; + } + for (const auto& dir : parallel_restorecon_queue_) { + selinux_android_restorecon(dir.c_str(), 0); + GenerateRestoreCon(dir); + } + } + + ForkSubProcesses(); + + if (!enable_parallel_restorecon_) { + selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE); + } + + WaitForSubProcesses(); + + android::base::SetProperty(kColdBootDoneProp, "true"); + LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds"; +} + +static UeventdConfiguration GetConfiguration() { + if (IsMicrodroid()) { + return ParseConfig({"/system/etc/ueventd.rc", "/vendor/etc/ueventd.rc"}); + } + + auto hardware = android::base::GetProperty("ro.hardware", ""); + + struct LegacyPathInfo { + std::string legacy_path; + std::string preferred; + }; + std::vector legacy_paths{ + {"/vendor/ueventd.rc", "/vendor/etc/ueventd.rc"}, + {"/odm/ueventd.rc", "/odm/etc/ueventd.rc"}, + {"/ueventd." + hardware + ".rc", "another ueventd.rc file"}}; + + std::vector canonical{"/system/etc/ueventd.rc"}; + + if (android::base::GetIntProperty("ro.product.first_api_level", 10000) < __ANDROID_API_T__) { + // TODO: Remove these legacy paths once Android S is no longer supported. + for (const auto& info : legacy_paths) { + canonical.push_back(info.legacy_path); + } + } else { + // Warn if newer device is using legacy paths. + for (const auto& info : legacy_paths) { + if (access(info.legacy_path.c_str(), F_OK) == 0) { + LOG(FATAL_WITHOUT_ABORT) + << "Legacy ueventd configuration file detected and will not be parsed: " + << info.legacy_path << ". Please move your configuration to " + << info.preferred << " instead."; + } + } + } + + return ParseConfig(canonical); +} + +int ueventd_main(int argc, char** argv) { + /* + * init sets the umask to 077 for forked processes. We need to + * create files with exact permissions, without modification by + * the umask. + */ + umask(000); + + android::base::InitLogging(argv, &android::base::KernelLogger); + + LOG(INFO) << "ueventd started!"; + + if (is_selinux_enabled()) { + // 设置ueventd进程标签,因为默认是继承init的标签u:r:init:s0,所以需要修改 + if (setcon("u:r:ueventd:s0") < 0) { + LOG(INFO) << "set context for ueventd failed"; + } else { + LOG(INFO) << "set context for ueventd success."; + } + SelinuxSetupKernelLogging(); + SelabelInitialize(); + } + + std::vector> uevent_handlers; + + auto ueventd_configuration = GetConfiguration(); + + uevent_handlers.emplace_back(std::make_unique( + std::move(ueventd_configuration.dev_permissions), + std::move(ueventd_configuration.sysfs_permissions), + std::move(ueventd_configuration.subsystems), android::fs_mgr::GetBootDevices(), true)); + uevent_handlers.emplace_back(std::make_unique( + std::move(ueventd_configuration.firmware_directories), + std::move(ueventd_configuration.external_firmware_handlers))); + + if (ueventd_configuration.enable_modalias_handling) { + std::vector base_paths = {"/odm/lib/modules", "/vendor/lib/modules"}; + uevent_handlers.emplace_back(std::make_unique(base_paths)); + } + UeventListener uevent_listener(ueventd_configuration.uevent_socket_rcvbuf_size); + + if (!android::base::GetBoolProperty(kColdBootDoneProp, false)) { + ColdBoot cold_boot(uevent_listener, uevent_handlers, + ueventd_configuration.enable_parallel_restorecon, + ueventd_configuration.parallel_restorecon_dirs); + cold_boot.Run(); + } + + for (auto& uevent_handler : uevent_handlers) { + uevent_handler->ColdbootDone(); + } + + // We use waitpid() in ColdBoot, so we can't ignore SIGCHLD until now. + signal(SIGCHLD, SIG_IGN); + // Reap and pending children that exited between the last call to waitpid() and setting SIG_IGN + // for SIGCHLD above. + while (waitpid(-1, nullptr, WNOHANG) > 0) { + } + + // Restore prio before main loop + setpriority(PRIO_PROCESS, 0, 0); + uevent_listener.Poll([&uevent_handlers](const Uevent& uevent) { + for (auto& uevent_handler : uevent_handlers) { + uevent_handler->HandleUevent(uevent); + } + return ListenerAction::kContinue; + }); + + return 0; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/util.cpp b/aosp/system/core/init/util.cpp index 58d45fe84a674c7242185d7cacddb8cd199f3fcf..ef7a6c05e3fddc6d8606f9caf949b83fe349c271 100644 --- a/aosp/system/core/init/util.cpp +++ b/aosp/system/core/init/util.cpp @@ -93,13 +93,12 @@ Result DecodeUid(const std::string& name) { */ Result CreateSocket(const std::string& name, int type, bool passcred, bool should_listen, mode_t perm, uid_t uid, gid_t gid, const std::string& socketcon) { -#if 0 - if (!socketcon.empty()) { + if (is_selinux_enabled() && !socketcon.empty()) { if (setsockcreatecon(socketcon.c_str()) == -1) { return ErrnoError() << "setsockcreatecon(\"" << socketcon << "\") failed"; } } -#endif + android::base::unique_fd fd(socket(PF_UNIX, type, 0)); if (fd < 0) { return ErrnoError() << "Failed to open socket '" << name << "'"; @@ -189,8 +188,10 @@ Result ReadFile(const std::string& path) { } static int OpenFile(const std::string& path, int flags, mode_t mode) { - return open(path.c_str(), flags, mode); -#if 0 + if (!is_selinux_enabled()) { + return open(path.c_str(), flags, mode); + } + std::string secontext; if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) { setfscreatecon(secontext.c_str()); @@ -205,7 +206,6 @@ static int OpenFile(const std::string& path, int flags, mode_t mode) { } return rc; -#endif } Result WriteFile(const std::string& path, const std::string& content) { @@ -250,9 +250,10 @@ int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) { } bool make_dir(const std::string& path, mode_t mode) { - int rc = mkdir(path.c_str(), mode); - return rc == 0; -#if 0 + if (!is_selinux_enabled()) { + return (mkdir(path.c_str(), mode) == 0); + } + std::string secontext; if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) { setfscreatecon(secontext.c_str()); @@ -267,7 +268,6 @@ bool make_dir(const std::string& path, mode_t mode) { } return rc == 0; -#endif } /* @@ -657,18 +657,20 @@ static void InitAborter(const char* abort_message) { // access any fds that it opens, including the one opened below for /dev/null. Therefore, // SetStdioToDevNull() must be called again in second stage init. void SetStdioToDevNull(char** argv) { - // Make stdin/stdout/stderr all point to /dev/null. - int fd = open("/dev/null", O_RDWR); // NOLINT(android-cloexec-open) - if (fd == -1) { - int saved_errno = errno; - android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter); - errno = saved_errno; - PLOG(FATAL) << "Couldn't open /dev/null"; - } - dup2(fd, STDIN_FILENO); - dup2(fd, STDOUT_FILENO); - dup2(fd, STDERR_FILENO); - if (fd > STDERR_FILENO) close(fd); + if (is_selinux_enabled()) { + // Make stdin/stdout/stderr all point to /dev/null. + int fd = open("/dev/null", O_RDWR); // NOLINT(android-cloexec-open) + if (fd == -1) { + int saved_errno = errno; + android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter); + errno = saved_errno; + PLOG(FATAL) << "Couldn't open /dev/null"; + } + dup2(fd, STDIN_FILENO); + dup2(fd, STDOUT_FILENO); + dup2(fd, STDERR_FILENO); + if (fd > STDERR_FILENO) close(fd); + } } void InitKernelLogging(char** argv) { diff --git a/aosp/system/core/rootdir/init.rc b/aosp/system/core/rootdir/init.rc index 39078aa8c068d3d7aafeb0f8fb920ddfcb21ba31..c2ab4417089415663e8ca9caa311a59c463d9bbb 100644 --- a/aosp/system/core/rootdir/init.rc +++ b/aosp/system/core/rootdir/init.rc @@ -475,6 +475,8 @@ on init # This allows the ledtrig-transient properties to be created here so # that they can be chown'd to system:system later on boot write /sys/class/leds/vibrator/trigger "transient" + restorecon /sys/class/power_supply/battery/voltage_now + restorecon /proc/version # This is used by Bionic to select optimized routines. write /dev/cpu_variant:${ro.bionic.arch} ${ro.bionic.cpu_variant} @@ -507,37 +509,6 @@ on init start hwservicemanager start vndservicemanager -# Run boringssl self test for each ABI. Any failures trigger reboot to firmware. -import /system/etc/init/hw/init.boringssl.${ro.zygote}.rc - -service boringssl_self_test32 /system/bin/boringssl_self_test32 - reboot_on_failure reboot,boringssl-self-check-failed - stdio_to_kmsg - # Explicitly specify that boringssl_self_test32 doesn't require any capabilities - capabilities - user nobody - -service boringssl_self_test64 /system/bin/boringssl_self_test64 - reboot_on_failure reboot,boringssl-self-check-failed - stdio_to_kmsg - # Explicitly specify that boringssl_self_test64 doesn't require any capabilities - capabilities - user nobody - -service boringssl_self_test_apex32 /apex/com.android.conscrypt/bin/boringssl_self_test32 - reboot_on_failure reboot,boringssl-self-check-failed - stdio_to_kmsg - # Explicitly specify that boringssl_self_test_apex32 doesn't require any capabilities - capabilities - user nobody - -service boringssl_self_test_apex64 /apex/com.android.conscrypt/bin/boringssl_self_test64 - reboot_on_failure reboot,boringssl-self-check-failed - stdio_to_kmsg - # Explicitly specify that boringssl_self_test_apex64 doesn't require any capabilities - capabilities - user nobody - # Healthd can trigger a full boot from charger mode by signaling this # property when the power button is held. on property:sys.boot_from_charger_mode=1 @@ -585,6 +556,7 @@ on late-init on early-fs # Once metadata has been mounted, we'll need vold to deal with userdata checkpointing + mkdir /metadata/ start vold on post-fs diff --git a/aosp/system/hwservicemanager/AccessControl.cpp b/aosp/system/hwservicemanager/AccessControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cbcfff9d6f97fcee6134e65904e91c170406cc4 --- /dev/null +++ b/aosp/system/hwservicemanager/AccessControl.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwservicemanager" + +#include +#include +#include + +#include "AccessControl.h" + +namespace android { + +static const char *kPermissionAdd = "add"; +static const char *kPermissionGet = "find"; +static const char *kPermissionList = "list"; + +struct audit_data { + const char* interfaceName; + const char* sid; + pid_t pid; +}; + +using android::FQName; + +AccessControl::AccessControl() { + if (!is_selinux_enabled()) { + mSeHandle = nullptr; + mSeContext = nullptr; + mSeCallbacks.func_audit = nullptr; + mSeCallbacks.func_log = nullptr; + return; + } + mSeHandle = selinux_android_hw_service_context_handle(); + LOG_ALWAYS_FATAL_IF(mSeHandle == nullptr, "Failed to acquire SELinux handle."); + + if (getcon(&mSeContext) != 0) { + LOG_ALWAYS_FATAL("Failed to acquire hwservicemanager context."); + } + + selinux_status_open(true); + + mSeCallbacks.func_audit = AccessControl::auditCallback; + selinux_set_callback(SELINUX_CB_AUDIT, mSeCallbacks); + + mSeCallbacks.func_log = selinux_log_callback; /* defined in libselinux */ + selinux_set_callback(SELINUX_CB_LOG, mSeCallbacks); +} + +bool AccessControl::canAdd(const std::string& fqName, const CallingContext& callingContext) { + FQName fqIface; + + if (!FQName::parse(fqName, &fqIface)) { + return false; + } + const std::string checkName = fqIface.package() + "::" + fqIface.name(); + + return checkPermission(callingContext, kPermissionAdd, checkName.c_str()); +} + +bool AccessControl::canGet(const std::string& fqName, const CallingContext& callingContext) { + FQName fqIface; + + if (!FQName::parse(fqName, &fqIface)) { + return false; + } + const std::string checkName = fqIface.package() + "::" + fqIface.name(); + + return checkPermission(callingContext, kPermissionGet, checkName.c_str()); +} + +bool AccessControl::canList(const CallingContext& callingContext) { + return checkPermission(callingContext, mSeContext, kPermissionList, nullptr); +} + +AccessControl::CallingContext AccessControl::getCallingContext(pid_t sourcePid) { + if (!is_selinux_enabled()) { + return { true, "", sourcePid }; + } + + char *sourceContext = nullptr; + + if (getpidcon(sourcePid, &sourceContext) < 0) { + ALOGE("SELinux: failed to retrieve process context for pid %d", sourcePid); + return { false, "", sourcePid }; + } + + std::string context = sourceContext; + freecon(sourceContext); + return { true, context, sourcePid }; +} + +bool AccessControl::checkPermission(const CallingContext& source, const char *targetContext, const char *perm, const char *interface) { + if (!is_selinux_enabled()) { + return true; + } + + if (!source.sidPresent) { + return false; + } + + bool allowed = false; + + struct audit_data ad; + ad.pid = source.pid; + ad.sid = source.sid.c_str(); + ad.interfaceName = interface; + + allowed = (selinux_check_access(source.sid.c_str(), targetContext, "hwservice_manager", + perm, (void *) &ad) == 0); + + return allowed; +} + +bool AccessControl::checkPermission(const CallingContext& source, const char *perm, const char *interface) { + if (!is_selinux_enabled()) { + return true; + } + + char *targetContext = nullptr; + bool allowed = false; + + // Lookup service in hwservice_contexts + if (selabel_lookup(mSeHandle, &targetContext, interface, 0) != 0) { + ALOGE("No match for interface %s in hwservice_contexts", interface); + return false; + } + + allowed = checkPermission(source, targetContext, perm, interface); + + freecon(targetContext); + + return allowed; +} + +int AccessControl::auditCallback(void *data, security_class_t /*cls*/, char *buf, size_t len) { + struct audit_data *ad = (struct audit_data *)data; + + if (!ad || !ad->interfaceName) { + ALOGE("No valid hwservicemanager audit data"); + return 0; + } + + const char* sid = ad->sid ? ad->sid : "N/A"; + + snprintf(buf, len, "interface=%s sid=%s pid=%d", ad->interfaceName, sid, ad->pid); + return 0; +} + +} // namespace android diff --git a/aosp/system/libhwbinder/Android.bp b/aosp/system/libhwbinder/Android.bp new file mode 100644 index 0000000000000000000000000000000000000000..915b35d2b164755d7febb48c6d713df0f6d678ef --- /dev/null +++ b/aosp/system/libhwbinder/Android.bp @@ -0,0 +1,163 @@ +// Copyright (C) 2009 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package { + default_applicable_licenses: ["system_libhwbinder_license"], +} + +// Added automatically by a large-scale-change +// http://go/android-license-faq +license { + name: "system_libhwbinder_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + +cc_library_headers { + name: "libhwbinder_headers", + export_include_dirs: ["include"], + host_supported: true, + recovery_available: true, + vendor_available: true, + product_available: true, + // TODO(b/153609531): remove when no longer needed. + native_bridge_supported: true, + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], + min_sdk_version: "29", +} + +cc_defaults { + name: "libhwbinder_defaults", + + header_libs: ["libhwbinder_headers"], + export_header_lib_headers: ["libhwbinder_headers"], + + sanitize: { + misc_undefined: ["integer"], + }, + srcs: [ + "Binder.cpp", + "BpHwBinder.cpp", + "BufferedTextOutput.cpp", + "Debug.cpp", + "IInterface.cpp", + "IPCThreadState.cpp", + "Parcel.cpp", + "ProcessState.cpp", + "Static.cpp", + "TextOutput.cpp", + "Utils.cpp", + ], + + product_variables: { + binder32bit: { + cflags: ["-DBINDER_IPC_32BIT=1"], + }, + }, + + cflags: [ + "-Wall", + "-Werror", + ], +} + +cc_defaults { + name: "libhwbinder-impl-shared-libs", + shared_libs: [ + "libbase", + "liblog", + "libcutils", + "libutils", + "libselinux", + ], + export_shared_lib_headers: [ + "libbase", + "libutils", + ], +} + +// WARNING: this should no longer be used +// This is automatically removed by bpfix. Once there are no makefiles, fixes can be automatically applied, and this can be removed. +cc_library { + name: "libhwbinder", + vendor_available: true, + + export_include_dirs: ["include"], + + visibility: [ + ":__subpackages__", + "//vendor:__subpackages__", + ], +} + +// Combined into libhidlbase for efficiency. +// Used as shared library to provide headers for libhidltransport-impl-internal. +cc_library_static { + name: "libhwbinder-impl-internal", + include_dirs: [ + // TODO(b/31559095): get headers from bionic on host + "bionic/libc/kernel/android/uapi/", + "bionic/libc/kernel/uapi/", + ], + + defaults: [ + "libhwbinder_defaults", + "libhwbinder-impl-shared-libs", + "hwbinder_lto", + ], + host_supported: true, + recovery_available: true, + vendor_available: true, + product_available: true, + // TODO(b/153609531): remove when no longer needed. + native_bridge_supported: true, + apex_available: [ + "//apex_available:platform", + "com.android.neuralnetworks", + "com.android.btservices", + "com.android.media", + "com.android.media.swcodec", + "com.android.nfcservices", + "com.android.tethering", + ], + min_sdk_version: "29", +} + +// Provide lto property to build hwbinder with LTO +cc_defaults { + name: "hwbinder_lto", + target: { + android: { + lto: { + thin: true, + }, + }, + }, + arch: { + // TODO(b/254713216): undefined symbol in BufferedTextOutput::getBuffer + riscv64: { + lto: { + thin: false, + }, + }, + }, +} diff --git a/aosp/system/libhwbinder/Binder.cpp b/aosp/system/libhwbinder/Binder.cpp index 1a433acd6827573040fdeae99f1584ff56f402ac..0e8f50260895935df3d38bf7e7afe11939d93a20 100644 --- a/aosp/system/libhwbinder/Binder.cpp +++ b/aosp/system/libhwbinder/Binder.cpp @@ -30,6 +30,7 @@ #include #include +#include namespace android { namespace hardware { @@ -96,9 +97,12 @@ bool BHwBinder::isRequestingSid() { } void BHwBinder::setRequestingSid(bool requestingSid) { - requestingSid = false; Extras* e = mExtras.load(std::memory_order_acquire); + if (!is_selinux_enabled()) { + requestingSid = false; + } + if (!e) { // default is false. Most things don't need sids, so avoiding allocations when possible. if (!requestingSid) { diff --git a/aosp/system/libhwbinder/ProcessState.cpp b/aosp/system/libhwbinder/ProcessState.cpp index a26d09c98fad0e25453ecf24a6462b3a98fa429f..d235cdaee522efef1c93ac11d63ee52a238c8280 100644 --- a/aosp/system/libhwbinder/ProcessState.cpp +++ b/aosp/system/libhwbinder/ProcessState.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include @@ -123,15 +124,13 @@ void ProcessState::becomeContextManager() { AutoMutex _l(mLock); -#if 0 - flat_binder_object obj { - .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX, - }; - + flat_binder_object obj; + if (is_selinux_enabled()) { + obj.flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX; + } else { + memset(&obj, 0, sizeof(obj)); + } status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj); -#endif - status_t result = 1; - // fallback to original method if (result != 0) { android_errorWriteLog(0x534e4554, "121035042"); diff --git a/aosp/system/memory/lmkd/lmkd.cpp b/aosp/system/memory/lmkd/lmkd.cpp index 63f42469932fa3fd963360b2a8e64154a792763d..8adeba3929c876aa084646a7b89b14ede9393fe9 100644 --- a/aosp/system/memory/lmkd/lmkd.cpp +++ b/aosp/system/memory/lmkd/lmkd.cpp @@ -3483,7 +3483,7 @@ static int init(void) { ctrl_sock.sock = android_get_control_socket("lmkd"); if (ctrl_sock.sock < 0) { - ALOGE("get lmkd control socket failed"); + ALOGE("get lmkd control socket failed (fd=%d)", ctrl_sock.sock); return -1; } diff --git a/aosp/system/sepolicy/prebuilts/api/34.0/private/file_contexts b/aosp/system/sepolicy/prebuilts/api/34.0/private/file_contexts new file mode 100644 index 0000000000000000000000000000000000000000..5857b46b0719f74d5398b8bd6c3f46cb8d27e1ce --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/34.0/private/file_contexts @@ -0,0 +1,891 @@ +########################################### +# Root +/ u:object_r:rootfs:s0 + +# Data files +/adb_keys u:object_r:adb_keys_file:s0 +/build\.prop u:object_r:rootfs:s0 +/default\.prop u:object_r:rootfs:s0 +/fstab\..* u:object_r:rootfs:s0 +/init\..* u:object_r:rootfs:s0 +/res(/.*)? u:object_r:rootfs:s0 +/selinux_version u:object_r:rootfs:s0 +/ueventd\..* u:object_r:rootfs:s0 +/verity_key u:object_r:rootfs:s0 + +# Executables +/init u:object_r:init_exec:s0 +/sbin(/.*)? u:object_r:rootfs:s0 + +# For kernel modules +/lib(/.*)? u:object_r:rootfs:s0 +/system_dlkm(/.*)? u:object_r:system_dlkm_file:s0 + +# Empty directories +/lost\+found u:object_r:rootfs:s0 +/acct u:object_r:cgroup:s0 +/config u:object_r:rootfs:s0 +/data_mirror u:object_r:mirror_data_file:s0 +/debug_ramdisk u:object_r:tmpfs:s0 +/mnt u:object_r:tmpfs:s0 +/proc u:object_r:rootfs:s0 +/second_stage_resources u:object_r:tmpfs:s0 +/sys u:object_r:sysfs:s0 +# proc fs & sys fs +/proc/net/route u:object_r:proc_net_route:s0 +/proc/version u:object_r:proc_version:s0 +/sys/block u:object_r:sysfs_block:s0 +/sys/bus/pci/drivers/virtio-pci u:object_r:sysfs_bpd_virtio_pci:s0 +/sys/bus/virtio u:object_r:sysfs_b_virtio:s0 +/sys/class/net/wlan0 u:object_r:sysfs_cn_wlan0:s0 +/sys/class/power_supply/battery/voltage_now u:object_r:sysfs_power:s0 +/sys/module/virtio_pci u:object_r:sysfs_m_virtio_pci:s0 +/apex u:object_r:apex_mnt_dir:s0 + +# Postinstall directories +/postinstall u:object_r:postinstall_mnt_dir:s0 +/postinstall/apex u:object_r:postinstall_apex_mnt_dir:s0 + +/apex/(\.(bootstrap|default)-)?apex-info-list.xml u:object_r:apex_info_file:s0 + +# Symlinks +/bin u:object_r:rootfs:s0 +/bugreports u:object_r:rootfs:s0 +/charger u:object_r:rootfs:s0 +/d u:object_r:rootfs:s0 +/etc u:object_r:rootfs:s0 +/sdcard u:object_r:rootfs:s0 + +# SELinux policy files +/vendor_file_contexts u:object_r:file_contexts_file:s0 +/plat_file_contexts u:object_r:file_contexts_file:s0 +/product_file_contexts u:object_r:file_contexts_file:s0 +/mapping_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_property_contexts u:object_r:property_contexts_file:s0 +/product_property_contexts u:object_r:property_contexts_file:s0 +/vendor_property_contexts u:object_r:property_contexts_file:s0 +/seapp_contexts u:object_r:seapp_contexts_file:s0 +/vendor_seapp_contexts u:object_r:seapp_contexts_file:s0 +/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/sepolicy u:object_r:sepolicy_file:s0 +/plat_service_contexts u:object_r:service_contexts_file:s0 +/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/plat_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/vendor_service_contexts u:object_r:vendor_service_contexts_file:s0 +/vendor_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vndservice_contexts u:object_r:vndservice_contexts_file:s0 + +########################## +# Devices +# +/dev(/.*)? u:object_r:device:s0 +/dev/adf[0-9]* u:object_r:graphics_device:s0 +/dev/adf-interface[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/adf-overlay-engine[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/ashmem u:object_r:ashmem_device:s0 +/dev/ashmem(.*)? u:object_r:ashmem_libcutils_device:s0 +/dev/audio.* u:object_r:audio_device:s0 +/dev/binder u:object_r:binder_device:s0 +/dev/block(/.*)? u:object_r:block_device:s0 +/dev/block/by-name/zoned_device u:object_r:zoned_block_device:s0 +/dev/block/dm-[0-9]+ u:object_r:dm_device:s0 +/dev/block/ublkb[0-9]+ u:object_r:ublk_block_device:s0 +/dev/block/loop[0-9]* u:object_r:loop_device:s0 +/dev/block/vd[a-z][0-9]* u:object_r:vd_device:s0 +/dev/block/vold/.+ u:object_r:vold_device:s0 +/dev/block/ram[0-9]* u:object_r:ram_device:s0 +/dev/block/zram[0-9]* u:object_r:ram_device:s0 +/dev/boringssl/selftest(/.*)? u:object_r:boringssl_self_test_marker:s0 +/dev/bus/usb(.*)? u:object_r:usb_device:s0 +/dev/console u:object_r:console_device:s0 +/dev/cpu_variant:.* u:object_r:dev_cpu_variant:s0 +/dev/dma_heap(/.*)? u:object_r:dmabuf_heap_device:s0 +/dev/dma_heap/system u:object_r:dmabuf_system_heap_device:s0 +/dev/dma_heap/system-uncached u:object_r:dmabuf_system_heap_device:s0 +/dev/dma_heap/system-secure(.*) u:object_r:dmabuf_system_secure_heap_device:s0 +/dev/dm-user(/.*)? u:object_r:dm_user_device:s0 +/dev/ublk-control u:object_r:ublk_control_device:s0 +/dev/device-mapper u:object_r:dm_device:s0 +/dev/eac u:object_r:audio_device:s0 +/dev/event-log-tags u:object_r:runtime_event_log_tags_file:s0 +/dev/cgroup_info(/.*)? u:object_r:cgroup_rc_file:s0 +/dev/fscklogs(/.*)? u:object_r:fscklogs:s0 +/dev/fuse u:object_r:fuse_device:s0 +/dev/gnss[0-9]+ u:object_r:gnss_device:s0 +/dev/graphics(/.*)? u:object_r:graphics_device:s0 +/dev/hw_random u:object_r:hw_random_device:s0 +/dev/hwbinder u:object_r:hwbinder_device:s0 +/dev/input(/.*)? u:object_r:input_device:s0 +/dev/iio:device[0-9]+ u:object_r:iio_device:s0 +/dev/ion u:object_r:ion_device:s0 +/dev/keychord u:object_r:keychord_device:s0 +/dev/loop-control u:object_r:loop_control_device:s0 +/dev/modem.* u:object_r:radio_device:s0 +/dev/mtp_usb u:object_r:mtp_device:s0 +/dev/pmsg0 u:object_r:pmsg_device:s0 +/dev/pn544 u:object_r:nfc_device:s0 +/dev/port u:object_r:port_device:s0 +/dev/ppp u:object_r:ppp_device:s0 +/dev/ptmx u:object_r:ptmx_device:s0 +/dev/pvrsrvkm u:object_r:gpu_device:s0 +/dev/kmsg u:object_r:kmsg_device:s0 +/dev/kmsg_debug u:object_r:kmsg_debug_device:s0 +/dev/kvm u:object_r:kvm_device:s0 +/dev/null u:object_r:null_device:s0 +/dev/nvhdcp1 u:object_r:video_device:s0 +/dev/random u:object_r:random_device:s0 +/dev/rpmsg-omx[0-9] u:object_r:rpmsg_device:s0 +/dev/rproc_user u:object_r:rpmsg_device:s0 +/dev/rtc[0-9] u:object_r:rtc_device:s0 +/dev/snd(/.*)? u:object_r:audio_device:s0 +/dev/socket(/.*)? u:object_r:socket_device:s0 +/dev/socket/adbd u:object_r:adbd_socket:s0 +/dev/socket/dnsproxyd u:object_r:dnsproxyd_socket:s0 +/dev/socket/dumpstate u:object_r:dumpstate_socket:s0 +/dev/socket/fwmarkd u:object_r:fwmarkd_socket:s0 +/dev/socket/lmkd u:object_r:lmkd_socket:s0 +/dev/socket/logd u:object_r:logd_socket:s0 +/dev/socket/logdr u:object_r:logdr_socket:s0 +/dev/socket/logdw u:object_r:logdw_socket:s0 +/dev/socket/statsdw u:object_r:statsdw_socket:s0 +/dev/socket/mdns u:object_r:mdns_socket:s0 +/dev/socket/mdnsd u:object_r:mdnsd_socket:s0 +/dev/socket/mtpd u:object_r:mtpd_socket:s0 +/dev/socket/pdx/system/buffer_hub u:object_r:pdx_bufferhub_dir:s0 +/dev/socket/pdx/system/buffer_hub/client u:object_r:pdx_bufferhub_client_endpoint_socket:s0 +/dev/socket/pdx/system/performance u:object_r:pdx_performance_dir:s0 +/dev/socket/pdx/system/performance/client u:object_r:pdx_performance_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display u:object_r:pdx_display_dir:s0 +/dev/socket/pdx/system/vr/display/client u:object_r:pdx_display_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/manager u:object_r:pdx_display_manager_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/screenshot u:object_r:pdx_display_screenshot_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/vsync u:object_r:pdx_display_vsync_endpoint_socket:s0 +/dev/socket/prng_seeder u:object_r:prng_seeder_socket:s0 +/dev/socket/property_service u:object_r:property_socket:s0 +/dev/socket/property_service_for_system u:object_r:property_socket:s0 +/dev/socket/racoon u:object_r:racoon_socket:s0 +/dev/socket/recovery u:object_r:recovery_socket:s0 +/dev/socket/rild u:object_r:rild_socket:s0 +/dev/socket/rild-debug u:object_r:rild_debug_socket:s0 +/dev/socket/snapuserd u:object_r:snapuserd_socket:s0 +/dev/socket/snapuserd_proxy u:object_r:snapuserd_proxy_socket:s0 +/dev/socket/tombstoned_crash u:object_r:tombstoned_crash_socket:s0 +/dev/socket/tombstoned_java_trace u:object_r:tombstoned_java_trace_socket:s0 +/dev/socket/tombstoned_intercept u:object_r:tombstoned_intercept_socket:s0 +/dev/socket/traced_consumer u:object_r:traced_consumer_socket:s0 +/dev/socket/traced_perf u:object_r:traced_perf_socket:s0 +/dev/socket/traced_producer u:object_r:traced_producer_socket:s0 +/dev/socket/heapprofd u:object_r:heapprofd_socket:s0 +/dev/socket/uncrypt u:object_r:uncrypt_socket:s0 +/dev/socket/wpa_eth[0-9] u:object_r:wpa_socket:s0 +/dev/socket/wpa_wlan[0-9] u:object_r:wpa_socket:s0 +/dev/socket/zygote u:object_r:zygote_socket:s0 +/dev/socket/zygote_secondary u:object_r:zygote_socket:s0 +/dev/socket/usap_pool_primary u:object_r:zygote_socket:s0 +/dev/socket/usap_pool_secondary u:object_r:zygote_socket:s0 +/dev/spdif_out.* u:object_r:audio_device:s0 +/dev/sys/block/by-name/rootdisk(/.*)? u:object_r:rootdisk_sysdev:s0 +/dev/sys/block/by-name/userdata(/.*)? u:object_r:userdata_sysdev:s0 +/dev/sys/fs/by-name/userdata(/.*)? u:object_r:userdata_sysdev:s0 +/dev/tty u:object_r:owntty_device:s0 +/dev/tty[0-9]* u:object_r:tty_device:s0 +/dev/ttyS[0-9]* u:object_r:serial_device:s0 +/dev/ttyUSB[0-9]* u:object_r:usb_serial_device:s0 +/dev/ttyACM[0-9]* u:object_r:usb_serial_device:s0 +/dev/tun u:object_r:tun_device:s0 +/dev/uhid u:object_r:uhid_device:s0 +/dev/uinput u:object_r:uhid_device:s0 +/dev/uio[0-9]* u:object_r:uio_device:s0 +/dev/urandom u:object_r:random_device:s0 +/dev/usb_accessory u:object_r:usbaccessory_device:s0 +/dev/v4l-touch[0-9]* u:object_r:input_device:s0 +/dev/vhost-vsock u:object_r:kvm_device:s0 +/dev/video[0-9]* u:object_r:video_device:s0 +/dev/vndbinder u:object_r:vndbinder_device:s0 +/dev/watchdog u:object_r:watchdog_device:s0 +/dev/xt_qtaguid u:object_r:qtaguid_device:s0 +/dev/zero u:object_r:zero_device:s0 +/dev/__properties__ u:object_r:properties_device:s0 +/dev/__properties__/property_info u:object_r:property_info:s0 +############################# +# Linker configuration +# +/linkerconfig(/.*)? u:object_r:linkerconfig_file:s0 + +# Apex sepoolicy files. +/dev/selinux/apex_file_contexts u:object_r:file_contexts_file:s0 +/dev/selinux/apex_seapp_contexts u:object_r:seapp_contexts_file:s0 +/dev/selinux/apex_service_contexts u:object_r:service_contexts_file:s0 +/dev/selinux/apex_property_contexts u:object_r:property_contexts_file:s0 +/dev/selinux/apex_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/dev/selinux/apex_mac_permissions\.xml u:object_r:mac_perms_file:s0 + +############################# +# System files +# +/system(/.*)? u:object_r:system_file:s0 +/system/apex/com.android.art u:object_r:art_apex_dir:s0 +/system/lib(64)?(/.*)? u:object_r:system_lib_file:s0 +/system/lib(64)?/bootstrap(/.*)? u:object_r:system_bootstrap_lib_file:s0 +/system/bin/mm_events u:object_r:mm_events_exec:s0 +/system/bin/atrace u:object_r:atrace_exec:s0 +/system/bin/auditctl u:object_r:auditctl_exec:s0 +/system/bin/bcc u:object_r:rs_exec:s0 +/system/bin/blank_screen u:object_r:blank_screen_exec:s0 +/system/bin/boringssl_self_test(32|64) u:object_r:boringssl_self_test_exec:s0 +/system/bin/prng_seeder u:object_r:prng_seeder_exec:s0 +/system/bin/charger u:object_r:charger_exec:s0 +/system/bin/e2fsdroid u:object_r:e2fs_exec:s0 +/system/bin/mke2fs u:object_r:e2fs_exec:s0 +/system/bin/e2fsck -- u:object_r:fsck_exec:s0 +/system/bin/extra_free_kbytes\.sh u:object_r:extra_free_kbytes_exec:s0 +/system/bin/fsck\.exfat -- u:object_r:fsck_exec:s0 +/system/bin/fsck\.f2fs -- u:object_r:fsck_exec:s0 +/system/bin/init u:object_r:init_exec:s0 +# TODO(/123600489): merge mini-keyctl into toybox +/system/bin/mini-keyctl -- u:object_r:toolbox_exec:s0 +/system/bin/fsverity_init u:object_r:fsverity_init_exec:s0 +/system/bin/sload_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/make_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/fsck_msdos -- u:object_r:fsck_exec:s0 +/system/bin/tcpdump -- u:object_r:tcpdump_exec:s0 +/system/bin/tune2fs -- u:object_r:fsck_exec:s0 +/system/bin/resize2fs -- u:object_r:fsck_exec:s0 +/system/bin/toolbox -- u:object_r:toolbox_exec:s0 +/system/bin/toybox -- u:object_r:toolbox_exec:s0 +/system/bin/ld\.mc u:object_r:rs_exec:s0 +/system/bin/logcat -- u:object_r:logcat_exec:s0 +/system/bin/logcatd -- u:object_r:logcat_exec:s0 +/system/bin/sh -- u:object_r:shell_exec:s0 +/system/bin/run-as -- u:object_r:runas_exec:s0 +/system/bin/bootanimation u:object_r:bootanim_exec:s0 +/system/bin/bootstat u:object_r:bootstat_exec:s0 +/system/bin/app_process32 u:object_r:zygote_exec:s0 +/system/bin/app_process64 u:object_r:zygote_exec:s0 +/system/bin/servicemanager u:object_r:servicemanager_exec:s0 +/system/bin/hwservicemanager u:object_r:hwservicemanager_exec:s0 +/system/bin/surfaceflinger u:object_r:surfaceflinger_exec:s0 +/system/bin/gpuservice u:object_r:gpuservice_exec:s0 +/system/bin/bufferhubd u:object_r:bufferhubd_exec:s0 +/system/bin/performanced u:object_r:performanced_exec:s0 +/system/bin/drmserver u:object_r:drmserver_exec:s0 +/system/bin/drmserver32 u:object_r:drmserver_exec:s0 +/system/bin/drmserver64 u:object_r:drmserver_exec:s0 +/system/bin/dumpstate u:object_r:dumpstate_exec:s0 +/system/bin/incident u:object_r:incident_exec:s0 +/system/bin/incidentd u:object_r:incidentd_exec:s0 +/system/bin/incident_helper u:object_r:incident_helper_exec:s0 +/system/bin/iw u:object_r:iw_exec:s0 +/system/bin/netutils-wrapper-1\.0 u:object_r:netutils_wrapper_exec:s0 +/system/bin/vold u:object_r:vold_exec:s0 +/system/bin/netd u:object_r:netd_exec:s0 +/system/bin/wificond u:object_r:wificond_exec:s0 +/system/bin/audioserver u:object_r:audioserver_exec:s0 +/system/bin/mediadrmserver u:object_r:mediadrmserver_exec:s0 +/system/bin/mediaserver u:object_r:mediaserver_exec:s0 +/system/bin/mediaserver32 u:object_r:mediaserver_exec:s0 +/system/bin/mediaserver64 u:object_r:mediaserver_exec:s0 +/system/bin/mediametrics u:object_r:mediametrics_exec:s0 +/system/bin/cameraserver u:object_r:cameraserver_exec:s0 +/system/bin/mediaextractor u:object_r:mediaextractor_exec:s0 +/system/bin/mediaswcodec u:object_r:mediaswcodec_exec:s0 +/system/bin/mediatranscoding u:object_r:mediatranscoding_exec:s0 +/system/bin/mediatuner u:object_r:mediatuner_exec:s0 +/system/bin/mdnsd u:object_r:mdnsd_exec:s0 +/system/bin/installd u:object_r:installd_exec:s0 +/system/bin/otapreopt_chroot u:object_r:otapreopt_chroot_exec:s0 +/system/bin/otapreopt_slot u:object_r:otapreopt_slot_exec:s0 +/system/bin/credstore u:object_r:credstore_exec:s0 +/system/bin/keystore u:object_r:keystore_exec:s0 +/system/bin/keystore2 u:object_r:keystore_exec:s0 +/system/bin/fingerprintd u:object_r:fingerprintd_exec:s0 +/system/bin/gatekeeperd u:object_r:gatekeeperd_exec:s0 +/system/bin/tombstoned u:object_r:tombstoned_exec:s0 +/system/bin/recovery-persist u:object_r:recovery_persist_exec:s0 +/system/bin/recovery-refresh u:object_r:recovery_refresh_exec:s0 +/system/bin/sdcard u:object_r:sdcardd_exec:s0 +/system/bin/snapshotctl u:object_r:snapshotctl_exec:s0 +/system/bin/remount u:object_r:remount_exec:s0 +/system/bin/dhcpcd u:object_r:dhcp_exec:s0 +/system/bin/dhcpcd-6\.8\.2 u:object_r:dhcp_exec:s0 +/system/bin/dmesgd u:object_r:dmesgd_exec:s0 +/system/bin/mtpd u:object_r:mtp_exec:s0 +/system/bin/pppd u:object_r:ppp_exec:s0 +/system/bin/racoon u:object_r:racoon_exec:s0 +/system/xbin/su u:object_r:su_exec:s0 +/system/bin/dnsmasq u:object_r:dnsmasq_exec:s0 +/system/bin/linker(64)? u:object_r:system_linker_exec:s0 +/system/bin/linkerconfig u:object_r:linkerconfig_exec:s0 +/system/bin/bootstrap/linker(64)? u:object_r:system_linker_exec:s0 +/system/bin/bootstrap/linkerconfig u:object_r:linkerconfig_exec:s0 +/system/bin/llkd u:object_r:llkd_exec:s0 +/system/bin/lmkd u:object_r:lmkd_exec:s0 +/system/bin/usbd u:object_r:usbd_exec:s0 +/system/bin/inputflinger u:object_r:inputflinger_exec:s0 +/system/bin/logd u:object_r:logd_exec:s0 +/system/bin/lpdumpd u:object_r:lpdumpd_exec:s0 +/system/bin/rss_hwm_reset u:object_r:rss_hwm_reset_exec:s0 +/system/bin/perfetto u:object_r:perfetto_exec:s0 +/system/bin/mtectrl u:object_r:mtectrl_exec:s0 +/system/bin/traced u:object_r:traced_exec:s0 +/system/bin/traced_perf u:object_r:traced_perf_exec:s0 +/system/bin/traced_probes u:object_r:traced_probes_exec:s0 +/system/bin/heapprofd u:object_r:heapprofd_exec:s0 +/system/bin/uncrypt u:object_r:uncrypt_exec:s0 +/system/bin/update_verifier u:object_r:update_verifier_exec:s0 +/system/bin/logwrapper u:object_r:system_file:s0 +/system/bin/vdc u:object_r:vdc_exec:s0 +/system/bin/cppreopts\.sh u:object_r:cppreopts_exec:s0 +/system/bin/preloads_copy\.sh u:object_r:preloads_copy_exec:s0 +/system/bin/preopt2cachename u:object_r:preopt2cachename_exec:s0 +/system/bin/viewcompiler u:object_r:viewcompiler_exec:s0 +/system/bin/sgdisk u:object_r:sgdisk_exec:s0 +/system/bin/blkid u:object_r:blkid_exec:s0 +/system/bin/flags_health_check -- u:object_r:flags_health_check_exec:s0 +/system/bin/idmap2(d)? u:object_r:idmap_exec:s0 +/system/bin/update_engine u:object_r:update_engine_exec:s0 +/system/bin/profcollectd u:object_r:profcollectd_exec:s0 +/system/bin/profcollectctl u:object_r:profcollectd_exec:s0 +/system/bin/storaged u:object_r:storaged_exec:s0 +/system/bin/virtual_touchpad u:object_r:virtual_touchpad_exec:s0 +/system/bin/hw/android\.frameworks\.bufferhub@1\.0-service u:object_r:fwk_bufferhub_exec:s0 +/system/bin/hw/android\.hidl\.allocator@1\.0-service u:object_r:hal_allocator_default_exec:s0 +/system/bin/hw/android\.system\.suspend-service u:object_r:system_suspend_exec:s0 +/system/etc/cgroups\.json u:object_r:cgroup_desc_file:s0 +/system/etc/task_profiles/cgroups_[0-9]+\.json u:object_r:cgroup_desc_api_file:s0 +/system/etc/event-log-tags u:object_r:system_event_log_tags_file:s0 +/system/etc/group u:object_r:system_group_file:s0 +/system/etc/ld\.config.* u:object_r:system_linker_config_file:s0 +/system/etc/passwd u:object_r:system_passwd_file:s0 +/system/etc/seccomp_policy(/.*)? u:object_r:system_seccomp_policy_file:s0 +/system/etc/security/cacerts(/.*)? u:object_r:system_security_cacerts_file:s0 +/system/etc/selinux/mapping/[0-9]+\.[0-9]+\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/system/etc/selinux/plat_property_contexts u:object_r:property_contexts_file:s0 +/system/etc/selinux/plat_service_contexts u:object_r:service_contexts_file:s0 +/system/etc/selinux/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/system/etc/selinux/plat_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/system/etc/selinux/plat_file_contexts u:object_r:file_contexts_file:s0 +/system/etc/selinux/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/system/etc/selinux/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_and_mapping_sepolicy\.cil\.sha256 u:object_r:sepolicy_file:s0 +/system/etc/task_profiles\.json u:object_r:task_profiles_file:s0 +/system/etc/task_profiles/task_profiles_[0-9]+\.json u:object_r:task_profiles_api_file:s0 +/system/usr/share/zoneinfo(/.*)? u:object_r:system_zoneinfo_file:s0 +/system/bin/adbd u:object_r:adbd_exec:s0 +/system/bin/vold_prepare_subdirs u:object_r:vold_prepare_subdirs_exec:s0 +/system/bin/stats u:object_r:stats_exec:s0 +/system/bin/statsd u:object_r:statsd_exec:s0 +/system/bin/bpfloader u:object_r:bpfloader_exec:s0 +/system/bin/btfloader u:object_r:bpfloader_exec:s0 +/system/bin/watchdogd u:object_r:watchdogd_exec:s0 +/system/bin/apexd u:object_r:apexd_exec:s0 +/system/bin/gsid u:object_r:gsid_exec:s0 +/system/bin/simpleperf u:object_r:simpleperf_exec:s0 +/system/bin/simpleperf_app_runner u:object_r:simpleperf_app_runner_exec:s0 +/system/bin/migrate_legacy_obb_data u:object_r:migrate_legacy_obb_data_exec:s0 +/system/bin/android\.frameworks\.automotive\.display@1\.0-service u:object_r:automotive_display_service_exec:s0 +/system/bin/snapuserd u:object_r:snapuserd_exec:s0 +/system/bin/odsign u:object_r:odsign_exec:s0 +/system/bin/vehicle_binding_util u:object_r:vehicle_binding_util_exec:s0 +/system/bin/cardisplayproxyd u:object_r:automotive_display_service_exec:s0 +/system/bin/evsmanagerd u:object_r:evsmanagerd_exec:s0 +/system/bin/android\.automotive\.evs\.manager@1\.[0-9]+ u:object_r:evsmanagerd_exec:s0 + +############################# +# Vendor files +# +/(vendor|system/vendor)(/.*)? u:object_r:vendor_file:s0 +/(vendor|system/vendor)/bin/sh u:object_r:vendor_shell_exec:s0 +/(vendor|system/vendor)/bin/toybox_vendor u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/bin/toolbox u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/cgroups\.json u:object_r:vendor_cgroup_desc_file:s0 +/(vendor|system/vendor)/etc/task_profiles\.json u:object_r:vendor_task_profiles_file:s0 + +/(vendor|system/vendor)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 + +/(vendor|system/vendor)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 + +/(vendor|system/vendor)/manifest\.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/compatibility_matrix\.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/vintf(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(vendor|system/vendor)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +/(vendor|system/vendor)/apex(/[^/]+){0,2} u:object_r:vendor_apex_file:s0 +/(vendor|system/vendor)/bin/misc_writer u:object_r:vendor_misc_writer_exec:s0 +/(vendor|system/vendor)/bin/boringssl_self_test(32|64) u:object_r:vendor_boringssl_self_test_exec:s0 + +# HAL location +/(vendor|system/vendor)/lib(64)?/hw u:object_r:vendor_hal_file:s0 + +/(vendor|system/vendor)/etc/selinux/vendor_service_contexts u:object_r:vendor_service_contexts_file:s0 + +############################# +# OEM and ODM files +# +/(odm|vendor/odm)(/.*)? u:object_r:vendor_file:s0 +/(odm|vendor/odm)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/hw u:object_r:vendor_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 +/(odm|vendor/odm)/bin/sh u:object_r:vendor_shell_exec:s0 +/(odm|vendor/odm)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(odm|vendor/odm)/app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(odm|vendor/odm)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +# secure-element service: vendor uuid mapping config file +/(odm|vendor/odm|vendor|system/vendor)/etc/hal_uuid_map_(.*)?\.xml u:object_r:vendor_uuid_mapping_config_file:s0 + + +# Input configuration +/(odm|vendor/odm|vendor|system/vendor)/usr/keylayout(/.*)?\.kl u:object_r:vendor_keylayout_file:s0 +/(odm|vendor/odm|vendor|system/vendor)/usr/keychars(/.*)?\.kcm u:object_r:vendor_keychars_file:s0 +/(odm|vendor/odm|vendor|system/vendor)/usr/idc(/.*)?\.idc u:object_r:vendor_idc_file:s0 + +/oem(/.*)? u:object_r:oemfs:s0 +/oem/overlay(/.*)? u:object_r:vendor_overlay_file:s0 + +# The precompiled monolithic sepolicy will be under /odm only when +# BOARD_USES_ODMIMAGE is true: a separate odm.img is built. +/odm/etc/selinux/precompiled_sepolicy u:object_r:sepolicy_file:s0 +/odm/etc/selinux/precompiled_sepolicy\.plat_and_mapping\.sha256 u:object_r:sepolicy_file:s0 + +/(odm|vendor/odm)/etc/selinux/odm_sepolicy\.cil u:object_r:sepolicy_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_file_contexts u:object_r:file_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_property_contexts u:object_r:property_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_service_contexts u:object_r:vendor_service_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_mac_permissions\.xml u:object_r:mac_perms_file:s0 + +############################# +# Product files +# +/(product|system/product)(/.*)? u:object_r:system_file:s0 +/(product|system/product)/etc/group u:object_r:system_group_file:s0 +/(product|system/product)/etc/passwd u:object_r:system_passwd_file:s0 +/(product|system/product)/overlay(/.*)? u:object_r:system_file:s0 + +/(product|system/product)/etc/selinux/product_file_contexts u:object_r:file_contexts_file:s0 +/(product|system/product)/etc/selinux/product_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(product|system/product)/etc/selinux/product_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(product|system/product)/etc/selinux/product_property_contexts u:object_r:property_contexts_file:s0 +/(product|system/product)/etc/selinux/product_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(product|system/product)/etc/selinux/product_service_contexts u:object_r:service_contexts_file:s0 +/(product|system/product)/etc/selinux/product_mac_permissions\.xml u:object_r:mac_perms_file:s0 + +/(product|system/product)/lib(64)?(/.*)? u:object_r:system_lib_file:s0 + +############################# +# SystemExt files +# +/(system_ext|system/system_ext)(/.*)? u:object_r:system_file:s0 +/(system_ext|system/system_ext)/etc/group u:object_r:system_group_file:s0 +/(system_ext|system/system_ext)/etc/passwd u:object_r:system_passwd_file:s0 +/(system_ext|system/system_ext)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 + +/(system_ext|system/system_ext)/etc/selinux/system_ext_file_contexts u:object_r:file_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_property_contexts u:object_r:property_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_service_contexts u:object_r:service_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/(system_ext|system/system_ext)/etc/selinux/userdebug_plat_sepolicy\.cil u:object_r:sepolicy_file:s0 + +/(system_ext|system/system_ext)/bin/aidl_lazy_test_server u:object_r:aidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/aidl_lazy_cb_test_server u:object_r:aidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/hidl_lazy_test_server u:object_r:hidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/hidl_lazy_cb_test_server u:object_r:hidl_lazy_test_server_exec:s0 + +/(system_ext|system/system_ext)/bin/canhalconfigurator(-aidl)? u:object_r:canhalconfigurator_exec:s0 + +/(system_ext|system/system_ext)/lib(64)?(/.*)? u:object_r:system_lib_file:s0 + +############################# +# VendorDlkm files +# This includes VENDOR Dynamically Loadable Kernel Modules and other misc files. +# +/(vendor_dlkm|vendor/vendor_dlkm|system/vendor/vendor_dlkm)(/.*)? u:object_r:vendor_file:s0 +/(vendor_dlkm|vendor/vendor_dlkm|system/vendor/vendor_dlkm)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +############################# +# OdmDlkm files +# This includes ODM Dynamically Loadable Kernel Modules and other misc files. +# +/(odm_dlkm|vendor/odm_dlkm|system/vendor/odm_dlkm)(/.*)? u:object_r:vendor_file:s0 +/(odm_dlkm|vendor/odm_dlkm|system/vendor/odm_dlkm)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +############################# +# Vendor files from /(product|system/product)/vendor_overlay +# +# NOTE: For additional vendor file contexts for vendor overlay files, +# use device specific file_contexts. +# +/(product|system/product)/vendor_overlay/[0-9]+/.* u:object_r:vendor_file:s0 + +############################# +# Data files +# +# NOTE: When modifying existing label rules, changes may also need to +# propagate to the "Expanded data files" section. +# +/data u:object_r:system_data_root_file:s0 +/data/(.*)? u:object_r:system_data_file:s0 +# for /data/data/xxx +/data/data u:object_r:system_data_file:s0:c512,c768 +/data/data(/.*)? u:object_r:system_data_file:s0:c512,c768 +/data/system/environ(/.*)? u:object_r:environ_system_data_file:s0 +/data/system/packages\.list u:object_r:packages_list_file:s0 +/data/system/game_mode_intervention\.list u:object_r:game_mode_intervention_list_file:s0 +/data/unencrypted(/.*)? u:object_r:unencrypted_data_file:s0 +/data/backup(/.*)? u:object_r:backup_data_file:s0 +/data/secure/backup(/.*)? u:object_r:backup_data_file:s0 +/data/system/ndebugsocket u:object_r:system_ndebug_socket:s0 +/data/system/unsolzygotesocket u:object_r:system_unsolzygote_socket:s0 +/data/drm(/.*)? u:object_r:drm_data_file:s0 +/data/resource-cache(/.*)? u:object_r:resourcecache_data_file:s0 +/data/dalvik-cache(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/ota(/.*)? u:object_r:ota_data_file:s0 +/data/ota_package(/.*)? u:object_r:ota_package_file:s0 +/data/adb(/.*)? u:object_r:adb_data_file:s0 +/data/anr(/.*)? u:object_r:anr_data_file:s0 +/data/apex(/.*)? u:object_r:apex_data_file:s0 +/data/apex/active/(.*)? u:object_r:staging_data_file:s0 +/data/apex/backup/(.*)? u:object_r:staging_data_file:s0 +/data/apex/decompressed/(.*)? u:object_r:staging_data_file:s0 +/data/apex/ota_reserved(/.*)? u:object_r:apex_ota_reserved_file:s0 +/data/app(/.*)? u:object_r:apk_data_file:s0 +# Traditional /data/app/[packageName]-[randomString]/base.apk location +/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +# /data/app/[randomStringA]/[packageName]-[randomStringB]/base.apk layout +/data/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/data/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app-private(/.*)? u:object_r:apk_private_data_file:s0 +/data/app-private/vmdl.*\.tmp(/.*)? u:object_r:apk_private_tmp_file:s0 +/data/gsi(/.*)? u:object_r:gsi_data_file:s0 +/data/gsi_persistent_data u:object_r:gsi_persistent_data_file:s0 +/data/gsi/ota(/.*)? u:object_r:ota_image_data_file:s0 +/data/tombstones(/.*)? u:object_r:tombstone_data_file:s0 +/data/vendor/tombstones/wifi(/.*)? u:object_r:tombstone_wifi_data_file:s0 +/data/local/appbase(/.*)? u:object_r:apk_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/data(/.*)? u:object_r:app_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/media(/.*)? u:object_r:media_rw_data_file:s0 +/data/local/tests(/.*)? u:object_r:shell_test_data_file:s0 +/data/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/data/local/tmp/ltp(/.*)? u:object_r:nativetest_data_file:s0 +/data/local/traces(/.*)? u:object_r:trace_data_file:s0 +/data/media u:object_r:media_userdir_file:s0 +/data/media/.* u:object_r:media_rw_data_file:s0 +/data/mediadrm(/.*)? u:object_r:media_data_file:s0 +/data/nativetest(/.*)? u:object_r:nativetest_data_file:s0 +/data/nativetest64(/.*)? u:object_r:nativetest_data_file:s0 +# This directory was removed after Q Beta 2, but we need to preserve labels for upgrading devices. +/data/pkg_staging(/.*)? u:object_r:staging_data_file:s0 +/data/property(/.*)? u:object_r:property_data_file:s0 +/data/preloads(/.*)? u:object_r:preloads_data_file:s0 +/data/preloads/media(/.*)? u:object_r:preloads_media_file:s0 +/data/preloads/demo(/.*)? u:object_r:preloads_media_file:s0 +/data/server_configurable_flags(/.*)? u:object_r:server_configurable_flags_data_file:s0 +/data/app-staging(/.*)? u:object_r:staging_data_file:s0 +# Ensure we have the same labels as /data/app or /data/apex/active +# to avoid restorecon conflicts +/data/rollback/\d+/[^/]+/.*\.apk u:object_r:apk_data_file:s0 +/data/rollback/\d+/[^/]+/.*\.apex u:object_r:staging_data_file:s0 +/data/fonts/files(/.*)? u:object_r:font_data_file:s0 +/data/misc_ce u:object_r:system_userdir_file:s0 +/data/misc_de u:object_r:system_userdir_file:s0 +/data/system_ce u:object_r:system_userdir_file:s0 +/data/system_de u:object_r:system_userdir_file:s0 +/data/user u:object_r:system_userdir_file:s0 +/data/user_de u:object_r:system_userdir_file:s0 + +# Misc data +/data/misc/adb(/.*)? u:object_r:adb_keys_file:s0 +/data/misc/a11ytrace(/.*)? u:object_r:accessibility_trace_data_file:s0 +/data/misc/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc/apexdata/com\.android\.art(/.*)? u:object_r:apex_art_data_file:s0 +/data/misc/apexdata/com\.android\.compos(/.*)? u:object_r:apex_compos_data_file:s0 +/data/misc/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.scheduling(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.tethering(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 +/data/misc/apns(/.*)? u:object_r:radio_data_file:s0 +/data/misc/appcompat(/.*)? u:object_r:appcompat_data_file:s0 +/data/misc/audio(/.*)? u:object_r:audio_data_file:s0 +/data/misc/audioserver(/.*)? u:object_r:audioserver_data_file:s0 +/data/misc/audiohal(/.*)? u:object_r:audiohal_data_file:s0 +/data/misc/bootstat(/.*)? u:object_r:bootstat_data_file:s0 +/data/misc/boottrace(/.*)? u:object_r:boottrace_data_file:s0 +/data/misc/bluetooth(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluetooth/logs(/.*)? u:object_r:bluetooth_logs_data_file:s0 +/data/misc/bluedroid(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluedroid/\.a2dp_ctrl u:object_r:bluetooth_socket:s0 +/data/misc/bluedroid/\.a2dp_data u:object_r:bluetooth_socket:s0 +/data/misc/camera(/.*)? u:object_r:camera_data_file:s0 +/data/misc/carrierid(/.*)? u:object_r:radio_data_file:s0 +/data/misc/dhcp(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dhcp-6\.8\.2(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dmesgd(/.*)? u:object_r:dmesgd_data_file:s0 +/data/misc/emergencynumberdb(/.*)? u:object_r:emergency_data_file:s0 +/data/misc/gatekeeper(/.*)? u:object_r:gatekeeper_data_file:s0 +/data/misc/incidents(/.*)? u:object_r:incident_data_file:s0 +/data/misc/installd(/.*)? u:object_r:install_data_file:s0 +/data/misc/keychain(/.*)? u:object_r:keychain_data_file:s0 +/data/misc/credstore(/.*)? u:object_r:credstore_data_file:s0 +/data/misc/keystore(/.*)? u:object_r:keystore_data_file:s0 +/data/misc/logd(/.*)? u:object_r:misc_logd_file:s0 +/data/misc/media(/.*)? u:object_r:media_data_file:s0 +/data/misc/net(/.*)? u:object_r:net_data_file:s0 +/data/misc/network_watchlist(/.*)? u:object_r:network_watchlist_data_file:s0 +/data/misc/nfc/logs(/.*)? u:object_r:nfc_logs_data_file:s0 +/data/misc/odrefresh(/.*)? u:object_r:odrefresh_data_file:s0 +/data/misc/odsign(/.*)? u:object_r:odsign_data_file:s0 +/data/misc/odsign/metrics(/.*)? u:object_r:odsign_metrics_file:s0 +/data/misc/perfetto-traces/bugreport(.*)? u:object_r:perfetto_traces_bugreport_data_file:s0 +/data/misc/perfetto-traces(/.*)? u:object_r:perfetto_traces_data_file:s0 +/data/misc/perfetto-configs(/.*)? u:object_r:perfetto_configs_data_file:s0 +/data/misc/prereboot(/.*)? u:object_r:prereboot_data_file:s0 +/data/misc/profcollectd(/.*)? u:object_r:profcollectd_data_file:s0 +/data/misc/radio(/.*)? u:object_r:radio_core_data_file:s0 +/data/misc/recovery(/.*)? u:object_r:recovery_data_file:s0 +/data/misc/shared_relro(/.*)? u:object_r:shared_relro_file:s0 +/data/misc/sms(/.*)? u:object_r:radio_data_file:s0 +/data/misc/snapshotctl_log(/.*)? u:object_r:snapshotctl_log_data_file:s0 +/data/misc/stats-active-metric(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-data(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-service(/.*)? u:object_r:stats_config_data_file:s0 +/data/misc/stats-metadata(/.*)? u:object_r:stats_data_file:s0 +/data/misc/systemkeys(/.*)? u:object_r:systemkeys_data_file:s0 +/data/misc/textclassifier(/.*)? u:object_r:textclassifier_data_file:s0 +/data/misc/train-info(/.*)? u:object_r:stats_data_file:s0 +/data/misc/user(/.*)? u:object_r:misc_user_data_file:s0 +/data/misc/virtualizationservice(/.*)? u:object_r:virtualizationservice_data_file:s0 +/data/misc/vpn(/.*)? u:object_r:vpn_data_file:s0 +/data/misc/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc_ce/[0-9]+/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc/wifi/sockets(/.*)? u:object_r:wpa_socket:s0 +/data/misc/wifi/sockets/wpa_ctrl.* u:object_r:system_wpa_socket:s0 +/data/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc/update_engine(/.*)? u:object_r:update_engine_data_file:s0 +/data/misc/update_engine_log(/.*)? u:object_r:update_engine_log_data_file:s0 +/data/system/dropbox(/.*)? u:object_r:dropbox_data_file:s0 +/data/system/heapdump(/.*)? u:object_r:heapdump_data_file:s0 +/data/misc/trace(/.*)? u:object_r:method_trace_data_file:s0 +/data/misc/wmtrace(/.*)? u:object_r:wm_trace_data_file:s0 +# TODO(calin) label profile reference differently so that only +# profman run as a special user can write to them +/data/misc/profiles/cur(/[0-9]+)? u:object_r:user_profile_root_file:s0 +/data/misc/profiles/cur/[0-9]+/.* u:object_r:user_profile_data_file:s0 +/data/misc/profiles/ref(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profman(/.*)? u:object_r:profman_dump_data_file:s0 +/data/vendor(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_ce u:object_r:vendor_userdir_file:s0 +/data/vendor_ce/.* u:object_r:vendor_data_file:s0 +/data/vendor_de u:object_r:vendor_userdir_file:s0 +/data/vendor_de/.* u:object_r:vendor_data_file:s0 + +# storaged proto files +/data/misc_de/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 +/data/misc_ce/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 + +# checkin data files +/data/misc_ce/[0-9]+/checkin(/.*)? u:object_r:checkin_data_file:s0 + +# Fingerprint data +/data/system/users/[0-9]+/fpdata(/.*)? u:object_r:fingerprintd_data_file:s0 + +# Fingerprint vendor data file +/data/vendor_de/[0-9]+/fpdata(/.*)? u:object_r:fingerprint_vendor_data_file:s0 + +# Face vendor data file +/data/vendor_de/[0-9]+/facedata(/.*)? u:object_r:face_vendor_data_file:s0 +/data/vendor_ce/[0-9]+/facedata(/.*)? u:object_r:face_vendor_data_file:s0 + +# Iris vendor data file +/data/vendor_de/[0-9]+/irisdata(/.*)? u:object_r:iris_vendor_data_file:s0 + +# Bootchart data +/data/bootchart(/.*)? u:object_r:bootchart_data_file:s0 + +# Sandbox sdk data (managed by installd) +/data/misc_de/[0-9]+/sdksandbox u:object_r:sdk_sandbox_system_data_file:s0 +/data/misc_ce/[0-9]+/sdksandbox u:object_r:sdk_sandbox_system_data_file:s0 + +# App data snapshots (managed by installd). +/data/misc_de/[0-9]+/rollback(/.*)? u:object_r:rollback_data_file:s0 +/data/misc_ce/[0-9]+/rollback(/.*)? u:object_r:rollback_data_file:s0 + +# Apex data directories +/data/misc_de/[0-9]+/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc_ce/[0-9]+/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.appsearch(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 + +# Apex rollback directories +/data/misc_de/[0-9]+/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 +/data/misc_ce/[0-9]+/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 + +# Incremental directories +/data/incremental(/.*)? u:object_r:apk_data_file:s0 +/data/incremental/MT_[^/]+/mount/.pending_reads u:object_r:incremental_control_file:s0 +/data/incremental/MT_[^/]+/mount/.log u:object_r:incremental_control_file:s0 +/data/incremental/MT_[^/]+/mount/.blocks_written u:object_r:incremental_control_file:s0 + +# Boot animation data +/data/bootanim(/.*)? u:object_r:bootanim_data_file:s0 +############################# +# Expanded data files +# +/mnt/expand u:object_r:mnt_expand_file:s0 +# CAREFUL: the two system_data_file patterns below can't be replaced with one +# pattern "/mnt/expand/[^/]+(/.*)?", since SELinux would prioritize that over +# "/mnt/expand/[^/]+/user". This is because when a path is matched by two +# patterns that contain regex meta-characters, SELinux just chooses the longer +# pattern (or the later pattern if the patterns are the same length), rather +# than the pattern containing fewer regex meta-characters. Splitting the +# pattern into "/mnt/expand/[^/]+" and "/mnt/expand/[^/]+/.*" works around this +# problem, except for 1-character filenames which we aren't using. +/mnt/expand/[^/]+ u:object_r:system_data_file:s0 +/mnt/expand/[^/]+/.* u:object_r:system_data_file:s0 +/mnt/expand/[^/]+/app(/.*)? u:object_r:apk_data_file:s0 +/mnt/expand/[^/]+/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +# /mnt/expand/..../app/[randomStringA]/[packageName]-[randomStringB]/base.apk layout +/mnt/expand/[^/]+/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/mnt/expand/[^/]+/media u:object_r:media_userdir_file:s0 +/mnt/expand/[^/]+/media/.* u:object_r:media_rw_data_file:s0 +/mnt/expand/[^/]+/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/mnt/expand/[^/]+/misc_ce u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/misc_de u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/user u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/user_de u:object_r:system_userdir_file:s0 + +# coredump directory for userdebug/eng devices +/cores(/.*)? u:object_r:coredump_file:s0 + +# Wallpaper files +/data/system/users/[0-9]+/wallpaper_lock_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_lock u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper u:object_r:wallpaper_file:s0 + +# Ringtone files +/data/system_de/[0-9]+/ringtones(/.*)? u:object_r:ringtone_file:s0 + +# ShortcutManager icons, e.g. +# /data/system_ce/0/shortcut_service/bitmaps/com.example.app/1457472879282.png +/data/system_ce/[0-9]+/shortcut_service/bitmaps(/.*)? u:object_r:shortcut_manager_icons:s0 + +# User icon files +/data/system/users/[0-9]+/photo\.png u:object_r:icon_file:s0 + +# Shutdown-checkpoints files +/data/system/shutdown-checkpoints(/.*)? u:object_r:shutdown_checkpoints_system_data_file:s0 + +# vold per-user data +/data/misc_de/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc_ce/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 + +# Backup service persistent per-user bookkeeping +/data/system_ce/[0-9]+/backup(/.*)? u:object_r:backup_data_file:s0 +# Backup service temporary per-user data for inter-change with apps +/data/system_ce/[0-9]+/backup_stage(/.*)? u:object_r:backup_data_file:s0 + +############################# +# efs files +# +/efs(/.*)? u:object_r:efs_file:s0 + +############################# +# Cache files +# +/cache(/.*)? u:object_r:cache_file:s0 +/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Overlayfs support directories +# +/cache/overlay(/.*)? u:object_r:overlayfs_file:s0 +/mnt/scratch(/.*)? u:object_r:overlayfs_file:s0 + +/data/cache(/.*)? u:object_r:cache_file:s0 +/data/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/data/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/data/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Metadata files +# +/metadata(/.*)? u:object_r:metadata_file:s0 +/metadata/apex(/.*)? u:object_r:apex_metadata_file:s0 +/metadata/vold(/.*)? u:object_r:vold_metadata_file:s0 +/metadata/gsi(/.*)? u:object_r:gsi_metadata_file:s0 +/metadata/gsi/dsu/active u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/booted u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/lp_names u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/[^/]+/metadata_encryption_dir u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/ota(/.*)? u:object_r:ota_metadata_file:s0 +/metadata/password_slots(/.*)? u:object_r:password_slot_metadata_file:s0 +/metadata/ota(/.*)? u:object_r:ota_metadata_file:s0 +/metadata/bootstat(/.*)? u:object_r:metadata_bootstat_file:s0 +/metadata/sepolicy(/.*)? u:object_r:sepolicy_metadata_file:s0 +/metadata/staged-install(/.*)? u:object_r:staged_install_file:s0 +/metadata/userspacereboot(/.*)? u:object_r:userspace_reboot_metadata_file:s0 +/metadata/watchdog(/.*)? u:object_r:watchdog_metadata_file:s0 +/metadata/repair-mode(/.*)? u:object_r:repair_mode_metadata_file:s0 + +############################# +# asec containers +/mnt/asec(/.*)? u:object_r:asec_apk_file:s0 +/mnt/asec/[^/]+/[^/]+\.zip u:object_r:asec_public_file:s0 +/mnt/asec/[^/]+/lib(/.*)? u:object_r:asec_public_file:s0 +/data/app-asec(/.*)? u:object_r:asec_image_file:s0 + +############################# +# external storage +/mnt/media_rw(/.*)? u:object_r:mnt_media_rw_file:s0 +/mnt/user(/.*)? u:object_r:mnt_user_file:s0 +/mnt/pass_through(/.*)? u:object_r:mnt_pass_through_file:s0 +/mnt/sdcard u:object_r:mnt_sdcard_file:s0 +/mnt/runtime(/.*)? u:object_r:storage_file:s0 +/storage(/.*)? u:object_r:storage_file:s0 + +############################# +# mount point for read-write vendor partitions +/mnt/vendor(/.*)? u:object_r:mnt_vendor_file:s0 + +############################# +# mount point for read-write product partitions +/mnt/product(/.*)? u:object_r:mnt_product_file:s0 + +############################# +# /postinstall file contexts +/(system|product)/bin/check_dynamic_partitions u:object_r:postinstall_exec:s0 +/(system|product)/bin/otapreopt_script u:object_r:postinstall_exec:s0 +/(system|product)/bin/otapreopt u:object_r:postinstall_dexopt_exec:s0 diff --git a/aosp/system/sepolicy/private/file_contexts b/aosp/system/sepolicy/private/file_contexts new file mode 100644 index 0000000000000000000000000000000000000000..ca4873375d9113f86cd5c728c6d8978fd5e7fd72 --- /dev/null +++ b/aosp/system/sepolicy/private/file_contexts @@ -0,0 +1,916 @@ +########################################### +# Entries in this file describe the security context associated with a file +# path. They are used when building the device image, to include the security +# context within the extended file attributes of the file system. They are also +# used at runtime when calling restorecon. +# +# Entries are merged with other file_contexts from other partitions (e.g., +# vendor or odm, see the full list at libselinux/src/android/android.c). +# +# The entries are evaluated by the following rules: +# - Static entries (that is, not using regular expressions) are always +# evaluated first. +# - The first matching entry is used. +# - Entries are evaluated from the bottom to the top. +# +# Based on these rules, it is recommended that the less specific entries appear +# first. For instance: +# /dev(/.*)? u:object_r:device:s0 +# /dev/block(/.*)? u:object_r:block_device:s0 +# /dev/block/my_dev u:object_r:my_dev:s0 +# + +# Root +/ u:object_r:rootfs:s0 + +# Data files +/adb_keys u:object_r:adb_keys_file:s0 +/build\.prop u:object_r:rootfs:s0 +/default\.prop u:object_r:rootfs:s0 +/fstab\..* u:object_r:rootfs:s0 +/init\..* u:object_r:rootfs:s0 +/res(/.*)? u:object_r:rootfs:s0 +/selinux_version u:object_r:rootfs:s0 +/ueventd\..* u:object_r:rootfs:s0 +/verity_key u:object_r:rootfs:s0 + +# Executables +/init u:object_r:init_exec:s0 +/sbin(/.*)? u:object_r:rootfs:s0 + +# For kernel modules +/lib(/.*)? u:object_r:rootfs:s0 +/system_dlkm(/.*)? u:object_r:system_dlkm_file:s0 + +# Empty directories +/lost\+found u:object_r:rootfs:s0 +/acct u:object_r:cgroup:s0 +/config u:object_r:rootfs:s0 +/data_mirror u:object_r:mirror_data_file:s0 +/debug_ramdisk u:object_r:tmpfs:s0 +/mnt u:object_r:tmpfs:s0 +/proc u:object_r:rootfs:s0 +/second_stage_resources u:object_r:tmpfs:s0 +/sys u:object_r:sysfs:s0 +# proc fs & sys fs +/proc/net/route u:object_r:proc_net_route:s0 +/proc/version u:object_r:proc_version:s0 +/sys/block u:object_r:sysfs_block:s0 +/sys/bus/pci/drivers/virtio-pci u:object_r:sysfs_bpd_virtio_pci:s0 +/sys/bus/virtio u:object_r:sysfs_b_virtio:s0 +/sys/class/net/wlan0 u:object_r:sysfs_cn_wlan0:s0 +/sys/class/power_supply/battery/voltage_now u:object_r:sysfs_power:s0 +/sys/module/virtio_pci u:object_r:sysfs_m_virtio_pci:s0 +/apex u:object_r:apex_mnt_dir:s0 +/bootstrap-apex u:object_r:apex_mnt_dir:s0 +/tmp u:object_r:shell_data_file:s0 + +# Postinstall directories +/postinstall u:object_r:postinstall_mnt_dir:s0 +/postinstall/apex u:object_r:postinstall_apex_mnt_dir:s0 + +/apex/(\.(bootstrap|default)-)?apex-info-list.xml u:object_r:apex_info_file:s0 + +# Symlinks +/bin u:object_r:rootfs:s0 +/bugreports u:object_r:rootfs:s0 +/charger u:object_r:rootfs:s0 +/d u:object_r:rootfs:s0 +/etc u:object_r:rootfs:s0 +/sdcard u:object_r:rootfs:s0 + +# SELinux policy files +/vendor_file_contexts u:object_r:file_contexts_file:s0 +/plat_file_contexts u:object_r:file_contexts_file:s0 +/product_file_contexts u:object_r:file_contexts_file:s0 +/mapping_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_property_contexts u:object_r:property_contexts_file:s0 +/product_property_contexts u:object_r:property_contexts_file:s0 +/vendor_property_contexts u:object_r:property_contexts_file:s0 +/seapp_contexts u:object_r:seapp_contexts_file:s0 +/vendor_seapp_contexts u:object_r:seapp_contexts_file:s0 +/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/sepolicy u:object_r:sepolicy_file:s0 +/plat_service_contexts u:object_r:service_contexts_file:s0 +/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/plat_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/vendor_service_contexts u:object_r:vendor_service_contexts_file:s0 +/vendor_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vndservice_contexts u:object_r:vndservice_contexts_file:s0 + +########################## +# Devices +# +/dev(/.*)? u:object_r:device:s0 +/dev/adf[0-9]* u:object_r:graphics_device:s0 +/dev/adf-interface[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/adf-overlay-engine[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/ashmem u:object_r:ashmem_device:s0 +/dev/ashmem(.*)? u:object_r:ashmem_libcutils_device:s0 +/dev/audio.* u:object_r:audio_device:s0 +/dev/binder u:object_r:binder_device:s0 +/dev/block(/.*)? u:object_r:block_device:s0 +/dev/block/by-name/zoned_device u:object_r:zoned_block_device:s0 +/dev/block/dm-[0-9]+ u:object_r:dm_device:s0 +/dev/block/ublkb[0-9]+ u:object_r:ublk_block_device:s0 +/dev/block/loop[0-9]* u:object_r:loop_device:s0 +/dev/block/vd[a-z][0-9]* u:object_r:vd_device:s0 +/dev/block/vold/.+ u:object_r:vold_device:s0 +/dev/block/ram[0-9]* u:object_r:ram_device:s0 +/dev/block/zram[0-9]* u:object_r:ram_device:s0 +/dev/boringssl/selftest(/.*)? u:object_r:boringssl_self_test_marker:s0 +/dev/bus/usb(.*)? u:object_r:usb_device:s0 +/dev/console u:object_r:console_device:s0 +/dev/cpu_variant:.* u:object_r:dev_cpu_variant:s0 +/dev/dma_heap(/.*)? u:object_r:dmabuf_heap_device:s0 +/dev/dma_heap/system u:object_r:dmabuf_system_heap_device:s0 +/dev/dma_heap/system-uncached u:object_r:dmabuf_system_heap_device:s0 +/dev/dma_heap/system-secure(.*) u:object_r:dmabuf_system_secure_heap_device:s0 +/dev/dm-user(/.*)? u:object_r:dm_user_device:s0 +/dev/ublk-control u:object_r:ublk_control_device:s0 +/dev/device-mapper u:object_r:dm_device:s0 +/dev/eac u:object_r:audio_device:s0 +/dev/event-log-tags u:object_r:runtime_event_log_tags_file:s0 +/dev/cgroup_info(/.*)? u:object_r:cgroup_rc_file:s0 +/dev/fscklogs(/.*)? u:object_r:fscklogs:s0 +/dev/fuse u:object_r:fuse_device:s0 +/dev/gnss[0-9]+ u:object_r:gnss_device:s0 +/dev/graphics(/.*)? u:object_r:graphics_device:s0 +/dev/hidraw[0-9]+ u:object_r:hidraw_device:s0 +/dev/hw_random u:object_r:hw_random_device:s0 +/dev/hwbinder u:object_r:hwbinder_device:s0 +/dev/input(/.*)? u:object_r:input_device:s0 +/dev/iio:device[0-9]+ u:object_r:iio_device:s0 +/dev/ion u:object_r:ion_device:s0 +/dev/keychord u:object_r:keychord_device:s0 +/dev/loop-control u:object_r:loop_control_device:s0 +/dev/modem.* u:object_r:radio_device:s0 +/dev/mtp_usb u:object_r:mtp_device:s0 +/dev/pmsg0 u:object_r:pmsg_device:s0 +/dev/pn544 u:object_r:nfc_device:s0 +/dev/port u:object_r:port_device:s0 +/dev/ptmx u:object_r:ptmx_device:s0 +/dev/pvrsrvkm u:object_r:gpu_device:s0 +/dev/kmsg u:object_r:kmsg_device:s0 +/dev/kmsg_debug u:object_r:kmsg_debug_device:s0 +/dev/kvm u:object_r:kvm_device:s0 +/dev/null u:object_r:null_device:s0 +/dev/nvhdcp1 u:object_r:video_device:s0 +/dev/random u:object_r:random_device:s0 +/dev/rpmsg-omx[0-9] u:object_r:rpmsg_device:s0 +/dev/rproc_user u:object_r:rpmsg_device:s0 +/dev/rtc[0-9] u:object_r:rtc_device:s0 +/dev/snd(/.*)? u:object_r:audio_device:s0 +/dev/socket(/.*)? u:object_r:socket_device:s0 +/dev/socket/adbd u:object_r:adbd_socket:s0 +/dev/socket/aconfigd u:object_r:aconfigd_socket:s0 +/dev/socket/dnsproxyd u:object_r:dnsproxyd_socket:s0 +/dev/socket/dumpstate u:object_r:dumpstate_socket:s0 +/dev/socket/fwmarkd u:object_r:fwmarkd_socket:s0 +/dev/socket/lmkd u:object_r:lmkd_socket:s0 +/dev/socket/logd u:object_r:logd_socket:s0 +/dev/socket/logdr u:object_r:logdr_socket:s0 +/dev/socket/logdw u:object_r:logdw_socket:s0 +/dev/socket/statsdw u:object_r:statsdw_socket:s0 +/dev/socket/mdns u:object_r:mdns_socket:s0 +/dev/socket/mdnsd u:object_r:mdnsd_socket:s0 +/dev/socket/ot-daemon(/.*)? u:object_r:ot_daemon_socket:s0 +/dev/socket/pdx/system/buffer_hub u:object_r:pdx_bufferhub_dir:s0 +/dev/socket/pdx/system/buffer_hub/client u:object_r:pdx_bufferhub_client_endpoint_socket:s0 +/dev/socket/pdx/system/performance u:object_r:pdx_performance_dir:s0 +/dev/socket/pdx/system/performance/client u:object_r:pdx_performance_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display u:object_r:pdx_display_dir:s0 +/dev/socket/pdx/system/vr/display/client u:object_r:pdx_display_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/manager u:object_r:pdx_display_manager_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/screenshot u:object_r:pdx_display_screenshot_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/vsync u:object_r:pdx_display_vsync_endpoint_socket:s0 +/dev/socket/prng_seeder u:object_r:prng_seeder_socket:s0 +/dev/socket/property_service u:object_r:property_socket:s0 +/dev/socket/property_service_for_system u:object_r:property_socket:s0 +/dev/socket/recovery u:object_r:recovery_socket:s0 +/dev/socket/rild u:object_r:rild_socket:s0 +/dev/socket/rild-debug u:object_r:rild_debug_socket:s0 +/dev/socket/snapuserd u:object_r:snapuserd_socket:s0 +/dev/socket/snapuserd_proxy u:object_r:snapuserd_proxy_socket:s0 +/dev/socket/tombstoned_crash u:object_r:tombstoned_crash_socket:s0 +/dev/socket/tombstoned_java_trace u:object_r:tombstoned_java_trace_socket:s0 +/dev/socket/tombstoned_intercept u:object_r:tombstoned_intercept_socket:s0 +/dev/socket/traced_consumer u:object_r:traced_consumer_socket:s0 +/dev/socket/traced_perf u:object_r:traced_perf_socket:s0 +/dev/socket/traced_producer u:object_r:traced_producer_socket:s0 +/dev/socket/heapprofd u:object_r:heapprofd_socket:s0 +/dev/socket/uncrypt u:object_r:uncrypt_socket:s0 +/dev/socket/wpa_eth[0-9] u:object_r:wpa_socket:s0 +/dev/socket/wpa_wlan[0-9] u:object_r:wpa_socket:s0 +/dev/socket/zygote u:object_r:zygote_socket:s0 +/dev/socket/zygote_secondary u:object_r:zygote_socket:s0 +/dev/socket/usap_pool_primary u:object_r:zygote_socket:s0 +/dev/socket/usap_pool_secondary u:object_r:zygote_socket:s0 +/dev/spdif_out.* u:object_r:audio_device:s0 +/dev/sys/block/by-name/rootdisk(/.*)? u:object_r:rootdisk_sysdev:s0 +/dev/sys/block/by-name/userdata(/.*)? u:object_r:userdata_sysdev:s0 +/dev/sys/fs/by-name/userdata(/.*)? u:object_r:userdata_sysdev:s0 +/dev/tty u:object_r:owntty_device:s0 +/dev/tty[0-9]* u:object_r:tty_device:s0 +/dev/ttyS[0-9]* u:object_r:serial_device:s0 +/dev/ttyUSB[0-9]* u:object_r:usb_serial_device:s0 +/dev/ttyACM[0-9]* u:object_r:usb_serial_device:s0 +/dev/tun u:object_r:tun_device:s0 +/dev/uhid u:object_r:uhid_device:s0 +/dev/uinput u:object_r:uhid_device:s0 +/dev/uio[0-9]* u:object_r:uio_device:s0 +/dev/urandom u:object_r:random_device:s0 +/dev/usb_accessory u:object_r:usbaccessory_device:s0 +/dev/v4l-touch[0-9]* u:object_r:input_device:s0 +/dev/vfio(/.*)? u:object_r:vfio_device:s0 +/dev/vhost-vsock u:object_r:kvm_device:s0 +/dev/video[0-9]* u:object_r:video_device:s0 +/dev/vndbinder u:object_r:vndbinder_device:s0 +/dev/watchdog u:object_r:watchdog_device:s0 +/dev/xt_qtaguid u:object_r:qtaguid_device:s0 +/dev/zero u:object_r:zero_device:s0 +/dev/__properties__ u:object_r:properties_device:s0 +/dev/__properties__/appcompat_override u:object_r:properties_device:s0 +/dev/__properties__/property_info u:object_r:property_info:s0 +/dev/__properties__/appcompat_override/property_info u:object_r:property_info:s0 +############################# +# Linker configuration +# +/linkerconfig(/.*)? u:object_r:linkerconfig_file:s0 + +############################# +# System files +# +/system(/.*)? u:object_r:system_file:s0 +/system/apex/com.android.art u:object_r:art_apex_dir:s0 +/system/lib(64)?(/.*)? u:object_r:system_lib_file:s0 +/system/lib(64)?/bootstrap(/.*)? u:object_r:system_bootstrap_lib_file:s0 +/system/bin/mm_events u:object_r:mm_events_exec:s0 +/system/bin/atrace u:object_r:atrace_exec:s0 +/system/bin/auditctl u:object_r:auditctl_exec:s0 +/system/bin/bcc u:object_r:rs_exec:s0 +/system/bin/blank_screen u:object_r:blank_screen_exec:s0 +/system/bin/boringssl_self_test(32|64) u:object_r:boringssl_self_test_exec:s0 +/system/bin/prng_seeder u:object_r:prng_seeder_exec:s0 +/system/bin/charger u:object_r:charger_exec:s0 +/system/bin/e2fsdroid u:object_r:e2fs_exec:s0 +/system/bin/mke2fs u:object_r:e2fs_exec:s0 +/system/bin/e2fsck -- u:object_r:fsck_exec:s0 +/system/bin/extra_free_kbytes\.sh u:object_r:extra_free_kbytes_exec:s0 +/system/bin/fsck\.exfat -- u:object_r:fsck_exec:s0 +/system/bin/fsck\.f2fs -- u:object_r:fsck_exec:s0 +/system/bin/init u:object_r:init_exec:s0 +# TODO(/123600489): merge mini-keyctl into toybox +/system/bin/mini-keyctl -- u:object_r:toolbox_exec:s0 +/system/bin/fsverity_init u:object_r:fsverity_init_exec:s0 +/system/bin/sload_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/make_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/fsck_msdos -- u:object_r:fsck_exec:s0 +/system/bin/tcpdump -- u:object_r:tcpdump_exec:s0 +/system/bin/tune2fs -- u:object_r:fsck_exec:s0 +/system/bin/resize2fs -- u:object_r:fsck_exec:s0 +/system/bin/toolbox -- u:object_r:toolbox_exec:s0 +/system/bin/toybox -- u:object_r:toolbox_exec:s0 +/system/bin/ld\.mc u:object_r:rs_exec:s0 +/system/bin/logcat -- u:object_r:logcat_exec:s0 +/system/bin/logcatd -- u:object_r:logcat_exec:s0 +/system/bin/sh -- u:object_r:shell_exec:s0 +/system/bin/run-as -- u:object_r:runas_exec:s0 +/system/bin/bootanimation u:object_r:bootanim_exec:s0 +/system/bin/bootstat u:object_r:bootstat_exec:s0 +/system/bin/app_process32 u:object_r:zygote_exec:s0 +/system/bin/app_process64 u:object_r:zygote_exec:s0 +/system/bin/servicemanager u:object_r:servicemanager_exec:s0 +/system/bin/surfaceflinger u:object_r:surfaceflinger_exec:s0 +/system/bin/gpuservice u:object_r:gpuservice_exec:s0 +/system/bin/bufferhubd u:object_r:bufferhubd_exec:s0 +/system/bin/performanced u:object_r:performanced_exec:s0 +/system/bin/drmserver u:object_r:drmserver_exec:s0 +/system/bin/drmserver32 u:object_r:drmserver_exec:s0 +/system/bin/drmserver64 u:object_r:drmserver_exec:s0 +/system/bin/dumpstate u:object_r:dumpstate_exec:s0 +/system/bin/incident u:object_r:incident_exec:s0 +/system/bin/incidentd u:object_r:incidentd_exec:s0 +/system/bin/incident_helper u:object_r:incident_helper_exec:s0 +/system/bin/iw u:object_r:iw_exec:s0 +/system/bin/netutils-wrapper-1\.0 u:object_r:netutils_wrapper_exec:s0 +/system/bin/vold u:object_r:vold_exec:s0 +/system/bin/netd u:object_r:netd_exec:s0 +/system/bin/wificond u:object_r:wificond_exec:s0 +/system/bin/audioserver u:object_r:audioserver_exec:s0 +/system/bin/mediadrmserver u:object_r:mediadrmserver_exec:s0 +/system/bin/mediaserver u:object_r:mediaserver_exec:s0 +/system/bin/mediaserver32 u:object_r:mediaserver_exec:s0 +/system/bin/mediaserver64 u:object_r:mediaserver_exec:s0 +/system/bin/mediametrics u:object_r:mediametrics_exec:s0 +/system/bin/cameraserver u:object_r:cameraserver_exec:s0 +/system/bin/mediaextractor u:object_r:mediaextractor_exec:s0 +/system/bin/mediaswcodec u:object_r:mediaswcodec_exec:s0 +/system/bin/mediatranscoding u:object_r:mediatranscoding_exec:s0 +/system/bin/mediatuner u:object_r:mediatuner_exec:s0 +/system/bin/mdnsd u:object_r:mdnsd_exec:s0 +/system/bin/installd u:object_r:installd_exec:s0 +/system/bin/otapreopt_chroot u:object_r:otapreopt_chroot_exec:s0 +/system/bin/otapreopt_slot u:object_r:otapreopt_slot_exec:s0 +/system/bin/credstore u:object_r:credstore_exec:s0 +/system/bin/keystore u:object_r:keystore_exec:s0 +/system/bin/keystore2 u:object_r:keystore_exec:s0 +/system/bin/fingerprintd u:object_r:fingerprintd_exec:s0 +/system/bin/gatekeeperd u:object_r:gatekeeperd_exec:s0 +/system/bin/tombstoned u:object_r:tombstoned_exec:s0 +/system/bin/recovery-persist u:object_r:recovery_persist_exec:s0 +/system/bin/recovery-refresh u:object_r:recovery_refresh_exec:s0 +/system/bin/sdcard u:object_r:sdcardd_exec:s0 +/system/bin/snapshotctl u:object_r:snapshotctl_exec:s0 +/system/bin/remount u:object_r:remount_exec:s0 +/system/bin/dhcpcd u:object_r:dhcp_exec:s0 +/system/bin/dhcpcd-6\.8\.2 u:object_r:dhcp_exec:s0 +/system/bin/dmesgd u:object_r:dmesgd_exec:s0 +/system/xbin/su u:object_r:su_exec:s0 +/system/bin/dnsmasq u:object_r:dnsmasq_exec:s0 +/system/bin/linker(64)? u:object_r:system_linker_exec:s0 +/system/bin/linkerconfig u:object_r:linkerconfig_exec:s0 +/system/bin/bootstrap/linker(64)? u:object_r:system_linker_exec:s0 +/system/bin/bootstrap/linkerconfig u:object_r:linkerconfig_exec:s0 +/system/bin/llkd u:object_r:llkd_exec:s0 +/system/bin/lmkd u:object_r:lmkd_exec:s0 +/system/bin/usbd u:object_r:usbd_exec:s0 +/system/bin/inputflinger u:object_r:inputflinger_exec:s0 +/system/bin/logd u:object_r:logd_exec:s0 +/system/bin/lpdumpd u:object_r:lpdumpd_exec:s0 +/system/bin/rss_hwm_reset u:object_r:rss_hwm_reset_exec:s0 +/system/bin/perfetto u:object_r:perfetto_exec:s0 +/system/bin/mtectrl u:object_r:mtectrl_exec:s0 +/system/bin/misctrl u:object_r:misctrl_exec:s0 +/system/bin/traced u:object_r:traced_exec:s0 +/system/bin/traced_perf u:object_r:traced_perf_exec:s0 +/system/bin/traced_probes u:object_r:traced_probes_exec:s0 +/system/bin/heapprofd u:object_r:heapprofd_exec:s0 +/system/bin/uncrypt u:object_r:uncrypt_exec:s0 +/system/bin/update_verifier u:object_r:update_verifier_exec:s0 +/system/bin/logwrapper u:object_r:system_file:s0 +/system/bin/vdc u:object_r:vdc_exec:s0 +/system/bin/cppreopts\.sh u:object_r:cppreopts_exec:s0 +/system/bin/preloads_copy\.sh u:object_r:preloads_copy_exec:s0 +/system/bin/preopt2cachename u:object_r:preopt2cachename_exec:s0 +/system/bin/viewcompiler u:object_r:viewcompiler_exec:s0 +/system/bin/sgdisk u:object_r:sgdisk_exec:s0 +/system/bin/blkid u:object_r:blkid_exec:s0 +/system/bin/flags_health_check -- u:object_r:flags_health_check_exec:s0 +/system/bin/idmap2(d)? u:object_r:idmap_exec:s0 +/system/bin/update_engine u:object_r:update_engine_exec:s0 +/system/bin/profcollectd u:object_r:profcollectd_exec:s0 +/system/bin/profcollectctl u:object_r:profcollectd_exec:s0 +/system/bin/storaged u:object_r:storaged_exec:s0 +/system/bin/virtual_touchpad u:object_r:virtual_touchpad_exec:s0 +/system/bin/virtual_camera u:object_r:virtual_camera_exec:s0 +/system/bin/hw/android\.frameworks\.bufferhub@1\.0-service u:object_r:fwk_bufferhub_exec:s0 +/system/bin/hw/android\.system\.suspend-service u:object_r:system_suspend_exec:s0 +/(system|system_ext|product)/etc/aconfig(/.*)? u:object_r:system_aconfig_storage_file:s0 +/system/etc/cgroups\.json u:object_r:cgroup_desc_file:s0 +/system/etc/task_profiles/cgroups_[0-9]+\.json u:object_r:cgroup_desc_api_file:s0 +/system/etc/event-log-tags u:object_r:system_event_log_tags_file:s0 +/system/etc/font_fallback.xml u:object_r:system_font_fallback_file:s0 +/system/etc/group u:object_r:system_group_file:s0 +/system/etc/ld\.config.* u:object_r:system_linker_config_file:s0 +/system/etc/passwd u:object_r:system_passwd_file:s0 +/system/etc/seccomp_policy(/.*)? u:object_r:system_seccomp_policy_file:s0 +/system/etc/security/cacerts(/.*)? u:object_r:system_security_cacerts_file:s0 +/system/etc/selinux/mapping/[0-9]+\.[0-9]+(\.compat)?\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/system/etc/selinux/plat_property_contexts u:object_r:property_contexts_file:s0 +/system/etc/selinux/plat_service_contexts u:object_r:service_contexts_file:s0 +/system/etc/selinux/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/system/etc/selinux/plat_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/system/etc/selinux/plat_file_contexts u:object_r:file_contexts_file:s0 +/system/etc/selinux/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/system/etc/selinux/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_and_mapping_sepolicy\.cil\.sha256 u:object_r:sepolicy_file:s0 +/system/etc/task_profiles\.json u:object_r:task_profiles_file:s0 +/system/etc/task_profiles/task_profiles_[0-9]+\.json u:object_r:task_profiles_api_file:s0 +/system/usr/share/zoneinfo(/.*)? u:object_r:system_zoneinfo_file:s0 +/system/bin/adbd u:object_r:adbd_exec:s0 +/system/bin/vold_prepare_subdirs u:object_r:vold_prepare_subdirs_exec:s0 +/system/bin/stats u:object_r:stats_exec:s0 +/system/bin/statsd u:object_r:statsd_exec:s0 +/system/bin/bpfloader u:object_r:bpfloader_exec:s0 +/system/bin/netbpfload u:object_r:bpfloader_exec:s0 +/system/bin/watchdogd u:object_r:watchdogd_exec:s0 +/system/bin/aconfigd u:object_r:aconfigd_exec:s0 +/system/bin/apexd u:object_r:apexd_exec:s0 +/system/bin/gsid u:object_r:gsid_exec:s0 +/system/bin/simpleperf u:object_r:simpleperf_exec:s0 +/system/bin/simpleperf_app_runner u:object_r:simpleperf_app_runner_exec:s0 +/system/bin/migrate_legacy_obb_data u:object_r:migrate_legacy_obb_data_exec:s0 +/system/bin/android\.frameworks\.automotive\.display@1\.0-service u:object_r:automotive_display_service_exec:s0 +/system/bin/snapuserd u:object_r:snapuserd_exec:s0 +/system/bin/odsign u:object_r:odsign_exec:s0 +/system/bin/vehicle_binding_util u:object_r:vehicle_binding_util_exec:s0 +/system/bin/cardisplayproxyd u:object_r:automotive_display_service_exec:s0 +/system/bin/evsmanagerd u:object_r:evsmanagerd_exec:s0 +/system/bin/android\.automotive\.evs\.manager@1\.[0-9]+ u:object_r:evsmanagerd_exec:s0 +/system/bin/uprobestats u:object_r:uprobestats_exec:s0 + +############################# +# Vendor files +# +/(vendor|system/vendor)(/.*)? u:object_r:vendor_file:s0 +/(vendor|system/vendor)/bin/sh u:object_r:vendor_shell_exec:s0 +/(vendor|system/vendor)/bin/toybox_vendor u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/bin/toolbox u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/cgroups\.json u:object_r:vendor_cgroup_desc_file:s0 +/(vendor|system/vendor)/etc/task_profiles\.json u:object_r:vendor_task_profiles_file:s0 +/(vendor|system/vendor)/etc/avf/microdroid(/.*)? u:object_r:vendor_microdroid_file:s0 + +/(vendor|system/vendor)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 + +/(vendor|system/vendor)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 + +/(vendor|system/vendor)/manifest\.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/compatibility_matrix\.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/vintf(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(vendor|system/vendor)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +/(vendor|system/vendor)/apex(/[^/]+){0,2} u:object_r:vendor_apex_file:s0 +/(vendor|system/vendor)/bin/misc_writer u:object_r:vendor_misc_writer_exec:s0 +/(vendor|system/vendor)/bin/boringssl_self_test(32|64) u:object_r:vendor_boringssl_self_test_exec:s0 + +/(vendor|system/vendor)/etc/aconfig(/.*)? u:object_r:vendor_aconfig_storage_file:s0 + +# HAL location +/(vendor|system/vendor)/lib(64)?/hw u:object_r:vendor_hal_file:s0 + +/(vendor|system/vendor)/etc/selinux/vendor_service_contexts u:object_r:vendor_service_contexts_file:s0 + +############################# +# OEM and ODM files +# +/(odm|vendor/odm)(/.*)? u:object_r:vendor_file:s0 +/(odm|vendor/odm)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/hw u:object_r:vendor_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 +/(odm|vendor/odm)/bin/sh u:object_r:vendor_shell_exec:s0 +/(odm|vendor/odm)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(odm|vendor/odm)/app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(odm|vendor/odm)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +# secure-element service: vendor uuid mapping config file +/(odm|vendor/odm|vendor|system/vendor)/etc/hal_uuid_map_(.*)?\.xml u:object_r:vendor_uuid_mapping_config_file:s0 + + +# Input configuration +/(odm|vendor/odm|vendor|system/vendor)/usr/keylayout(/.*)?\.kl u:object_r:vendor_keylayout_file:s0 +/(odm|vendor/odm|vendor|system/vendor)/usr/keychars(/.*)?\.kcm u:object_r:vendor_keychars_file:s0 +/(odm|vendor/odm|vendor|system/vendor)/usr/idc(/.*)?\.idc u:object_r:vendor_idc_file:s0 + +/oem(/.*)? u:object_r:oemfs:s0 +/oem/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/oem/media/bootanimation.zip u:object_r:bootanim_oem_file:s0 +/oem/media/shutdownanimation.zip u:object_r:bootanim_oem_file:s0 +/oem/media/userspace-reboot.zip u:object_r:bootanim_oem_file:s0 + +# The precompiled monolithic sepolicy will be under /odm only when +# BOARD_USES_ODMIMAGE is true: a separate odm.img is built. +/odm/etc/selinux/precompiled_sepolicy u:object_r:sepolicy_file:s0 +/odm/etc/selinux/precompiled_sepolicy\.plat_and_mapping\.sha256 u:object_r:sepolicy_file:s0 + +/(odm|vendor/odm)/etc/selinux/odm_sepolicy\.cil u:object_r:sepolicy_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_file_contexts u:object_r:file_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_property_contexts u:object_r:property_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_service_contexts u:object_r:vendor_service_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_mac_permissions\.xml u:object_r:mac_perms_file:s0 + +############################# +# Product files +# +/(product|system/product)(/.*)? u:object_r:system_file:s0 +/(product|system/product)/etc/group u:object_r:system_group_file:s0 +/(product|system/product)/etc/passwd u:object_r:system_passwd_file:s0 +/(product|system/product)/overlay(/.*)? u:object_r:system_file:s0 + +/(product|system/product)/etc/selinux/product_file_contexts u:object_r:file_contexts_file:s0 +/(product|system/product)/etc/selinux/product_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(product|system/product)/etc/selinux/product_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(product|system/product)/etc/selinux/product_property_contexts u:object_r:property_contexts_file:s0 +/(product|system/product)/etc/selinux/product_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(product|system/product)/etc/selinux/product_service_contexts u:object_r:service_contexts_file:s0 +/(product|system/product)/etc/selinux/product_mac_permissions\.xml u:object_r:mac_perms_file:s0 + +/(product|system/product)/lib(64)?(/.*)? u:object_r:system_lib_file:s0 + +############################# +# SystemExt files +# +/(system_ext|system/system_ext)(/.*)? u:object_r:system_file:s0 +/(system_ext|system/system_ext)/etc/group u:object_r:system_group_file:s0 +/(system_ext|system/system_ext)/etc/passwd u:object_r:system_passwd_file:s0 +/(system_ext|system/system_ext)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 + +/(system_ext|system/system_ext)/etc/selinux/system_ext_file_contexts u:object_r:file_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_keystore2_key_contexts u:object_r:keystore2_key_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_property_contexts u:object_r:property_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_service_contexts u:object_r:service_contexts_file:s0 +/(system_ext|system/system_ext)/etc/selinux/system_ext_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/(system_ext|system/system_ext)/etc/selinux/userdebug_plat_sepolicy\.cil u:object_r:sepolicy_file:s0 + +/(system_ext|system/system_ext)/bin/aidl_lazy_test_server u:object_r:aidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/aidl_lazy_cb_test_server u:object_r:aidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/hidl_lazy_test_server u:object_r:hidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/hidl_lazy_cb_test_server u:object_r:hidl_lazy_test_server_exec:s0 +/(system_ext|system/system_ext)/bin/hwservicemanager u:object_r:hwservicemanager_exec:s0 +/(system_ext|system/system_ext)/bin/hw/android\.hidl\.allocator@1\.0-service u:object_r:hal_allocator_default_exec:s0 + + +/(system_ext|system/system_ext)/bin/canhalconfigurator(-aidl)? u:object_r:canhalconfigurator_exec:s0 + +/(system_ext|system/system_ext)/lib(64)?(/.*)? u:object_r:system_lib_file:s0 + +############################# +# VendorDlkm files +# This includes VENDOR Dynamically Loadable Kernel Modules and other misc files. +# +/(vendor_dlkm|vendor/vendor_dlkm|system/vendor/vendor_dlkm)(/.*)? u:object_r:vendor_file:s0 +/(vendor_dlkm|vendor/vendor_dlkm|system/vendor/vendor_dlkm)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +############################# +# OdmDlkm files +# This includes ODM Dynamically Loadable Kernel Modules and other misc files. +# +/(odm_dlkm|vendor/odm_dlkm|system/vendor/odm_dlkm)(/.*)? u:object_r:vendor_file:s0 +/(odm_dlkm|vendor/odm_dlkm|system/vendor/odm_dlkm)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +############################# +# Vendor files from /(product|system/product)/vendor_overlay +# +# NOTE: For additional vendor file contexts for vendor overlay files, +# use device specific file_contexts. +# +/(product|system/product)/vendor_overlay/[0-9]+/.* u:object_r:vendor_file:s0 + +############################# +# Data files +# +# NOTE: When modifying existing label rules, changes may also need to +# propagate to the "Expanded data files" section. +# +/data u:object_r:system_data_root_file:s0 +/data/(.*)? u:object_r:system_data_file:s0 +# for /data/data/xxx +/data/data u:object_r:system_data_file:s0:c512,c768 +/data/data(/.*)? u:object_r:system_data_file:s0:c512,c768 +/data/system/environ(/.*)? u:object_r:environ_system_data_file:s0 +/data/system/packages\.list u:object_r:packages_list_file:s0 +/data/system/game_mode_intervention\.list u:object_r:game_mode_intervention_list_file:s0 +/data/unencrypted(/.*)? u:object_r:unencrypted_data_file:s0 +/data/backup(/.*)? u:object_r:backup_data_file:s0 +/data/secure/backup(/.*)? u:object_r:backup_data_file:s0 +/data/system/ndebugsocket u:object_r:system_ndebug_socket:s0 +/data/system/unsolzygotesocket u:object_r:system_unsolzygote_socket:s0 +/data/drm(/.*)? u:object_r:drm_data_file:s0 +/data/resource-cache(/.*)? u:object_r:resourcecache_data_file:s0 +/data/dalvik-cache(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/ota(/.*)? u:object_r:ota_data_file:s0 +/data/ota_package(/.*)? u:object_r:ota_package_file:s0 +/data/adb(/.*)? u:object_r:adb_data_file:s0 +/data/anr(/.*)? u:object_r:anr_data_file:s0 +/data/apex(/.*)? u:object_r:apex_data_file:s0 +/data/apex/active/(.*)? u:object_r:staging_data_file:s0 +/data/apex/backup/(.*)? u:object_r:staging_data_file:s0 +/data/apex/decompressed/(.*)? u:object_r:staging_data_file:s0 +/data/apex/ota_reserved(/.*)? u:object_r:apex_ota_reserved_file:s0 +/data/app(/.*)? u:object_r:apk_data_file:s0 +# Traditional /data/app/[packageName]-[randomString]/base.apk location +/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +# /data/app/[randomStringA]/[packageName]-[randomStringB]/base.apk layout +/data/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/data/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app-private(/.*)? u:object_r:apk_private_data_file:s0 +/data/app-private/vmdl.*\.tmp(/.*)? u:object_r:apk_private_tmp_file:s0 +/data/gsi(/.*)? u:object_r:gsi_data_file:s0 +/data/gsi_persistent_data u:object_r:gsi_persistent_data_file:s0 +/data/gsi/ota(/.*)? u:object_r:ota_image_data_file:s0 +/data/tombstones(/.*)? u:object_r:tombstone_data_file:s0 +/data/local/appbase(/.*)? u:object_r:apk_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/data(/.*)? u:object_r:app_data_file:s0 +/data/local/appbase/[^/]+/[^/]+/[^/]+/data/media(/.*)? u:object_r:media_rw_data_file:s0 +/data/local/tests(/.*)? u:object_r:shell_test_data_file:s0 +/data/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/data/local/tmp/ltp(/.*)? u:object_r:nativetest_data_file:s0 +/data/local/traces(/.*)? u:object_r:trace_data_file:s0 +/data/media u:object_r:media_userdir_file:s0 +/data/media/.* u:object_r:media_rw_data_file:s0 +/data/mediadrm(/.*)? u:object_r:media_data_file:s0 +/data/nativetest(/.*)? u:object_r:nativetest_data_file:s0 +/data/nativetest64(/.*)? u:object_r:nativetest_data_file:s0 +# This directory was removed after Q Beta 2, but we need to preserve labels for upgrading devices. +/data/pkg_staging(/.*)? u:object_r:staging_data_file:s0 +/data/property(/.*)? u:object_r:property_data_file:s0 +/data/preloads(/.*)? u:object_r:preloads_data_file:s0 +/data/preloads/media(/.*)? u:object_r:preloads_media_file:s0 +/data/preloads/demo(/.*)? u:object_r:preloads_media_file:s0 +/data/server_configurable_flags(/.*)? u:object_r:server_configurable_flags_data_file:s0 +/data/app-staging(/.*)? u:object_r:staging_data_file:s0 +# Ensure we have the same labels as /data/app or /data/apex/active +# to avoid restorecon conflicts +/data/rollback/\d+/[^/]+/.*\.apk u:object_r:apk_data_file:s0 +/data/rollback/\d+/[^/]+/.*\.apex u:object_r:staging_data_file:s0 +/data/fonts/files(/.*)? u:object_r:font_data_file:s0 +/data/misc_ce u:object_r:system_userdir_file:s0 +/data/misc_de u:object_r:system_userdir_file:s0 +/data/system_ce u:object_r:system_userdir_file:s0 +/data/system_de u:object_r:system_userdir_file:s0 +/data/user u:object_r:system_userdir_file:s0 +/data/user_de u:object_r:system_userdir_file:s0 + +# Misc data +/data/misc/adb(/.*)? u:object_r:adb_keys_file:s0 +/data/misc/a11ytrace(/.*)? u:object_r:accessibility_trace_data_file:s0 +/data/misc/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc/apexdata/com\.android\.art(/.*)? u:object_r:apex_art_data_file:s0 +/data/misc/apexdata/com\.android\.compos(/.*)? u:object_r:apex_compos_data_file:s0 +/data/misc/apexdata/com\.android\.virt(/.*)? u:object_r:apex_virt_data_file:s0 +/data/misc/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.scheduling(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.tethering(/.*)? u:object_r:apex_tethering_data_file:s0 +/data/misc/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 +/data/misc/apns(/.*)? u:object_r:radio_data_file:s0 +/data/misc/appcompat(/.*)? u:object_r:appcompat_data_file:s0 +/data/misc/audio(/.*)? u:object_r:audio_data_file:s0 +/data/misc/audioserver(/.*)? u:object_r:audioserver_data_file:s0 +/data/misc/audiohal(/.*)? u:object_r:audiohal_data_file:s0 +/data/misc/bootstat(/.*)? u:object_r:bootstat_data_file:s0 +/data/misc/boottrace(/.*)? u:object_r:boottrace_data_file:s0 +/data/misc/bluetooth(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluetooth/logs(/.*)? u:object_r:bluetooth_logs_data_file:s0 +/data/misc/bluedroid(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluedroid/\.a2dp_ctrl u:object_r:bluetooth_socket:s0 +/data/misc/bluedroid/\.a2dp_data u:object_r:bluetooth_socket:s0 +/data/misc/camera(/.*)? u:object_r:camera_data_file:s0 +/data/misc/carrierid(/.*)? u:object_r:radio_data_file:s0 +/data/misc/dhcp(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dhcp-6\.8\.2(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dmesgd(/.*)? u:object_r:dmesgd_data_file:s0 +/data/misc/emergencynumberdb(/.*)? u:object_r:emergency_data_file:s0 +/data/misc/gatekeeper(/.*)? u:object_r:gatekeeper_data_file:s0 +/data/misc/incidents(/.*)? u:object_r:incident_data_file:s0 +/data/misc/installd(/.*)? u:object_r:install_data_file:s0 +/data/misc/keychain(/.*)? u:object_r:keychain_data_file:s0 +/data/misc/credstore(/.*)? u:object_r:credstore_data_file:s0 +/data/misc/keystore(/.*)? u:object_r:keystore_data_file:s0 +/data/misc/logd(/.*)? u:object_r:misc_logd_file:s0 +/data/misc/media(/.*)? u:object_r:media_data_file:s0 +/data/misc/net(/.*)? u:object_r:net_data_file:s0 +/data/misc/network_watchlist(/.*)? u:object_r:network_watchlist_data_file:s0 +/data/misc/telephonyconfig(/.*)? u:object_r:radio_data_file:s0 +/data/misc/nfc/logs(/.*)? u:object_r:nfc_logs_data_file:s0 +/data/misc/odrefresh(/.*)? u:object_r:odrefresh_data_file:s0 +/data/misc/odsign(/.*)? u:object_r:odsign_data_file:s0 +/data/misc/odsign/metrics(/.*)? u:object_r:odsign_metrics_file:s0 +/data/misc/perfetto-traces(/.*)? u:object_r:perfetto_traces_data_file:s0 +/data/misc/perfetto-traces/bugreport(.*)? u:object_r:perfetto_traces_bugreport_data_file:s0 +/data/misc/perfetto-traces/profiling(/.*)? u:object_r:perfetto_traces_profiling_data_file:s0 +/data/misc/perfetto-configs(/.*)? u:object_r:perfetto_configs_data_file:s0 +/data/misc/uprobestats-configs(/.*)? u:object_r:uprobestats_configs_data_file:s0 +/data/misc/prereboot(/.*)? u:object_r:prereboot_data_file:s0 +/data/misc/profcollectd(/.*)? u:object_r:profcollectd_data_file:s0 +/data/misc/radio(/.*)? u:object_r:radio_core_data_file:s0 +/data/misc/recovery(/.*)? u:object_r:recovery_data_file:s0 +/data/misc/shared_relro(/.*)? u:object_r:shared_relro_file:s0 +/data/misc/sms(/.*)? u:object_r:radio_data_file:s0 +/data/misc/snapshotctl_log(/.*)? u:object_r:snapshotctl_log_data_file:s0 +/data/misc/stats-active-metric(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-data(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-service(/.*)? u:object_r:stats_config_data_file:s0 +/data/misc/stats-metadata(/.*)? u:object_r:stats_data_file:s0 +/data/misc/systemkeys(/.*)? u:object_r:systemkeys_data_file:s0 +/data/misc/textclassifier(/.*)? u:object_r:textclassifier_data_file:s0 +/data/misc/train-info(/.*)? u:object_r:stats_data_file:s0 +/data/misc/user(/.*)? u:object_r:misc_user_data_file:s0 +/data/misc/virtualizationservice(/.*)? u:object_r:virtualizationservice_data_file:s0 +/data/misc/vpn(/.*)? u:object_r:vpn_data_file:s0 +/data/misc/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc_ce/[0-9]+/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc/wifi/sockets(/.*)? u:object_r:wpa_socket:s0 +/data/misc/wifi/sockets/wpa_ctrl.* u:object_r:system_wpa_socket:s0 +/data/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc/update_engine(/.*)? u:object_r:update_engine_data_file:s0 +/data/misc/update_engine_log(/.*)? u:object_r:update_engine_log_data_file:s0 +/data/misc/snapuserd_log(/.*)? u:object_r:snapuserd_log_data_file:s0 +/data/system/dropbox(/.*)? u:object_r:dropbox_data_file:s0 +/data/system/heapdump(/.*)? u:object_r:heapdump_data_file:s0 +/data/misc/trace(/.*)? u:object_r:method_trace_data_file:s0 +/data/misc/wmtrace(/.*)? u:object_r:wm_trace_data_file:s0 +# TODO(calin) label profile reference differently so that only +# profman run as a special user can write to them +/data/misc/profiles/cur(/[0-9]+)? u:object_r:user_profile_root_file:s0 +/data/misc/profiles/cur/[0-9]+/.* u:object_r:user_profile_data_file:s0 +/data/misc/profiles/ref(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profman(/.*)? u:object_r:profman_dump_data_file:s0 +/data/vendor(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_ce u:object_r:vendor_userdir_file:s0 +/data/vendor_ce/.* u:object_r:vendor_data_file:s0 +/data/vendor_de u:object_r:vendor_userdir_file:s0 +/data/vendor_de/.* u:object_r:vendor_data_file:s0 +/data/vendor/tombstones/wifi(/.*)? u:object_r:tombstone_wifi_data_file:s0 + +# storaged proto files +/data/misc_de/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 +/data/misc_ce/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 + +# checkin data files +/data/misc_ce/[0-9]+/checkin(/.*)? u:object_r:checkin_data_file:s0 + +# Fingerprint data +/data/system/users/[0-9]+/fpdata(/.*)? u:object_r:fingerprintd_data_file:s0 + +# Fingerprint vendor data file +/data/vendor_de/[0-9]+/fpdata(/.*)? u:object_r:fingerprint_vendor_data_file:s0 + +# Face vendor data file +/data/vendor_de/[0-9]+/facedata(/.*)? u:object_r:face_vendor_data_file:s0 +/data/vendor_ce/[0-9]+/facedata(/.*)? u:object_r:face_vendor_data_file:s0 + +# Iris vendor data file +/data/vendor_de/[0-9]+/irisdata(/.*)? u:object_r:iris_vendor_data_file:s0 + +# Bootchart data +/data/bootchart(/.*)? u:object_r:bootchart_data_file:s0 + +# Sandbox sdk data (managed by installd) +/data/misc_de/[0-9]+/sdksandbox u:object_r:sdk_sandbox_system_data_file:s0 +/data/misc_ce/[0-9]+/sdksandbox u:object_r:sdk_sandbox_system_data_file:s0 + +# App data snapshots (managed by installd). +/data/misc_de/[0-9]+/rollback(/.*)? u:object_r:rollback_data_file:s0 +/data/misc_ce/[0-9]+/rollback(/.*)? u:object_r:rollback_data_file:s0 + +# Apex data directories +/data/misc_de/[0-9]+/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc_ce/[0-9]+/apexdata(/.*)? u:object_r:apex_module_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.appsearch(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.permission(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.wifi(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_de/[0-9]+/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 +/data/misc_ce/[0-9]+/apexdata/com\.android\.uwb(/.*)? u:object_r:apex_system_server_data_file:s0 + +# Apex rollback directories +/data/misc_de/[0-9]+/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 +/data/misc_ce/[0-9]+/apexrollback(/.*)? u:object_r:apex_rollback_data_file:s0 + +# Incremental directories +/data/incremental(/.*)? u:object_r:apk_data_file:s0 +/data/incremental/MT_[^/]+/mount/.pending_reads u:object_r:incremental_control_file:s0 +/data/incremental/MT_[^/]+/mount/.log u:object_r:incremental_control_file:s0 +/data/incremental/MT_[^/]+/mount/.blocks_written u:object_r:incremental_control_file:s0 + +# Boot animation data +/data/misc/bootanim(/.*)? u:object_r:bootanim_data_file:s0 +############################# +# Expanded data files +# +/mnt/expand u:object_r:mnt_expand_file:s0 +/mnt/expand/[^/]+(/.*)? u:object_r:system_data_file:s0 +/mnt/expand/[^/]+/app(/.*)? u:object_r:apk_data_file:s0 +/mnt/expand/[^/]+/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +# /mnt/expand/..../app/[randomStringA]/[packageName]-[randomStringB]/base.apk layout +/mnt/expand/[^/]+/app/[^/]+/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/mnt/expand/[^/]+/media u:object_r:media_userdir_file:s0 +/mnt/expand/[^/]+/media/.* u:object_r:media_rw_data_file:s0 +/mnt/expand/[^/]+/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/mnt/expand/[^/]+/misc_ce u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/misc_de u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/user u:object_r:system_userdir_file:s0 +/mnt/expand/[^/]+/user_de u:object_r:system_userdir_file:s0 + +# coredump directory for userdebug/eng devices +/cores(/.*)? u:object_r:coredump_file:s0 + +# Wallpaper files +/data/system/users/[0-9]+/wallpaper_lock_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_lock u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper u:object_r:wallpaper_file:s0 + +# Ringtone files +/data/system_de/[0-9]+/ringtones(/.*)? u:object_r:ringtone_file:s0 + +# ShortcutManager icons, e.g. +# /data/system_ce/0/shortcut_service/bitmaps/com.example.app/1457472879282.png +/data/system_ce/[0-9]+/shortcut_service/bitmaps(/.*)? u:object_r:shortcut_manager_icons:s0 + +# User icon files +/data/system/users/[0-9]+/photo\.png u:object_r:icon_file:s0 + +# Shutdown-checkpoints files +/data/system/shutdown-checkpoints(/.*)? u:object_r:shutdown_checkpoints_system_data_file:s0 + +# vold per-user data +/data/misc_de/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc_ce/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 + +# Backup service persistent per-user bookkeeping +/data/system_ce/[0-9]+/backup(/.*)? u:object_r:backup_data_file:s0 +# Backup service temporary per-user data for inter-change with apps +/data/system_ce/[0-9]+/backup_stage(/.*)? u:object_r:backup_data_file:s0 + +############################# +# efs files +# +/efs(/.*)? u:object_r:efs_file:s0 + +############################# +# Cache files +# +/cache(/.*)? u:object_r:cache_file:s0 +/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Overlayfs support directories +# +/cache/overlay(/.*)? u:object_r:overlayfs_file:s0 +/mnt/scratch(/.*)? u:object_r:overlayfs_file:s0 + +/data/cache(/.*)? u:object_r:cache_file:s0 +/data/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/data/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/data/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Metadata files +# +/metadata(/.*)? u:object_r:metadata_file:s0 +/metadata/apex(/.*)? u:object_r:apex_metadata_file:s0 +/metadata/vold(/.*)? u:object_r:vold_metadata_file:s0 +/metadata/gsi(/.*)? u:object_r:gsi_metadata_file:s0 +/metadata/gsi/dsu/active u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/booted u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/lp_names u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/dsu/[^/]+/metadata_encryption_dir u:object_r:gsi_public_metadata_file:s0 +/metadata/gsi/ota(/.*)? u:object_r:ota_metadata_file:s0 +/metadata/password_slots(/.*)? u:object_r:password_slot_metadata_file:s0 +/metadata/ota(/.*)? u:object_r:ota_metadata_file:s0 +/metadata/bootstat(/.*)? u:object_r:metadata_bootstat_file:s0 +/metadata/staged-install(/.*)? u:object_r:staged_install_file:s0 +/metadata/userspacereboot(/.*)? u:object_r:userspace_reboot_metadata_file:s0 +/metadata/watchdog(/.*)? u:object_r:watchdog_metadata_file:s0 +/metadata/repair-mode(/.*)? u:object_r:repair_mode_metadata_file:s0 +/metadata/aconfig(/.*)? u:object_r:aconfig_storage_metadata_file:s0 +/metadata/aconfig/flags(/.*)? u:object_r:aconfig_storage_flags_metadata_file:s0 + +############################# +# asec containers +/mnt/asec(/.*)? u:object_r:asec_apk_file:s0 +/mnt/asec/[^/]+/[^/]+\.zip u:object_r:asec_public_file:s0 +/mnt/asec/[^/]+/lib(/.*)? u:object_r:asec_public_file:s0 +/data/app-asec(/.*)? u:object_r:asec_image_file:s0 + +############################# +# external storage +/mnt/media_rw(/.*)? u:object_r:mnt_media_rw_file:s0 +/mnt/user(/.*)? u:object_r:mnt_user_file:s0 +/mnt/pass_through(/.*)? u:object_r:mnt_pass_through_file:s0 +/mnt/sdcard u:object_r:mnt_sdcard_file:s0 +/mnt/runtime(/.*)? u:object_r:storage_file:s0 +/storage(/.*)? u:object_r:storage_file:s0 + +############################# +# mount point for read-write vendor partitions +/mnt/vendor(/.*)? u:object_r:mnt_vendor_file:s0 + +############################# +# mount point for read-write product partitions +/mnt/product(/.*)? u:object_r:mnt_product_file:s0 + +############################# +# /postinstall file contexts +/(system|product)/bin/check_dynamic_partitions u:object_r:postinstall_exec:s0 +/(system|product)/bin/otapreopt_script u:object_r:postinstall_exec:s0 +/(system|product)/bin/otapreopt u:object_r:postinstall_dexopt_exec:s0 diff --git a/aosp/system/sepolicy/public/file.te b/aosp/system/sepolicy/public/file.te new file mode 100644 index 0000000000000000000000000000000000000000..33f6b867b9cf5d70c24d76bb9f0ca87632568727 --- /dev/null +++ b/aosp/system/sepolicy/public/file.te @@ -0,0 +1,657 @@ +# Filesystem types +type labeledfs, fs_type; +type pipefs, fs_type; +type sockfs, fs_type; +type rootfs, fs_type; +type proc, fs_type, proc_type; +type binderfs, fs_type; +type binderfs_logs, fs_type; +type binderfs_logs_proc, fs_type; +type binderfs_logs_stats, fs_type; +type binderfs_features, fs_type; +# Security-sensitive proc nodes that should not be writable to most. +type proc_security, fs_type, proc_type; +type proc_drop_caches, fs_type, proc_type; +type proc_overcommit_memory, fs_type, proc_type; +type proc_min_free_order_shift, fs_type, proc_type; +type proc_kpageflags, fs_type, proc_type; +type proc_watermark_boost_factor, fs_type, proc_type; +type proc_percpu_pagelist_high_fraction, fs_type, proc_type; +# proc, sysfs, or other nodes that permit configuration of kernel usermodehelpers. +type usermodehelper, fs_type, proc_type; +type sysfs_usermodehelper, fs_type, sysfs_type; +type proc_qtaguid_ctrl, fs_type, mlstrustedobject, proc_type; +type proc_qtaguid_stat, fs_type, mlstrustedobject, proc_type; +type proc_bluetooth_writable, fs_type, proc_type; +type proc_abi, fs_type, proc_type; +type proc_asound, fs_type, proc_type; +type proc_bootconfig, fs_type, proc_type; +type proc_bpf, fs_type, proc_type; +type proc_buddyinfo, fs_type, proc_type; +type proc_cmdline, fs_type, proc_type; +type proc_cpu_alignment, fs_type, proc_type; +type proc_cpuinfo, fs_type, proc_type; +type proc_dirty, fs_type, proc_type; +type proc_diskstats, fs_type, proc_type; +type proc_extra_free_kbytes, fs_type, proc_type; +type proc_filesystems, fs_type, proc_type; +type proc_fs_verity, fs_type, proc_type; +type proc_hostname, fs_type, proc_type; +type proc_hung_task, fs_type, proc_type; +type proc_interrupts, fs_type, proc_type; +type proc_iomem, fs_type, proc_type; +type proc_kallsyms, fs_type, proc_type; +type proc_keys, fs_type, proc_type; +type proc_kmsg, fs_type, proc_type; +type proc_loadavg, fs_type, proc_type; +type proc_locks, fs_type, proc_type; +type proc_lowmemorykiller, fs_type, proc_type; +type proc_max_map_count, fs_type, proc_type; +type proc_meminfo, fs_type, proc_type; +type proc_misc, fs_type, proc_type; +type proc_modules, fs_type, proc_type; +type proc_mounts, fs_type, proc_type; +type proc_net, fs_type, proc_type, proc_net_type; +type proc_net_route, fs_type, proc_type; +type proc_net_tcp_udp, fs_type, proc_type; +type proc_page_cluster, fs_type, proc_type; +type proc_pagetypeinfo, fs_type, proc_type; +type proc_panic, fs_type, proc_type; +type proc_perf, fs_type, proc_type; +type proc_pid_max, fs_type, proc_type; +type proc_pipe_conf, fs_type, proc_type; +type proc_pressure_cpu, fs_type, proc_type; +type proc_pressure_io, fs_type, proc_type; +type proc_pressure_mem, fs_type, proc_type; +type proc_random, fs_type, proc_type; +type proc_sched, fs_type, proc_type; +type proc_slabinfo, fs_type, proc_type; +type proc_stat, fs_type, proc_type; +type proc_swaps, fs_type, proc_type; +type proc_sysrq, fs_type, proc_type; +type proc_timer, fs_type, proc_type; +type proc_tty_drivers, fs_type, proc_type; +type proc_uid_cputime_showstat, fs_type, proc_type; +type proc_uid_cputime_removeuid, fs_type, proc_type; +type proc_uid_io_stats, fs_type, proc_type; +type proc_uid_procstat_set, fs_type, proc_type; +type proc_uid_time_in_state, fs_type, proc_type; +type proc_uid_concurrent_active_time, fs_type, proc_type; +type proc_uid_concurrent_policy_time, fs_type, proc_type; +type proc_uid_cpupower, fs_type, proc_type; +type proc_uptime, fs_type, proc_type; +type proc_version, fs_type, proc_type; +type proc_vmallocinfo, fs_type, proc_type; +type proc_vmstat, fs_type, proc_type; +type proc_watermark_scale_factor, fs_type, proc_type; +type proc_zoneinfo, fs_type, proc_type; +type proc_vendor_sched, proc_type, fs_type; +type selinuxfs, fs_type, mlstrustedobject; +type fusectlfs, fs_type; +type cgroup, fs_type, mlstrustedobject; +type cgroup_v2, fs_type; +type sysfs, fs_type, sysfs_type, mlstrustedobject; +type sysfs_android_usb, fs_type, sysfs_type; +type sysfs_uio, sysfs_type, fs_type; +type sysfs_batteryinfo, fs_type, sysfs_type; +type sysfs_bluetooth_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_block, fs_type, sysfs_type; +type sysfs_bpd_virtio_pci, fs_type, sysfs_type; +type sysfs_b_virtio, fs_type, sysfs_type; +type sysfs_cn_wlan0, fs_type, sysfs_type; +type sysfs_devfreq_cur, fs_type, sysfs_type; +type sysfs_devfreq_dir, fs_type, sysfs_type; +type sysfs_devices_block, fs_type, sysfs_type; +type sysfs_dm, fs_type, sysfs_type; +type sysfs_dm_verity, fs_type, sysfs_type; +type sysfs_dma_heap, fs_type, sysfs_type; +type sysfs_dmabuf_stats, fs_type, sysfs_type; +type sysfs_dt_firmware_android, fs_type, sysfs_type; +type sysfs_extcon, fs_type, sysfs_type; +type sysfs_ion, fs_type, sysfs_type; +type sysfs_ipv4, fs_type, sysfs_type; +type sysfs_kernel_notes, fs_type, sysfs_type, mlstrustedobject; +type sysfs_leds, fs_type, sysfs_type; +type sysfs_loop, fs_type, sysfs_type; +type sysfs_gpu, fs_type, sysfs_type; +type sysfs_hwrandom, fs_type, sysfs_type; +type sysfs_nfc_power_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_wake_lock, fs_type, sysfs_type; +type sysfs_m_virtio_pci, fs_type, sysfs_type; +type sysfs_net, fs_type, sysfs_type; +type sysfs_power, fs_type, sysfs_type; +type sysfs_rtc, fs_type, sysfs_type; +type sysfs_suspend_stats, fs_type, sysfs_type; +type sysfs_switch, fs_type, sysfs_type; +type sysfs_sync_on_suspend, fs_type, sysfs_type; +type sysfs_transparent_hugepage, fs_type, sysfs_type; +type sysfs_lru_gen_enabled, fs_type, sysfs_type; +type sysfs_usb, fs_type, sysfs_type; +type sysfs_wakeup, fs_type, sysfs_type; +type sysfs_wakeup_reasons, fs_type, sysfs_type; +type sysfs_fs_ext4_features, sysfs_type, fs_type; +type sysfs_fs_f2fs, sysfs_type, fs_type; +type sysfs_fs_fuse_bpf, sysfs_type, fs_type; +type sysfs_fs_fuse_features, sysfs_type, fs_type; +type sysfs_fs_incfs_features, sysfs_type, fs_type; +type sysfs_fs_incfs_metrics, sysfs_type, fs_type; +type sysfs_vendor_sched, sysfs_type, fs_type; +userdebug_or_eng(` + typeattribute sysfs_vendor_sched mlstrustedobject; +') +type fs_bpf, fs_type, bpffs_type; +# TODO: S+ fs_bpf_tethering (used by mainline) should be private +type fs_bpf_tethering, fs_type, bpffs_type; +type fs_bpf_vendor, fs_type, bpffs_type; +type configfs, fs_type; +# /sys/devices/cs_etm +type sysfs_devices_cs_etm, fs_type, sysfs_type; +# /sys/devices/system/cpu +type sysfs_devices_system_cpu, fs_type, sysfs_type; +# /sys/module/lowmemorykiller +type sysfs_lowmemorykiller, fs_type, sysfs_type; +# /sys/module/wlan/parameters/fwpath +type sysfs_wlan_fwpath, fs_type, sysfs_type; +type sysfs_vibrator, fs_type, sysfs_type; +type sysfs_uhid, fs_type, sysfs_type; +type sysfs_thermal, sysfs_type, fs_type; + +type sysfs_zram, fs_type, sysfs_type; +type sysfs_zram_uevent, fs_type, sysfs_type; +type inotify, fs_type, mlstrustedobject; +type devpts, fs_type, mlstrustedobject; +type tmpfs, fs_type; +type shm, fs_type; +type mqueue, fs_type; +type fuse, fusefs_type, fs_type, mlstrustedobject; +type fuseblk, sdcard_type, fusefs_type, fs_type, mlstrustedobject; +type sdcardfs, sdcard_type, fs_type, mlstrustedobject; +type vfat, sdcard_type, fs_type, mlstrustedobject; +type exfat, sdcard_type, fs_type, mlstrustedobject; +type debugfs, fs_type, debugfs_type; +type debugfs_kprobes, fs_type, debugfs_type; +type debugfs_mmc, fs_type, debugfs_type; +type debugfs_mm_events_tracing, fs_type, debugfs_type, tracefs_type; +type debugfs_trace_marker, fs_type, debugfs_type, mlstrustedobject, tracefs_type; +type debugfs_tracing, fs_type, debugfs_type, mlstrustedobject, tracefs_type; +type debugfs_tracing_debug, fs_type, debugfs_type, mlstrustedobject, tracefs_type; +type debugfs_tracing_instances, fs_type, debugfs_type, tracefs_type; +type debugfs_tracing_printk_formats, fs_type, debugfs_type, tracefs_type; +type debugfs_wakeup_sources, fs_type, debugfs_type; +type debugfs_wifi_tracing, fs_type, debugfs_type, tracefs_type; +type securityfs, fs_type; + +type pstorefs, fs_type; +type functionfs, fs_type, mlstrustedobject; +type oemfs, fs_type, contextmount_type; +type usbfs, fs_type; +type binfmt_miscfs, fs_type; +type app_fusefs, fs_type, fusefs_type, contextmount_type; + +# File types +type unlabeled, file_type; + +# Default type for anything under /system. +type system_file, system_file_type, file_type; +# Default type for /system/asan.options +type system_asan_options_file, system_file_type, file_type; +# Type for /system/etc/event-log-tags (liblog implementation detail) +type system_event_log_tags_file, system_file_type, file_type; +# Default type for anything under /system/lib[64]. +type system_lib_file, system_file_type, file_type; +# system libraries that are available only to bootstrap processes +type system_bootstrap_lib_file, system_file_type, file_type; +# Default type for the group file /system/etc/group. +type system_group_file, system_file_type, file_type; +# Default type for linker executable /system/bin/linker[64]. +type system_linker_exec, system_file_type, file_type; +# Default type for linker config /system/etc/ld.config.*. +type system_linker_config_file, system_file_type, file_type; +# Default type for the passwd file /system/etc/passwd. +type system_passwd_file, system_file_type, file_type; +# Default type for linker config /system/etc/seccomp_policy/*. +type system_seccomp_policy_file, system_file_type, file_type; +# Default type for cacerts in /system/etc/security/cacerts/*. +type system_security_cacerts_file, system_file_type, file_type; +# Default type for /system/bin/tcpdump. +type tcpdump_exec, system_file_type, exec_type, file_type; +# Default type for zoneinfo files in /system/usr/share/zoneinfo/*. +type system_zoneinfo_file, system_file_type, file_type; +# Cgroups description file under /system/etc/cgroups.json +type cgroup_desc_file, system_file_type, file_type; +# Cgroups description file under /system/etc/task_profiles/cgroups_*.json +type cgroup_desc_api_file, system_file_type, file_type; +# Vendor cgroups description file under /vendor/etc/cgroups.json +type vendor_cgroup_desc_file, vendor_file_type, file_type; +# Task profiles file under /system/etc/task_profiles.json +type task_profiles_file, system_file_type, file_type; +# Task profiles file under /system/etc/task_profiles/task_profiles_*.json +type task_profiles_api_file, system_file_type, file_type; +# Vendor task profiles file under /vendor/etc/task_profiles.json +type vendor_task_profiles_file, vendor_file_type, file_type; +# Type for /system/apex/com.android.art +type art_apex_dir, system_file_type, file_type; +# /linkerconfig(/.*)? +type linkerconfig_file, file_type; +# Control files under /data/incremental +type incremental_control_file, file_type, data_file_type, core_data_file_type; +# /oem/media/bootanimation.zip|shutdownanimation.zip|userspace-reboot.zip +type bootanim_oem_file, file_type, system_file_type; + +# Default type for directories search for +# HAL implementations +type vendor_hal_file, vendor_file_type, file_type; +# Default type for under /vendor or /system/vendor +type vendor_file, vendor_file_type, file_type; +# Default type for everything in /vendor/app +type vendor_app_file, vendor_file_type, file_type; +# Default type for everything under /vendor/etc/ +type vendor_configs_file, vendor_file_type, file_type; +# Default type for all *same process* HALs and their lib/bin dependencies. +# e.g. libEGL_xxx.so, android.hardware.graphics.mapper@2.0-impl.so +type same_process_hal_file, vendor_file_type, file_type; +# Default type for vndk-sp libs. /vendor/lib/vndk-sp +type vndk_sp_file, vendor_file_type, file_type; +# Default type for everything in /vendor/framework +type vendor_framework_file, vendor_file_type, file_type; +# Default type for everything in /vendor/overlay +type vendor_overlay_file, vendor_file_type, file_type; +# Type for all vendor public libraries. These libs should only be exposed to +# apps. ABI stability of these libs is vendor's responsibility. +type vendor_public_lib_file, vendor_file_type, file_type; +# Type for all vendor public libraries for system. These libs should only be exposed to +# system. ABI stability of these libs is vendor's responsibility. +type vendor_public_framework_file, vendor_file_type, file_type; +# Type for all microdroid related files in the vendor partition. +# Files having this type should be read-only. +type vendor_microdroid_file, vendor_file_type, file_type; + +# Input configuration +type vendor_keylayout_file, vendor_file_type, file_type; +type vendor_keychars_file, vendor_file_type, file_type; +type vendor_idc_file, vendor_file_type, file_type; + +# Type for vendor uuid mapping config file +type vendor_uuid_mapping_config_file, vendor_file_type, file_type; + +# SoC-specific virtual machine disk files +type vendor_vm_file, vendor_file_type, file_type; +# SoC-specific virtual machine disk files that are mutable +type vendor_vm_data_file, vendor_file_type, file_type; + +# /metadata partition itself +type metadata_file, file_type; +# Vold files within /metadata +type vold_metadata_file, file_type; +# GSI files within /metadata +type gsi_metadata_file, gsi_metadata_file_type, file_type; +# DSU (GSI) files within /metadata that are globally readable. +type gsi_public_metadata_file, gsi_metadata_file_type, file_type; +# system_server shares Weaver slot information in /metadata +type password_slot_metadata_file, file_type; +# APEX files within /metadata +type apex_metadata_file, file_type; +# libsnapshot files within /metadata +type ota_metadata_file, file_type; +# property files within /metadata/bootstat +type metadata_bootstat_file, file_type; +# userspace reboot files within /metadata/userspacereboot +type userspace_reboot_metadata_file, file_type; +# Staged install files within /metadata/staged-install +type staged_install_file, file_type; +# Metadata information within /metadata/watchdog +type watchdog_metadata_file, file_type; +# Repair mode files within /metadata/repair-mode +type repair_mode_metadata_file, file_type; +# Aconfig storage file +type aconfig_storage_metadata_file, file_type; +# Aconfig storage flag value persistent copy +type aconfig_storage_flags_metadata_file, file_type; + +# Type for /dev/cpu_variant:.*. +type dev_cpu_variant, file_type; +# Speedup access for trusted applications to the runtime event tags +type runtime_event_log_tags_file, file_type; +# Type for /system/bin/logcat. +type logcat_exec, system_file_type, exec_type, file_type; +# Speedup access to cgroup map file +type cgroup_rc_file, file_type; +# /cores for coredumps on userdebug / eng builds +type coredump_file, file_type; +# Type of /data itself +type system_data_root_file, file_type, data_file_type, core_data_file_type; +# Default type for anything under /data. +type system_data_file, file_type, data_file_type, core_data_file_type; +# Default type for directories containing per-user encrypted directories, such +# as /data/user and /data/user_de. +type system_userdir_file, file_type, data_file_type, core_data_file_type; +# Type for /data/system/packages.list. +# TODO(b/129332765): Narrow down permissions to this. +# Find out users of system_data_file that should be granted only this. +type packages_list_file, file_type, data_file_type, core_data_file_type; +type game_mode_intervention_list_file, file_type, data_file_type, core_data_file_type; +# Default type for anything inside /data/vendor_{ce,de}. +type vendor_data_file, file_type, data_file_type; +# Type for /data/vendor_{ce,de} themselves. This has core_data_file_type +# because these directories themselves are platform-managed; only the files +# *inside* them are vendor data. (Somewhat similar to system_data_root_file.) +type vendor_userdir_file, file_type, data_file_type, core_data_file_type; +# Unencrypted data +type unencrypted_data_file, file_type, data_file_type, core_data_file_type; +# installd-create files in /data/misc/installd such as layout_version +type install_data_file, file_type, data_file_type, core_data_file_type; +# /data/drm - DRM plugin data +type drm_data_file, file_type, data_file_type, core_data_file_type; +# /data/adb - adb debugging files +type adb_data_file, file_type, data_file_type, core_data_file_type; +# /data/anr - ANR traces +type anr_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/tombstones - core dumps +type tombstone_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/vendor/tombstones/wifi - vendor wifi dumps +type tombstone_wifi_data_file, file_type, data_file_type; +# /data/apex - APEX data files +type apex_data_file, file_type, data_file_type, core_data_file_type; +# /data/app - user-installed apps +type apk_data_file, file_type, data_file_type, core_data_file_type; +type apk_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/app-private - forward-locked apps +type apk_private_data_file, file_type, data_file_type, core_data_file_type; +type apk_private_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/dalvik-cache +type dalvikcache_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota +type ota_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota_package +type ota_package_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profiles +type user_profile_root_file, file_type, data_file_type, core_data_file_type; +type user_profile_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profman +type profman_dump_data_file, file_type, data_file_type, core_data_file_type; +# /data/misc/prereboot +type prereboot_data_file, file_type, data_file_type, core_data_file_type; +# /data/resource-cache +type resourcecache_data_file, file_type, data_file_type, core_data_file_type; +# /data/local - writable by shell +type shell_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type, mlstrustedobject; +# /data/property +type property_data_file, file_type, data_file_type, core_data_file_type; +# /data/bootchart +type bootchart_data_file, file_type, data_file_type, core_data_file_type; +# /data/system/dropbox +type dropbox_data_file, file_type, data_file_type, core_data_file_type; +# /data/system/heapdump +type heapdump_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/nativetest +type nativetest_data_file, file_type, data_file_type, core_data_file_type; +# /data/local/tests +type shell_test_data_file, file_type, data_file_type, core_data_file_type; +# /data/system_de/0/ringtones +type ringtone_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/preloads +type preloads_data_file, file_type, data_file_type, core_data_file_type; +# /data/preloads/media +type preloads_media_file, file_type, data_file_type, core_data_file_type; +# /data/misc/dhcp and /data/misc/dhcp-6.8.2 +type dhcp_data_file, file_type, data_file_type, core_data_file_type; +# /data/server_configurable_flags +type server_configurable_flags_data_file, file_type, data_file_type, core_data_file_type; +# /data/app-staging +type staging_data_file, file_type, data_file_type, core_data_file_type; +# /vendor/apex +type vendor_apex_file, vendor_file_type, file_type; +# apex_manifest.pb in vendor apex +type vendor_apex_metadata_file, vendor_file_type, file_type; +# /data/system/shutdown-checkpoints +type shutdown_checkpoints_system_data_file, file_type, data_file_type, core_data_file_type; + +# Mount locations managed by vold +type mnt_media_rw_file, file_type; +type mnt_user_file, file_type; +type mnt_pass_through_file, file_type; +type mnt_expand_file, file_type; +type mnt_sdcard_file, file_type; +type storage_file, file_type; + +# Label for storage dirs which are just mount stubs +type mnt_media_rw_stub_file, file_type; +type storage_stub_file, file_type; + +# Mount location for read-write vendor partitions. +type mnt_vendor_file, file_type; + +# Mount location for read-write product partitions. +type mnt_product_file, file_type; + +# Mount point used for APEX images +type apex_mnt_dir, file_type; + +# /apex/apex-info-list.xml created by apexd +type apex_info_file, file_type; + +# /postinstall: Mount point used by update_engine to run postinstall. +type postinstall_mnt_dir, file_type; +# Files inside the /postinstall mountpoint are all labeled as postinstall_file. +type postinstall_file, file_type; +# /postinstall/apex: Mount point used for APEX images within /postinstall. +type postinstall_apex_mnt_dir, file_type; + +# /data_mirror: Contains mirror directory for storing all apps data. +type mirror_data_file, file_type, core_data_file_type; + +# /data/misc subdirectories +type adb_keys_file, file_type, data_file_type, core_data_file_type; +type apex_system_server_data_file, file_type, data_file_type, core_data_file_type, apex_data_file_type; +type apex_module_data_file, file_type, data_file_type, core_data_file_type; +type apex_ota_reserved_file, file_type, data_file_type, core_data_file_type; +type apex_rollback_data_file, file_type, data_file_type, core_data_file_type; +type appcompat_data_file, file_type, data_file_type, core_data_file_type; +type audio_data_file, file_type, data_file_type, core_data_file_type; +type audioserver_data_file, file_type, data_file_type, core_data_file_type; +type bluetooth_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type; +type bluetooth_logs_data_file, file_type, data_file_type, core_data_file_type; +type bootstat_data_file, file_type, data_file_type, core_data_file_type; +type boottrace_data_file, file_type, data_file_type, core_data_file_type; +type camera_data_file, file_type, data_file_type, core_data_file_type; +type credstore_data_file, file_type, data_file_type, core_data_file_type; +type gatekeeper_data_file, file_type, data_file_type, core_data_file_type; +type incident_data_file, file_type, data_file_type, core_data_file_type; +type keychain_data_file, file_type, data_file_type, core_data_file_type; +type keystore_data_file, file_type, data_file_type, core_data_file_type; +type media_data_file, file_type, data_file_type, core_data_file_type; +type media_rw_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type media_userdir_file, file_type, data_file_type, core_data_file_type; +type misc_user_data_file, file_type, data_file_type, core_data_file_type; +type net_data_file, file_type, data_file_type, core_data_file_type; +type network_watchlist_data_file, file_type, data_file_type, core_data_file_type; +type nfc_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type; +type nfc_logs_data_file, file_type, data_file_type, core_data_file_type; +type radio_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type, mlstrustedobject; +type recovery_data_file, file_type, data_file_type, core_data_file_type; +type shared_relro_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type snapshotctl_log_data_file, file_type, data_file_type, core_data_file_type; +type stats_config_data_file, file_type, data_file_type, core_data_file_type; +type stats_data_file, file_type, data_file_type, core_data_file_type; +type systemkeys_data_file, file_type, data_file_type, core_data_file_type; +type textclassifier_data_file, file_type, data_file_type, core_data_file_type; +type trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type vpn_data_file, file_type, data_file_type, core_data_file_type; +type wifi_data_file, file_type, data_file_type, core_data_file_type; +type vold_data_file, file_type, data_file_type, core_data_file_type; +type tee_data_file, file_type, data_file_type; +type update_engine_data_file, file_type, data_file_type, core_data_file_type; +type update_engine_log_data_file, file_type, data_file_type, core_data_file_type; +type snapuserd_log_data_file, file_type, data_file_type, core_data_file_type; +# /data/misc/trace for method traces on userdebug / eng builds +type method_trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type gsi_data_file, file_type, data_file_type, core_data_file_type; +type radio_core_data_file, file_type, data_file_type, core_data_file_type; + +# /data/data subdirectories - app sandboxes +type app_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type; +# /data/data subdirectories - priv-app sandboxes +type privapp_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type; +# /data/data subdirectory for system UID apps. +type system_app_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type, mlstrustedobject; +# Compatibility with type name used in Android 4.3 and 4.4. +# Default type for anything under /cache +type cache_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for /cache/overlay /mnt/scratch/overlay +type overlayfs_file, file_type, data_file_type, core_data_file_type; +# Type for /cache/backup_stage/* (fd interchange with apps) +type cache_backup_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# type for anything under /cache/backup (local transport storage) +type cache_private_backup_file, file_type, data_file_type, core_data_file_type; +# Type for anything under /cache/recovery +type cache_recovery_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Default type for anything under /efs +type efs_file, file_type; +# Type for wallpaper file. +type wallpaper_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for shortcut manager icon file. +type shortcut_manager_icons, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for user icon file. +type icon_file, file_type, data_file_type, core_data_file_type; +# /mnt/asec +type asec_apk_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Elements of asec files (/mnt/asec) that are world readable +type asec_public_file, file_type, data_file_type, core_data_file_type; +# /data/app-asec +type asec_image_file, file_type, data_file_type, core_data_file_type; +# /data/backup and /data/secure/backup +type backup_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# All devices have bluetooth efs files. But they +# vary per device, so this type is used in per +# device policy +type bluetooth_efs_file, file_type; +# Type for fingerprint template file +type fingerprintd_data_file, file_type, data_file_type, core_data_file_type; +# Type for _new_ fingerprint template file +type fingerprint_vendor_data_file, file_type, data_file_type; +# Type for appfuse file. +type app_fuse_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for face template file +type face_vendor_data_file, file_type, data_file_type; +# Type for iris template file +type iris_vendor_data_file, file_type, data_file_type; + +# Socket types +type adbd_socket, file_type, coredomain_socket; +type bluetooth_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type dnsproxyd_socket, file_type, coredomain_socket, mlstrustedobject; +type dumpstate_socket, file_type, coredomain_socket; +type fwmarkd_socket, file_type, coredomain_socket, mlstrustedobject; +type lmkd_socket, file_type, coredomain_socket; +type logd_socket, file_type, coredomain_socket, mlstrustedobject; +type logdr_socket, file_type, coredomain_socket, mlstrustedobject; +type logdw_socket, file_type, coredomain_socket, mlstrustedobject; +type mdns_socket, file_type, coredomain_socket; +type mdnsd_socket, file_type, coredomain_socket, mlstrustedobject; +type misc_logd_file, coredomain_socket, file_type, data_file_type, core_data_file_type; +type mtpd_socket, file_type, coredomain_socket; +type ot_daemon_socket, file_type, coredomain_socket; +type property_socket, file_type, coredomain_socket, mlstrustedobject; +type racoon_socket, file_type, coredomain_socket; +type recovery_socket, file_type, coredomain_socket; +type rild_socket, file_type; +type rild_debug_socket, file_type; +type snapuserd_socket, file_type, coredomain_socket; +type snapuserd_proxy_socket, file_type, coredomain_socket; +type statsdw_socket, file_type, coredomain_socket, mlstrustedobject; +type system_wpa_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type system_ndebug_socket, file_type, data_file_type, core_data_file_type, coredomain_socket, mlstrustedobject; +type system_unsolzygote_socket, file_type, data_file_type, core_data_file_type, coredomain_socket, mlstrustedobject; +type tombstoned_crash_socket, file_type, coredomain_socket, mlstrustedobject; +type tombstoned_java_trace_socket, file_type, mlstrustedobject; +type tombstoned_intercept_socket, file_type, coredomain_socket; +type traced_consumer_socket, file_type, coredomain_socket, mlstrustedobject; +type traced_perf_socket, file_type, coredomain_socket, mlstrustedobject; +type traced_producer_socket, file_type, coredomain_socket, mlstrustedobject; +type uncrypt_socket, file_type, coredomain_socket; +type wpa_socket, file_type, data_file_type, core_data_file_type; +type zygote_socket, file_type, coredomain_socket; +type heapprofd_socket, file_type, coredomain_socket, mlstrustedobject; +# UART (for GPS) control proc file +type gps_control, file_type; + +# PDX endpoint types +type pdx_display_dir, pdx_endpoint_dir_type, file_type; +type pdx_performance_dir, pdx_endpoint_dir_type, file_type; +type pdx_bufferhub_dir, pdx_endpoint_dir_type, file_type; + +pdx_service_socket_types(display_client, pdx_display_dir) +pdx_service_socket_types(display_manager, pdx_display_dir) +pdx_service_socket_types(display_screenshot, pdx_display_dir) +pdx_service_socket_types(display_vsync, pdx_display_dir) +pdx_service_socket_types(performance_client, pdx_performance_dir) +pdx_service_socket_types(bufferhub_client, pdx_bufferhub_dir) + +# file_contexts files +type file_contexts_file, system_file_type, file_type; + +# mac_permissions file +type mac_perms_file, system_file_type, file_type; + +# property_contexts file +type property_contexts_file, system_file_type, file_type; + +# seapp_contexts file +type seapp_contexts_file, system_file_type, file_type; + +# sepolicy files binary and others +type sepolicy_file, system_file_type, file_type; + +# service_contexts file +type service_contexts_file, system_file_type, file_type; + +# keystore2_key_contexts_file +type keystore2_key_contexts_file, system_file_type, file_type; + +# vendor service_contexts file +type vendor_service_contexts_file, vendor_file_type, file_type; + +# hwservice_contexts file +type hwservice_contexts_file, system_file_type, file_type; + +# vndservice_contexts file +type vndservice_contexts_file, file_type; + +# /sys/kernel/tracing/instances/bootreceiver for monitoring kernel memory corruptions. +type debugfs_bootreceiver_tracing, fs_type, debugfs_type, tracefs_type; + +# kernel modules +type vendor_kernel_modules, vendor_file_type, file_type; + +# system_dlkm +type system_dlkm_file, system_dlkm_file_type, file_type; + +# Allow files to be created in their appropriate filesystems. +allow fs_type self:filesystem associate; +allow cgroup tmpfs:filesystem associate; +allow cgroup_v2 tmpfs:filesystem associate; +allow cgroup_rc_file tmpfs:filesystem associate; +allow sysfs_type sysfs:filesystem associate; +allow debugfs_type { debugfs debugfs_tracing debugfs_tracing_debug }:filesystem associate; +allow file_type labeledfs:filesystem associate; +allow file_type tmpfs:filesystem associate; +allow file_type rootfs:filesystem associate; +allow dev_type tmpfs:filesystem associate; +allow app_fuse_file app_fusefs:filesystem associate; +allow postinstall_file self:filesystem associate; +allow proc_net proc:filesystem associate; + +# asanwrapper (run a sanitized app_process, to be used with wrap properties) +with_asan(`type asanwrapper_exec, exec_type, file_type;') + +# Deprecated in SDK version 28 +type audiohal_data_file, file_type, data_file_type, core_data_file_type; + +# It's a bug to assign the file_type attribute and fs_type attribute +# to any type. Do not allow it. +# +# For example, the following is a bug: +# type apk_data_file, file_type, data_file_type, fs_type; +# Should be: +# type apk_data_file, file_type, data_file_type; +neverallow fs_type file_type:filesystem associate; diff --git a/aosp/system/sepolicy/tests/policy.py b/aosp/system/sepolicy/tests/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..86237e950511b5838726a6a3522d050cbe5492b6 --- /dev/null +++ b/aosp/system/sepolicy/tests/policy.py @@ -0,0 +1,671 @@ +# Copyright 2021 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ctypes import * +import re +import os +import sys +import platform +import fc_sort + +### +# Check whether the regex will match a file path starting with the provided +# prefix +# +# Compares regex entries in file_contexts with a path prefix. Regex entries +# are often more specific than this file prefix. For example, the regex could +# be /system/bin/foo\.sh and the prefix could be /system. This function +# loops over the regex removing characters from the end until +# 1) there is a match - return True or 2) run out of characters - return +# False. +# +COMMON_PREFIXES = { + "/(vendor|system/vendor)": ["/vendor", "/system/vendor"], + "/(odm|vendor/odm)": ["/odm", "/vendor/odm"], + "/(product|system/product)": ["/product", "/system/product"], + "/(system_ext|system/system_ext)": ["/system_ext", "/system/system_ext"], +} + +def MatchPathPrefix(pathregex, prefix): + # Before running regex compile loop, try two heuristics, because compiling + # regex is too expensive. These two can handle more than 90% out of all + # MatchPathPrefix calls. + + # Heuristic 1: handle common prefixes for partitions + for c in COMMON_PREFIXES: + if not pathregex.startswith(c): + continue + found = False + for p in COMMON_PREFIXES[c]: + if prefix.startswith(p): + found = True + prefix = prefix[len(p):] + pathregex = pathregex[len(c):] + break + if not found: + return False + + # Heuristic 2: compare normal characters as long as possible + idx = 0 + while idx < len(prefix): + if idx == len(pathregex): + return False + if pathregex[idx] in fc_sort.META_CHARS or pathregex[idx] == '\\': + break + if pathregex[idx] != prefix[idx]: + return False + idx += 1 + if idx == len(prefix): + return True + + # Fall back to regex compile loop. + for i in range(len(pathregex), 0, -1): + try: + pattern = re.compile('^' + pathregex[0:i] + "$") + except: + continue + if pattern.match(prefix): + return True + return False + +def MatchPathPrefixes(pathregex, Prefixes): + for Prefix in Prefixes: + if MatchPathPrefix(pathregex, Prefix): + return True + return False + +class TERule: + def __init__(self, rule): + data = rule.split(',') + self.flavor = data[0] + self.sctx = data[1] + self.tctx = data[2] + self.tclass = data[3] + self.perms = set((data[4].strip()).split(' ')) + self.rule = rule + +class Policy: + __ExpandedRules = set() + __Rules = set() + __FcDict = None + __FcSorted = None + __GenfsDict = None + __libsepolwrap = None + __policydbP = None + __BUFSIZE = 2048 + + def AssertPathTypesDoNotHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr, ExcludedTypes = []): + # Query policy for the types associated with Attr + TypesPol = self.QueryTypeAttribute(Attr, True) - set(ExcludedTypes) + # Search file_contexts to find types associated with input paths. + PathTypes = self.__GetTypesAndFilesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix) + violators = set() + for PathType in PathTypes: + filepath, filetype = PathType + if filetype in TypesPol: + violators.add((str(filetype), str(filepath))) + + ret = "" + if len(violators) > 0: + ret += "The following types on " + ret += " ".join(str(x) for x in sorted(MatchPrefix)) + ret += " must not be associated with the " + ret += "\"" + Attr + "\" attribute.\n" + ret += "Violator types and corresponding paths:\n" + ret += "\n".join(str(x) for x in sorted(violators)) + ret += "\n" + return "" + + # Check that all types for "filesystem" have "attribute" associated with them + # for types labeled in genfs_contexts. + def AssertGenfsFilesystemTypesHaveAttr(self, Filesystem, Attr): + TypesPol = self.QueryTypeAttribute(Attr, True) + TypesGenfs = self.__GenfsDict[Filesystem] + violators = TypesGenfs.difference(TypesPol) + + ret = "" + if len(violators) > 0: + ret += "The following types in " + Filesystem + ret += " must be associated with the " + ret += "\"" + Attr + "\" attribute: " + ret += " ".join(str(x) for x in sorted(violators)) + "\n" + return "" + + # Check that path prefixes that match MatchPrefix, and do not Match + # DoNotMatchPrefix have the attribute Attr. + # For example assert that all types in /sys, and not in /sys/kernel/debugfs + # have the sysfs_type attribute. + def AssertPathTypesHaveAttr(self, MatchPrefix, DoNotMatchPrefix, Attr, ExcludedTypes = []): + # Query policy for the types associated with Attr + TypesPol = self.QueryTypeAttribute(Attr, True) | set(ExcludedTypes) + # Search file_contexts to find paths/types that should be associated with + # Attr. + PathTypes = self.__GetTypesAndFilesByFilePathPrefix(MatchPrefix, DoNotMatchPrefix) + violators = set() + for PathType in PathTypes: + filepath, filetype = PathType + if filetype not in TypesPol: + violators.add((str(filetype), str(filepath))) + + ret = "" + if len(violators) > 0: + ret += "The following types on " + ret += " ".join(str(x) for x in sorted(MatchPrefix)) + ret += " must be associated with the " + ret += "\"" + Attr + "\" attribute.\n" + ret += "Violator types and corresponding paths:\n" + ret += "\n".join(str(x) for x in sorted(violators)) + ret += "\n" + return "" + + def AssertPropertyOwnersAreExclusive(self): + systemProps = self.QueryTypeAttribute('system_property_type', True) + vendorProps = self.QueryTypeAttribute('vendor_property_type', True) + violators = systemProps.intersection(vendorProps) + ret = "" + if len(violators) > 0: + ret += "The following types have both system_property_type " + ret += "and vendor_property_type: " + ret += " ".join(str(x) for x in sorted(violators)) + "\n" + return ret + + # Return all file_contexts entries that map to the input Type. + def QueryFc(self, Type): + if Type in self.__FcDict: + return self.__FcDict[Type] + else: + return None + + # Return all attributes associated with a type if IsAttr=False or + # all types associated with an attribute if IsAttr=True + def QueryTypeAttribute(self, Type, IsAttr): + TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, + create_string_buffer(Type.encode("ascii")), IsAttr) + if (TypeIterP == None): + sys.exit("Failed to initialize type iterator") + buf = create_string_buffer(self.__BUFSIZE) + TypeAttr = set() + while True: + ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE, + self.__policydbP, TypeIterP) + if ret == 0: + TypeAttr.add(buf.value.decode("ascii")) + continue + if ret == 1: + break; + # We should never get here. + sys.exit("Failed to import policy") + self.__libsepolwrap.destroy_type_iter(TypeIterP) + return TypeAttr + + def __TERuleMatch(self, Rule, **kwargs): + # Match source type + if ("scontext" in kwargs and + len(kwargs['scontext']) > 0 and + Rule.sctx not in kwargs['scontext']): + return False + # Match target type + if ("tcontext" in kwargs and + len(kwargs['tcontext']) > 0 and + Rule.tctx not in kwargs['tcontext']): + return False + # Match target class + if ("tclass" in kwargs and + len(kwargs['tclass']) > 0 and + not bool(set([Rule.tclass]) & kwargs['tclass'])): + return False + # Match any perms + if ("perms" in kwargs and + len(kwargs['perms']) > 0 and + not bool(Rule.perms & kwargs['perms'])): + return False + return True + + # resolve a type to its attributes or + # resolve an attribute to its types and attributes + # For example if scontext is the domain attribute, then we need to + # include all types with the domain attribute such as untrusted_app and + # priv_app and all the attributes of those types such as appdomain. + def ResolveTypeAttribute(self, Type): + types = self.GetAllTypes(False) + attributes = self.GetAllTypes(True) + + if Type in types: + return self.QueryTypeAttribute(Type, False) + elif Type in attributes: + TypesAndAttributes = set() + Types = self.QueryTypeAttribute(Type, True) + TypesAndAttributes |= Types + for T in Types: + TypesAndAttributes |= self.QueryTypeAttribute(T, False) + return TypesAndAttributes + else: + return set() + + # Return all TERules that match: + # (any scontext) or (any tcontext) or (any tclass) or (any perms), + # perms. + # Any unspecified paramenter will match all. + # + # Example: QueryTERule(tcontext=["foo", "bar"], perms=["entrypoint"]) + # Will return any rule with: + # (tcontext="foo" or tcontext="bar") and ("entrypoint" in perms) + def QueryTERule(self, **kwargs): + if len(self.__Rules) == 0: + self.__InitTERules() + + # add any matching types and attributes for scontext and tcontext + if ("scontext" in kwargs and len(kwargs['scontext']) > 0): + scontext = set() + for sctx in kwargs['scontext']: + scontext |= self.ResolveTypeAttribute(sctx) + if (len(scontext) == 0): + return [] + kwargs['scontext'] = scontext + if ("tcontext" in kwargs and len(kwargs['tcontext']) > 0): + tcontext = set() + for tctx in kwargs['tcontext']: + tcontext |= self.ResolveTypeAttribute(tctx) + if (len(tcontext) == 0): + return [] + kwargs['tcontext'] = tcontext + for Rule in self.__Rules: + if self.__TERuleMatch(Rule, **kwargs): + yield Rule + + # Same as QueryTERule but only using the expanded ruleset. + # i.e. all attributes have been expanded to their various types. + def QueryExpandedTERule(self, **kwargs): + if len(self.__ExpandedRules) == 0: + self.__InitExpandedTERules() + for Rule in self.__ExpandedRules: + if self.__TERuleMatch(Rule, **kwargs): + yield Rule + + def GetAllTypes(self, isAttr): + TypeIterP = self.__libsepolwrap.init_type_iter(self.__policydbP, None, isAttr) + if (TypeIterP == None): + sys.exit("Failed to initialize type iterator") + buf = create_string_buffer(self.__BUFSIZE) + AllTypes = set() + while True: + ret = self.__libsepolwrap.get_type(buf, self.__BUFSIZE, + self.__policydbP, TypeIterP) + if ret == 0: + AllTypes.add(buf.value.decode("ascii")) + continue + if ret == 1: + break; + # We should never get here. + sys.exit("Failed to import policy") + self.__libsepolwrap.destroy_type_iter(TypeIterP) + return AllTypes + + def __ExactMatchPathPrefix(self, pathregex, prefix): + pattern = re.compile('^' + pathregex + "$") + if pattern.match(prefix): + return True + return False + + # Return a tuple (prefix, i) where i is the index of the most specific + # match of prefix in the sorted file_contexts. This is useful for limiting a + # file_contexts search to matches that are more specific and omitting less + # specific matches. For example, finding all matches to prefix /data/vendor + # should not include /data(/.*)? if /data/vendor(/.*)? is also specified. + def __FcSortedIndex(self, prefix): + index = 0 + for i in range(0, len(self.__FcSorted)): + if self.__ExactMatchPathPrefix(self.__FcSorted[i].path, prefix): + index = i + return prefix, index + + # Return a tuple of (path, Type) for all matching paths. Use the sorted + # file_contexts and index returned from __FcSortedIndex() to limit results + # to results that are more specific than the prefix. + def __MatchPathPrefixTypes(self, prefix, index): + PathType = [] + for i in range(index, len(self.__FcSorted)): + if MatchPathPrefix(self.__FcSorted[i].path, prefix): + PathType.append((self.__FcSorted[i].path, self.__FcSorted[i].type)) + return PathType + + # Return types that match MatchPrefixes but do not match + # DoNotMatchPrefixes + def __GetTypesAndFilesByFilePathPrefix(self, MatchPrefixes, DoNotMatchPrefixes): + ret = [] + + MatchPrefixesWithIndex = [] + for MatchPrefix in MatchPrefixes: + MatchPrefixesWithIndex.append(self.__FcSortedIndex(MatchPrefix)) + + for MatchPrefixWithIndex in MatchPrefixesWithIndex: + PathTypes = self.__MatchPathPrefixTypes(*MatchPrefixWithIndex) + for PathType in PathTypes: + if MatchPathPrefixes(PathType[0], DoNotMatchPrefixes): + continue + ret.append(PathType) + return ret + + def __GetTERules(self, policydbP, avtabIterP, Rules): + if Rules is None: + Rules = set() + buf = create_string_buffer(self.__BUFSIZE) + ret = 0 + while True: + ret = self.__libsepolwrap.get_allow_rule(buf, self.__BUFSIZE, + policydbP, avtabIterP) + if ret == 0: + Rule = TERule(buf.value.decode("ascii")) + Rules.add(Rule) + continue + if ret == 1: + break; + # We should never get here. + sys.exit("Failed to import policy") + + def __InitTERules(self): + avtabIterP = self.__libsepolwrap.init_avtab(self.__policydbP) + if (avtabIterP == None): + sys.exit("Failed to initialize avtab") + self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules) + self.__libsepolwrap.destroy_avtab(avtabIterP) + avtabIterP = self.__libsepolwrap.init_cond_avtab(self.__policydbP) + if (avtabIterP == None): + sys.exit("Failed to initialize conditional avtab") + self.__GetTERules(self.__policydbP, avtabIterP, self.__Rules) + self.__libsepolwrap.destroy_avtab(avtabIterP) + + def __InitExpandedTERules(self): + avtabIterP = self.__libsepolwrap.init_expanded_avtab(self.__policydbP) + if (avtabIterP == None): + sys.exit("Failed to initialize avtab") + self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules) + self.__libsepolwrap.destroy_expanded_avtab(avtabIterP) + avtabIterP = self.__libsepolwrap.init_expanded_cond_avtab(self.__policydbP) + if (avtabIterP == None): + sys.exit("Failed to initialize conditional avtab") + self.__GetTERules(self.__policydbP, avtabIterP, self.__ExpandedRules) + self.__libsepolwrap.destroy_expanded_avtab(avtabIterP) + + # load ctypes-ified libsepol wrapper + def __InitLibsepolwrap(self, LibPath): + lib = CDLL(LibPath) + + # int get_allow_rule(char *out, size_t len, void *policydbp, void *avtab_iterp); + lib.get_allow_rule.restype = c_int + lib.get_allow_rule.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p]; + # void *load_policy(const char *policy_path); + lib.load_policy.restype = c_void_p + lib.load_policy.argtypes = [c_char_p] + # void destroy_policy(void *policydbp); + lib.destroy_policy.argtypes = [c_void_p] + # void *init_expanded_avtab(void *policydbp); + lib.init_expanded_avtab.restype = c_void_p + lib.init_expanded_avtab.argtypes = [c_void_p] + # void *init_expanded_cond_avtab(void *policydbp); + lib.init_expanded_cond_avtab.restype = c_void_p + lib.init_expanded_cond_avtab.argtypes = [c_void_p] + # void destroy_expanded_avtab(void *avtab_iterp); + lib.destroy_expanded_avtab.argtypes = [c_void_p] + # void *init_avtab(void *policydbp); + lib.init_avtab.restype = c_void_p + lib.init_avtab.argtypes = [c_void_p] + # void *init_cond_avtab(void *policydbp); + lib.init_cond_avtab.restype = c_void_p + lib.init_cond_avtab.argtypes = [c_void_p] + # void destroy_avtab(void *avtab_iterp); + lib.destroy_avtab.argtypes = [c_void_p] + # int get_type(char *out, size_t max_size, void *policydbp, void *type_iterp); + lib.get_type.restype = c_int + lib.get_type.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p] + # void *init_type_iter(void *policydbp, const char *type, bool is_attr); + lib.init_type_iter.restype = c_void_p + lib.init_type_iter.argtypes = [c_void_p, c_char_p, c_bool] + # void destroy_type_iter(void *type_iterp); + lib.destroy_type_iter.argtypes = [c_void_p] + # void *init_genfs_iter(void *policydbp) + lib.init_genfs_iter.restype = c_void_p + lib.init_genfs_iter.argtypes = [c_void_p] + # int get_genfs(char *out, size_t max_size, void *genfs_iterp); + lib.get_genfs.restype = c_int + lib.get_genfs.argtypes = [c_char_p, c_size_t, c_void_p, c_void_p] + # void destroy_genfs_iter(void *genfs_iterp) + lib.destroy_genfs_iter.argtypes = [c_void_p] + + self.__libsepolwrap = lib + + def __GenfsDictAdd(self, Dict, buf): + fs, buf = buf.split(' ', 1) + path, context = buf.rsplit(' ', 1) + Type = context.split(":")[2] + if not fs in Dict: + Dict[fs] = {Type} + else: + Dict[fs].add(Type) + + def __InitGenfsCon(self): + self.__GenfsDict = {} + GenfsIterP = self.__libsepolwrap.init_genfs_iter(self.__policydbP) + if (GenfsIterP == None): + sys.exit("Failed to retreive genfs entries") + buf = create_string_buffer(self.__BUFSIZE) + while True: + ret = self.__libsepolwrap.get_genfs(buf, self.__BUFSIZE, + self.__policydbP, GenfsIterP) + if ret == 0: + self.__GenfsDictAdd(self.__GenfsDict, buf.value.decode("ascii")) + continue + if ret == 1: + self.__GenfsDictAdd(self.__GenfsDict, buf.value.decode("ascii")) + break; + # We should never get here. + sys.exit("Failed to get genfs entries") + self.__libsepolwrap.destroy_genfs_iter(GenfsIterP) + + # load file_contexts + def __InitFC(self, FcPaths): + self.__FcDict = {} + if FcPaths is None: + return + fc = [] + for path in FcPaths: + if not os.path.exists(path): + sys.exit("file_contexts file " + path + " does not exist.") + fd = open(path, "r") + fc += fd.readlines() + fd.close() + for i in fc: + rec = i.split() + try: + t = rec[-1].split(":")[2] + if t in self.__FcDict: + self.__FcDict[t].append(rec[0]) + else: + self.__FcDict[t] = [rec[0]] + except: + pass + self.__FcSorted = fc_sort.sort(FcPaths) + + # load policy + def __InitPolicy(self, PolicyPath): + cPolicyPath = create_string_buffer(PolicyPath.encode("ascii")) + self.__policydbP = self.__libsepolwrap.load_policy(cPolicyPath) + if (self.__policydbP is None): + sys.exit("Failed to load policy") + + def __init__(self, PolicyPath, FcPaths, LibPath): + self.__InitLibsepolwrap(LibPath) + self.__InitFC(FcPaths) + self.__InitPolicy(PolicyPath) + self.__InitGenfsCon() + + def __del__(self): + if self.__policydbP is not None: + self.__libsepolwrap.destroy_policy(self.__policydbP) + +coredomainAllowlist = { + # TODO: how do we make sure vendor_init doesn't have bad coupling with + # /vendor? It is the only system process which is not coredomain. + 'vendor_init', + # TODO(b/152813275): need to avoid allowlist for rootdir + "modprobe", + "slideshow", + } + +class scontext: + def __init__(self): + self.fromSystem = False + self.fromVendor = False + self.coredomain = False + self.appdomain = False + self.attributes = set() + self.entrypoints = [] + self.entrypointpaths = [] + self.error = "" + +class TestPolicy: + """A policy loaded in memory with its domains easily accessible.""" + + def __init__(self): + self.alldomains = {} + self.coredomains = set() + self.appdomains = set() + self.vendordomains = set() + self.pol = None + + # compat vars + self.alltypes = set() + self.oldalltypes = set() + self.compatMapping = None + self.pubtypes = set() + + def GetAllDomains(self): + for result in self.pol.QueryTypeAttribute("domain", True): + self.alldomains[result] = scontext() + + def GetAppDomains(self): + for d in self.alldomains: + # The application of the "appdomain" attribute is trusted because core + # selinux policy contains neverallow rules that enforce that only zygote + # and runas spawned processes may transition to processes that have + # the appdomain attribute. + if "appdomain" in self.alldomains[d].attributes: + self.alldomains[d].appdomain = True + self.appdomains.add(d) + + def GetCoreDomains(self): + for d in self.alldomains: + domain = self.alldomains[d] + # TestCoredomainViolations will verify if coredomain was incorrectly + # applied. + if "coredomain" in domain.attributes: + domain.coredomain = True + self.coredomains.add(d) + # check whether domains are executed off of /system or /vendor + if d in coredomainAllowlist: + continue + # TODO(b/153112003): add checks to prevent app domains from being + # incorrectly labeled as coredomain. Apps don't have entrypoints as + # they're always dynamically transitioned to by zygote. + if d in self.appdomains: + continue + # TODO(b/153112747): need to handle cases where there is a dynamic + # transition OR there happens to be no context in AOSP files. + if not domain.entrypointpaths: + continue + + for path in domain.entrypointpaths: + vendor = any(MatchPathPrefix(path, prefix) for prefix in + ["/vendor", "/odm"]) + system = any(MatchPathPrefix(path, prefix) for prefix in + ["/init", "/system_ext", "/product" ]) + + # only mark entrypoint as system if it is not in legacy /system/vendor + if MatchPathPrefix(path, "/system/vendor"): + vendor = True + elif MatchPathPrefix(path, "/system"): + system = True + + if not vendor and not system: + domain.error += "Unrecognized entrypoint for " + d + " at " + path + "\n" + + domain.fromSystem = domain.fromSystem or system + domain.fromVendor = domain.fromVendor or vendor + + ### + # Add the entrypoint type and path(s) to each domain. + # + def GetDomainEntrypoints(self): + for x in self.pol.QueryExpandedTERule(tclass=set(["file"]), perms=set(["entrypoint"])): + if not x.sctx in self.alldomains: + continue + self.alldomains[x.sctx].entrypoints.append(str(x.tctx)) + # postinstall_file represents a special case specific to A/B OTAs. + # Update_engine mounts a partition and relabels it postinstall_file. + # There is no file_contexts entry associated with postinstall_file + # so skip the lookup. + if x.tctx == "postinstall_file": + continue + entrypointpath = self.pol.QueryFc(x.tctx) + if not entrypointpath: + continue + self.alldomains[x.sctx].entrypointpaths.extend(entrypointpath) + + ### + # Get attributes associated with each domain + # + def GetAttributes(self): + for domain in self.alldomains: + for result in self.pol.QueryTypeAttribute(domain, False): + self.alldomains[domain].attributes.add(result) + + def setup(self, pol): + self.pol = pol + self.GetAllDomains() + self.GetAttributes() + self.GetDomainEntrypoints() + self.GetAppDomains() + self.GetCoreDomains() + + def GetAllTypes(self, basepol, oldpol): + self.alltypes = basepol.GetAllTypes(False) + self.oldalltypes = oldpol.GetAllTypes(False) + + # setup for the policy compatibility tests + def compatSetup(self, basepol, oldpol, mapping, types): + self.GetAllTypes(basepol, oldpol) + self.compatMapping = mapping + self.pubtypes = types + + def DomainsWithAttribute(self, attr): + domains = [] + for domain in self.alldomains: + if attr in self.alldomains[domain].attributes: + domains.append(domain) + return domains + + def PrintScontexts(self): + for d in sorted(self.alldomains.keys()): + sctx = self.alldomains[d] + print(d) + print("\tcoredomain="+str(sctx.coredomain)) + print("\tappdomain="+str(sctx.appdomain)) + print("\tfromSystem="+str(sctx.fromSystem)) + print("\tfromVendor="+str(sctx.fromVendor)) + print("\tattributes="+str(sctx.attributes)) + print("\tentrypoints="+str(sctx.entrypoints)) + print("\tentrypointpaths=") + if sctx.entrypointpaths is not None: + for path in sctx.entrypointpaths: + print("\t\t"+str(path)) diff --git a/aosp/system/vold/Utils.cpp b/aosp/system/vold/Utils.cpp index 7add69fba406f7931ad93035cee42e6e26f5e3dc..241dea48869b7209609dff4c399283147e97c7b1 100644 --- a/aosp/system/vold/Utils.cpp +++ b/aosp/system/vold/Utils.cpp @@ -101,23 +101,24 @@ std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relativ status_t CreateDeviceNode(const std::string& path, dev_t dev) { std::lock_guard lock(kSecurityLock); const char* cpath = path.c_str(); - auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); }); + auto clearfscreatecon = android::base::make_scope_guard([] { if (is_selinux_enabled()) setfscreatecon(nullptr); }); auto secontext = std::unique_ptr(nullptr, freecon); char* tmp_secontext; - if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFBLK) == 0) { - secontext.reset(tmp_secontext); - if (setfscreatecon(secontext.get()) != 0) { - LOG(ERROR) << "Failed to setfscreatecon for device node " << path; - return -EINVAL; + if (is_selinux_enabled()) { + if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFBLK) == 0) { + secontext.reset(tmp_secontext); + if (setfscreatecon(secontext.get()) != 0) { + LOG(ERROR) << "Failed to setfscreatecon for device node " << path; + return -EINVAL; + } + } else if (errno == ENOENT) { + LOG(DEBUG) << "No selabel defined for device node " << path; + } else { + PLOG(ERROR) << "Failed to look up selabel for device node " << path; + return -errno; } - } else if (errno == ENOENT) { - LOG(DEBUG) << "No selabel defined for device node " << path; - } else { - PLOG(ERROR) << "Failed to look up selabel for device node " << path; - return -errno; } - mode_t mode = 0660 | S_IFBLK; if (mknod(cpath, mode, dev) < 0) { if (errno != EEXIST) { @@ -477,23 +478,24 @@ status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, unsigned int attrs) { std::lock_guard lock(kSecurityLock); const char* cpath = path.c_str(); - auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); }); + auto clearfscreatecon = android::base::make_scope_guard([] { if (is_selinux_enabled()) setfscreatecon(nullptr); }); auto secontext = std::unique_ptr(nullptr, freecon); char* tmp_secontext; - if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFDIR) == 0) { - secontext.reset(tmp_secontext); - if (setfscreatecon(secontext.get()) != 0) { - LOG(ERROR) << "Failed to setfscreatecon for directory " << path; - return -EINVAL; + if (is_selinux_enabled()) { + if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFDIR) == 0) { + secontext.reset(tmp_secontext); + if (setfscreatecon(secontext.get()) != 0) { + LOG(ERROR) << "Failed to setfscreatecon for directory " << path; + return -EINVAL; + } + } else if (errno == ENOENT) { + LOG(DEBUG) << "No selabel defined for directory " << path; + } else { + PLOG(ERROR) << "Failed to look up selabel for directory " << path; + return -errno; } - } else if (errno == ENOENT) { - LOG(DEBUG) << "No selabel defined for directory " << path; - } else { - PLOG(ERROR) << "Failed to look up selabel for directory " << path; - return -errno; } - if (fs_prepare_dir(cpath, mode, uid, gid) != 0) return -errno; if (attrs && SetAttrs(path, attrs) != 0) return -errno; return OK; @@ -738,7 +740,7 @@ status_t ForkExecvp(const std::vector& args, std::vector +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct vold_configs { + bool has_adoptable : 1; + bool has_quota : 1; + bool has_reserved : 1; + bool has_compress : 1; +} VoldConfigs; + +static int process_config(VolumeManager* vm, VoldConfigs* configs); +static void coldboot(const char* path); +static void parse_args(int argc, char** argv); +static void VoldLogger(android::base::LogId log_buffer_id, android::base::LogSeverity severity, + const char* tag, const char* file, unsigned int line, const char* message); + +struct selabel_handle* sehandle; +android::base::LogdLogger logd_logger(android::base::SYSTEM); + +using android::base::StringPrintf; +using android::fs_mgr::ReadDefaultFstab; + +int main(int argc, char** argv) { + atrace_set_tracing_enabled(false); + setenv("ANDROID_LOG_TAGS", "*:d", 1); // Do not submit with verbose logs enabled + android::base::InitLogging(argv, &VoldLogger); + + LOG(INFO) << "Vold 3.0 (the awakening) firing up"; + + ATRACE_BEGIN("main"); + + LOG(DEBUG) << "Detected support for:" + << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "") + << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "") + << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : ""); + + VolumeManager* vm; + NetlinkManager* nm; + + parse_args(argc, argv); + + if (is_selinux_enabled()) { + sehandle = selinux_android_file_context_handle(); + if (!sehandle) { + LOG(ERROR) << "Failed to get SELinux file contexts handle"; + exit(1); + } + selinux_android_set_sehandle(sehandle); + } + mkdir("/dev/block/vold", 0755); + + /* For when cryptfs checks and mounts an encrypted filesystem */ + klog_set_level(6); + + /* Create our singleton managers */ + if (!(vm = VolumeManager::Instance())) { + LOG(ERROR) << "Unable to create VolumeManager"; + exit(1); + } + + if (!(nm = NetlinkManager::Instance())) { + LOG(ERROR) << "Unable to create NetlinkManager"; + exit(1); + } + + if (android::base::GetBoolProperty("vold.debug", false)) { + vm->setDebug(true); + } + + if (vm->start()) { + PLOG(ERROR) << "Unable to start VolumeManager"; + exit(1); + } + + VoldConfigs configs = {}; + if (process_config(vm, &configs)) { + PLOG(ERROR) << "Error reading configuration... continuing anyways"; + } + + android::hardware::configureRpcThreadpool(1, false /* callerWillJoin */); + + ATRACE_BEGIN("VoldNativeService::start"); + if (android::vold::VoldNativeService::start() != android::OK) { + LOG(ERROR) << "Unable to start VoldNativeService"; + exit(1); + } + ATRACE_END(); + + LOG(DEBUG) << "VoldNativeService::start() completed OK"; + + ATRACE_BEGIN("NetlinkManager::start"); + if (nm->start()) { + PLOG(ERROR) << "Unable to start NetlinkManager"; + exit(1); + } + ATRACE_END(); + + // This call should go after listeners are started to avoid + // a deadlock between vold and init (see b/34278978 for details) + android::base::SetProperty("vold.has_adoptable", configs.has_adoptable ? "1" : "0"); + android::base::SetProperty("vold.has_quota", configs.has_quota ? "1" : "0"); + android::base::SetProperty("vold.has_reserved", configs.has_reserved ? "1" : "0"); + android::base::SetProperty("vold.has_compress", configs.has_compress ? "1" : "0"); + + // Do coldboot here so it won't block booting, + // also the cold boot is needed in case we have flash drive + // connected before Vold launched + coldboot("/sys/block"); + + ATRACE_END(); + + android::IPCThreadState::self()->joinThreadPool(); + LOG(INFO) << "vold shutting down"; + + exit(0); +} + +static void parse_args(int argc, char** argv) { + static struct option opts[] = { + {"blkid_context", required_argument, 0, 'b'}, + {"blkid_untrusted_context", required_argument, 0, 'B'}, + {"fsck_context", required_argument, 0, 'f'}, + {"fsck_untrusted_context", required_argument, 0, 'F'}, + {nullptr, 0, nullptr, 0}, + }; + + int c; + while ((c = getopt_long(argc, argv, "", opts, nullptr)) != -1) { + switch (c) { + // clang-format off + case 'b': android::vold::sBlkidContext = optarg; break; + case 'B': android::vold::sBlkidUntrustedContext = optarg; break; + case 'f': android::vold::sFsckContext = optarg; break; + case 'F': android::vold::sFsckUntrustedContext = optarg; break; + // clang-format on + } + } + + CHECK(android::vold::sBlkidContext != nullptr); + CHECK(android::vold::sBlkidUntrustedContext != nullptr); + CHECK(android::vold::sFsckContext != nullptr); + CHECK(android::vold::sFsckUntrustedContext != nullptr); +} + +static void do_coldboot(DIR* d, int lvl) { + struct dirent* de; + int dfd, fd; + + dfd = dirfd(d); + + fd = openat(dfd, "uevent", O_WRONLY | O_CLOEXEC); + if (fd >= 0) { + write(fd, "add\n", 4); + close(fd); + } + + while ((de = readdir(d))) { + DIR* d2; + + if (de->d_name[0] == '.') continue; + + if (de->d_type != DT_DIR && lvl > 0) continue; + + fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (fd < 0) continue; + + d2 = fdopendir(fd); + if (d2 == 0) + close(fd); + else { + do_coldboot(d2, lvl + 1); + closedir(d2); + } + } +} + +static void coldboot(const char* path) { + ATRACE_NAME("coldboot"); + DIR* d = opendir(path); + if (d) { + do_coldboot(d, 0); + closedir(d); + } +} + +static int process_config(VolumeManager* vm, VoldConfigs* configs) { + ATRACE_NAME("process_config"); + + if (!ReadDefaultFstab(&fstab_default)) { + PLOG(ERROR) << "Failed to open default fstab"; + return -1; + } + + /* Loop through entries looking for ones that vold manages */ + configs->has_adoptable = false; + configs->has_quota = false; + configs->has_reserved = false; + configs->has_compress = false; + for (auto& entry : fstab_default) { + if (entry.fs_mgr_flags.quota) { + configs->has_quota = true; + } + if (entry.reserved_size > 0) { + configs->has_reserved = true; + } + if (entry.fs_mgr_flags.fs_compress) { + configs->has_compress = true; + } + + /* Make sure logical partitions have an updated blk_device. */ + if (entry.fs_mgr_flags.logical && !fs_mgr_update_logical_partition(&entry) && + !entry.fs_mgr_flags.no_fail) { + PLOG(FATAL) << "could not find logical partition " << entry.blk_device; + } + + if (entry.mount_point == "/data" && !entry.metadata_key_dir.empty()) { + // Pre-populate userdata dm-devices since the uevents are asynchronous (b/198405417). + android::vold::defaultkey_precreate_dm_device(); + } + + if (entry.fs_mgr_flags.vold_managed) { + if (entry.fs_mgr_flags.nonremovable) { + LOG(WARNING) << "nonremovable no longer supported; ignoring volume"; + continue; + } + + std::string sysPattern(entry.blk_device); + std::string nickname(entry.label); + int flags = 0; + + if (entry.is_encryptable()) { + flags |= android::vold::Disk::Flags::kAdoptable; + configs->has_adoptable = true; + } + if (entry.fs_mgr_flags.no_emulated_sd || + android::base::GetBoolProperty("vold.debug.default_primary", false)) { + flags |= android::vold::Disk::Flags::kDefaultPrimary; + } + + vm->addDiskSource(std::shared_ptr( + new VolumeManager::DiskSource(sysPattern, nickname, flags))); + } + } + return 0; +} + +static void VoldLogger(android::base::LogId log_buffer_id, android::base::LogSeverity severity, + const char* tag, const char* file, unsigned int line, const char* message) { + logd_logger(log_buffer_id, severity, tag, file, line, message); + + if (severity >= android::base::WARNING) { + static bool early_boot_done = false; + + // If metadata encryption setup (fscrypt_mount_metadata_encrypted) or + // basic FBE setup (fscrypt_init_user0) fails, then the boot will fail + // before adb can be started, so logcat won't be available. To allow + // debugging these early boot failures, log early errors and warnings to + // the kernel log. This allows diagnosing failures via the serial log, + // or via last dmesg/"fastboot oem dmesg" on devices that support it. + // + // As a very quick-and-dirty test for whether /data has been mounted, + // check whether /data/misc/vold exists. + if (!early_boot_done) { + if (access("/data/misc/vold", F_OK) == 0 && fscrypt_init_user0_done) { + early_boot_done = true; + return; + } + android::base::KernelLogger(log_buffer_id, severity, tag, file, line, message); + } + } +} diff --git a/aosp/system/vold/vold_prepare_subdirs.cpp b/aosp/system/vold/vold_prepare_subdirs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c131d0ae16bf626595c25e0d4d57cd0d50fa782 --- /dev/null +++ b/aosp/system/vold/vold_prepare_subdirs.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Tool to create a directory with the right SELinux context applied, or + * apply the context if it's absent. Also fixes mode, uid, gid. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "Utils.h" +#include "android/os/IVold.h" + +#include + +static void usage(const char* progname) { + std::cerr << "Usage: " << progname << " [ prepare | destroy ] " + << std::endl; + exit(-1); +} + +static bool small_int(const std::string& s) { + return !s.empty() && s.size() < 7 && s.find_first_not_of("0123456789") == std::string::npos; +} + +static bool valid_uuid(const std::string& s) { + return s.size() < 40 && s.find_first_not_of("0123456789abcdefABCDEF-_") == std::string::npos; +} + +static bool prepare_dir_for_user(struct selabel_handle* sehandle, mode_t mode, uid_t uid, gid_t gid, + const std::string& path, uid_t user_id) { + auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); }); + auto secontext = std::unique_ptr(nullptr, freecon); + char* tmp_secontext; + + if (is_selinux_enabled()) { + if (selabel_lookup(sehandle, &tmp_secontext, path.c_str(), S_IFDIR) == 0) { + secontext.reset(tmp_secontext); + if (user_id != (uid_t)-1) { + if (selinux_android_context_with_level(secontext.get(), &tmp_secontext, user_id, + (uid_t)-1) != 0) { + PLOG(ERROR) << "Unable to create context with level for: " << path; + return false; + } + secontext.reset(tmp_secontext); + } + if (setfscreatecon(secontext.get()) != 0) { + LOG(ERROR) << "Failed to setfscreatecon for directory " << path; + return false; + } + } else if (errno == ENOENT) { + LOG(DEBUG) << "No selabel defined for directory " << path; + } else { + PLOG(ERROR) << "Failed to look up selabel for directory " << path; + return false; + } + } + LOG(DEBUG) << "Setting up mode " << std::oct << mode << std::dec << " uid " << uid << " gid " + << gid << " context " << (secontext ? secontext.get() : "null") + << " on path: " << path; + if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) { + return false; + } + if (is_selinux_enabled() && secontext) { + char* tmp_oldsecontext = nullptr; + if (lgetfilecon(path.c_str(), &tmp_oldsecontext) < 0) { + PLOG(ERROR) << "Unable to read secontext for: " << path; + return false; + } + auto oldsecontext = std::unique_ptr(tmp_oldsecontext, freecon); + if (strcmp(secontext.get(), oldsecontext.get()) != 0) { + LOG(INFO) << "Relabelling from " << ((char*)oldsecontext.get()) << " to " + << ((char*)secontext.get()) << ": " << path; + if (lsetfilecon(path.c_str(), secontext.get()) != 0) { + PLOG(ERROR) << "Relabelling failed for: " << path; + return false; + } + } + } + return true; +} + +static bool prepare_dir(struct selabel_handle* sehandle, mode_t mode, uid_t uid, gid_t gid, + const std::string& path) { + return prepare_dir_for_user(sehandle, mode, uid, gid, path, (uid_t)-1); +} + +static bool rmrf_contents(const std::string& path) { + auto dirp = std::unique_ptr(opendir(path.c_str()), closedir); + if (!dirp) { + if (errno == ENOENT) { + return true; + } + PLOG(ERROR) << "Unable to open directory: " << path; + return false; + } + bool res = true; + for (;;) { + errno = 0; + auto const entry = readdir(dirp.get()); + if (!entry) { + if (errno) { + PLOG(ERROR) << "readdir failed on: " << path; + return false; + } + return res; + } + if (entry->d_name[0] == '.') continue; + auto subdir = path + "/" + entry->d_name; + if (0 != + android::vold::ForkExecvp(std::vector{"/system/bin/rm", "-rf", subdir})) { + LOG(ERROR) << "rm -rf failed on " << subdir; + res = false; + } + } +} + +static bool prepare_apex_subdirs(struct selabel_handle* sehandle, const std::string& path) { + if (!prepare_dir(sehandle, 0711, 0, 0, path + "/apexdata")) return false; + + // Since vold/vold_prepare_subdirs run in the bootstrap mount namespace + // we can't get the full list of APEXes by scanning /apex directory. + // Instead, we can look up /data/misc/apexdata for the list of APEXes, + // which is populated during `perform_apex_config` in init. + // Note: `init_user0` should be invoked after `perform_apex_config`. + auto dirp = std::unique_ptr(opendir("/data/misc/apexdata"), closedir); + if (!dirp) { + PLOG(ERROR) << "Unable to open apex directory"; + return false; + } + struct dirent* entry; + while ((entry = readdir(dirp.get())) != nullptr) { + if (entry->d_type != DT_DIR) continue; + + const char* name = entry->d_name; + // skip any starting with "." + if (name[0] == '.') continue; + + if (!prepare_dir(sehandle, 0771, AID_ROOT, AID_SYSTEM, path + "/apexdata/" + name)) { + return false; + } + } + return true; +} + +static bool prepare_subdirs(const std::string& volume_uuid, int user_id, int flags) { + struct selabel_handle* sehandle = selinux_android_file_context_handle(); + if (!sehandle) { + LOG(ERROR) << "Failed to get SELinux file contexts handle"; + return false; + } + + if (flags & android::os::IVold::STORAGE_FLAG_DE) { + auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id); + if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, user_de_path, user_id)) { + return false; + } + + auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id); + if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, + misc_de_path + "/sdksandbox", user_id)) { + return false; + } + + if (volume_uuid.empty()) { + if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/vold")) return false; + if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/storaged")) return false; + if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/rollback")) return false; + // TODO: Return false if this returns false once sure this should succeed. + prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/apexrollback"); + prepare_apex_subdirs(sehandle, misc_de_path); + + auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id); + if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, profiles_de_path, + user_id)) { + return false; + } + + auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id); + if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, vendor_de_path + "/fpdata")) { + return false; + } + auto facedata_path = vendor_de_path + "/facedata"; + if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) { + return false; + } + } + } + if (flags & android::os::IVold::STORAGE_FLAG_CE) { + auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id); + if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, user_ce_path, user_id)) { + return false; + } + + auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id); + if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, + misc_ce_path + "/sdksandbox", user_id)) { + return false; + } + + if (volume_uuid.empty()) { + if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/vold")) return false; + if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/storaged")) return false; + if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/rollback")) return false; + // TODO: Return false if this returns false once sure this should succeed. + prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/apexrollback"); + prepare_apex_subdirs(sehandle, misc_ce_path); + // Give gmscore (who runs in cache group) access to the checkin directory. Also provide + // the user id to set the correct selinux mls_level. + if (!prepare_dir_for_user(sehandle, 0770, AID_SYSTEM, AID_CACHE, + misc_ce_path + "/checkin", user_id)) { + // TODO(b/203742483) the checkin directory was created with the wrong permission & + // context. Delete the directory to get these devices out of the bad state. Revert + // the change once the droidfood population is on newer build. + LOG(INFO) << "Failed to prepare the checkin directory, deleting for recreation"; + android::vold::DeleteDirContentsAndDir(misc_ce_path + "/checkin"); + if (!prepare_dir_for_user(sehandle, 0770, AID_SYSTEM, AID_CACHE, + misc_ce_path + "/checkin", user_id)) { + return false; + } + } + + auto system_ce_path = android::vold::BuildDataSystemCePath(user_id); + if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, system_ce_path + "/backup")) { + return false; + } + if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, + system_ce_path + "/backup_stage")) { + return false; + } + auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id); + auto facedata_path = vendor_ce_path + "/facedata"; + if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) { + return false; + } + } + } + return true; +} + +static bool destroy_subdirs(const std::string& volume_uuid, int user_id, int flags) { + bool res = true; + if (flags & android::os::IVold::STORAGE_FLAG_CE) { + auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id); + res &= rmrf_contents(misc_ce_path); + + if (volume_uuid.empty()) { + auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id); + res &= rmrf_contents(vendor_ce_path); + } + } + if (flags & android::os::IVold::STORAGE_FLAG_DE) { + auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id); + res &= rmrf_contents(misc_de_path); + + if (volume_uuid.empty()) { + auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id); + res &= rmrf_contents(vendor_de_path); + } + } + return res; +} + +int main(int argc, const char* const argv[]) { + android::base::InitLogging(const_cast(argv)); + std::vector args(argv + 1, argv + argc); + + if (args.size() != 4 || !valid_uuid(args[1]) || !small_int(args[2]) || !small_int(args[3])) { + usage(argv[0]); + return -1; + } + + auto volume_uuid = args[1]; + int user_id = stoi(args[2]); + int flags = stoi(args[3]); + if (args[0] == "prepare") { + if (!prepare_subdirs(volume_uuid, user_id, flags)) return -1; + } else if (args[0] == "destroy") { + if (!destroy_subdirs(volume_uuid, user_id, flags)) return -1; + } else { + usage(argv[0]); + return -1; + } + return 0; +}