How to run an Android init service with superuser SELinux context?


Question

I want to run an Android init service. I have a device which has rooted shell (purchased from manufacture as rooted). This device doesn't have Magisk or other su manager but adb shell is rooted and it has userdebug ROM installed on it.



I have followed following steps to set up init service:




  1. Created /etc/init/custom.rc file with following contents:



#/etc/init/custom.rc

# define service, use executable here if script not needed
service custom /system/bin/custom.sh

# don't start unless explicitly asked to
disabled

# run with unrestricted SELinux context to avoid avc denials
# can also use "u:r:su:s0" on userdebug / eng builds if no Magisk
# it's required if SELinux is enforcing and service needs access
# to some system resources not allowed by default sepolicy
# seclabel u:r:magisk:s0
seclabel u:r:su:s0

# start the service when boot is completed
on property:sys.boot_completed=1
start custom



  1. Created /system/bin/custom.sh with following contents:



#!/system/bin/sh

# execute the binary, should run in foreground, otherwise get in loop
echo "$(date): Starting program..."
exec /system/bin/executable



  1. Placed my executable at /system/bin/executable.

  2. Gave permissions to all files as following:



# Give rights to the executable
chown 0.0 /system/bin/executable
chmod 554 /system/bin/executable
chcon u:object_r:system_file:s0 /system/bin/executable

# Give rights to the custom.sh
chown 0.0 /system/bin/custom.sh
chmod 554 /system/bin/custom.sh
chcon u:object_r:system_file:s0 /system/bin/custom.sh

# Give rights to the custom.rc
chown 0.0 /etc/init/custom.rc
chmod 644 /etc/init/custom.rc
chcon u:object_r:system_file:s0 /etc/init/custom.rc



  1. Reboot the system.



I got following error:



[
55.829099 / 06-09 23:51:09.279][0] init: cannot execve('/system/bin/custom.sh'): Permission denied
[ 55.850172 / 06-09 23:51:09.309][6] init: Service 'custom' (pid 7729)
[ 55.850224 / 06-09 23:51:09.309][6] init: Service 'custom' (pid 7729) exited with status 127
[ 55.850243 / 06-09 23:51:09.309][6] init: Sending signal 9 to service 'custom' (pid 7729) process group...
[ 60.830224 / 06-09 23:51:14.289][6] init: starting service 'custom'...
[ 60.832073 / 06-09 23:51:14.289][1] init: cannot execve('/system/bin/custom.sh'): Permission denied
[ 60.832153 / 06-09 23:51:14.289][3] audit: type=1400 audit(1560142274.289:131): avc: denied { transition } for pid=8035 comm="init" path="/system/bin/custom.sh" dev="sda24" ino=8146 scontext=u:r:init:s0 tcontext=u:r:su:s0 tclass=process permissive=0


I have very little experience with SELinux Policies. Please guide me how can I fix this.


Answer

Here the error is:



audit: type=1400 audit(1560142274.289:131): avc: denied {
 transition 
}
 for pid=8035 comm="init" path="/system/bin/custom.sh" dev="sda24" ino=8146 scontext=u:r:init:s0 tcontext=u:r:su:s0 tclass=process permissive=0


In easy words it states that init is running with its context u:r:init:0, you want it to execute /system/bin/custom.sh with context u:r:su:s0, but it's not allowed in sepolicy.



Rooting a phone gets two things: UID 0 (which you have) and an unrestricted SELinux context (which you don't have). Magisk allows any other context to do anything with its own contexts (u:r:magisk:s0 and u:object_r:magisk:s0). And it can do anything to any other context. See details in this answer.



u:r:su:s0 is a limited context which doesn't allow init to make transition to itself. Only adb can do this on userdebug or eng builds of a ROM. See reference and this answer for details.



Possible solutions:




  • Run service in init's context if it doesn't need to access any resources which init isn't allowed to access. But in most cases it's highly unlikely.

  • Root your device with Magisk and run service with u:r:magisk:s0 context as explained in this answer.

  • Modify your SELinux policy to allow this transition. Inject the following statement to sepolicy using magiskpolicy or sepolicy-inject:



    ~# magiskpolicy --live 'allow init su process transition'
    ~# sepolicy-inject -s init -t su -c process -p transition -l


    Also see dmesg for any other denials. As a reference, on my device init is allowed to do following operations to Magisk:



    allow init magisk : process {
     fork transition sigchld sigkill sigstop signull signal ptrace getsched setsched getsession getpgid setpgid getcap setcap share getattr setexec setfscreate noatsecure siginh setrlimit rlimitinh dyntransition setcurrent execmem execstack execheap setkeycreate setsockcreate getrlimit 
    }
    
    allow init magisk : fifo_file { read write getattr open }
    allow init magisk : fd use
    allow init magisk : unix_stream_socket { getopt connectto }
    allow init magisk : binder { impersonate call set_context_mgr transfer }


    Then extract boot.img and ramdisk (only on non-system-as-root devices), replace /sepolicy with new policy file copied from /sys/fs/selinux/policy, repack boot.img and flash back.


  • Set SELinux permissive



    From root adb shell do echo -n 0 >/sys/fs/selinux/enforce or setenforce 0. However this is not permanent and will be set to enforced on boot. init can't set it permissive. Also setting SELinux permissive is a security risk and hence never recommended.



Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes