android 9.0user版本如何开启root,打开su

在默认情况下,adbd是以uid root的权限启动的。不过它确实还会通过函数drop_privileges()主动把自己降到uid shell : shell,如下:

# /system/core/adb/daemon/main.cpp

static void drop_privileges(int server_port) {
    ScopedMinijail jail(minijail_new());

    // Add extra groups:
    // AID_ADB to access the USB driver
    // AID_LOG to read system logs (adb logcat)
    // AID_INPUT to diagnose input issues (getevent)
    // AID_INET to diagnose network issues (ping)
    // AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
    // AID_SDCARD_R to allow reading from the SD card
    // AID_SDCARD_RW to allow writing to the SD card
    // AID_NET_BW_STATS to read out qtaguid statistics
    // AID_READPROC for reading /proc entries across UID boundaries
    // AID_UHID for using 'hid' command to read/write to /dev/uhid
    gid_t groups[] = {AID_ADB,          AID_LOG,          AID_INPUT,    AID_INET,
                      AID_NET_BT,       AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
                      AID_NET_BW_STATS, AID_READPROC,     AID_UHID};
    minijail_set_supplementary_gids(jail.get(), arraysize(groups), groups);

    // Don't listen on a port (default 5037) if running in secure mode.
    // Don't run as root if running in secure mode.
    if (should_drop_privileges()) {
        const bool should_drop_caps = should_drop_capabilities_bounding_set();

        if (should_drop_caps) {
            minijail_use_caps(jail.get(), CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_SETGID));
        }

        minijail_change_gid(jail.get(), AID_SHELL);
        minijail_change_uid(jail.get(), AID_SHELL);
        // minijail_enter() will abort if any priv-dropping step fails.
        minijail_enter(jail.get());
        ...
}        

再看下should_drop_privileges()方法,这个函数来判断是否要降级,返回false就是使用root权限

# /system/core/adb/daemon/main.cpp

static bool should_drop_privileges() {
#if defined(ALLOW_ADBD_ROOT)
    // The properties that affect `adb root` and `adb unroot` are ro.secure and
    // ro.debuggable. In this context the names don't make the expected behavior
    // particularly obvious.
    //
    // ro.debuggable:
    //   Allowed to become root, but not necessarily the default. Set to 1 on
    //   eng and userdebug builds.
    //
    // ro.secure:
    //   Drop privileges by default. Set to 1 on userdebug and user builds.
    bool ro_secure = android::base::GetBoolProperty("ro.secure", true);
    bool ro_debuggable = __android_log_is_debuggable();
     // Drop privileges if ro.secure is set...
    bool drop = ro_secure;

    // ... except "adb root" lets you keep privileges in a debuggable build.
    std::string prop = android::base::GetProperty("service.adb.root", "");
    bool adb_root = (prop == "1");
    bool adb_unroot = (prop == "0");
    if (ro_debuggable && adb_root) {
        drop = false;
    }
    // ... and "adb unroot" lets you explicitly drop privileges.
    if (adb_unroot) {
        drop = true;
    }

    return drop;
#else
    return true; // "adb root" not allowed, always drop privileges.
#endif // ALLOW_ADBD_ROOT
}
1.开启adbd的root的权限

第一种方式
①.修改 /system/core/adb/daemon/main.cpp

static bool should_drop_privileges() {
  // 注释方法内代码,添加如下代码
  std::string prop = android::base::GetProperty("service.adb.root", "");
  if (prop == "1"){
 	  return false;
  }
  return true;
}

第二种方式
①修改 /build/core/main.mk

## user/userdebug ##

user_variant := $(filter user userdebug,$(TARGET_BUILD_VARIANT))
enable_target_debugging := true
tags_to_install :=
ifneq (,$(user_variant))
  # Target is secure in user builds.
  ADDITIONAL_DEFAULT_PROPERTIES += ro.secure=1
  ADDITIONAL_DEFAULT_PROPERTIES += security.perf_harden=1
    ...
将·ro.secure=1 修改为ro.secure=0

②修改 /system/core/adb/Android.mk

- ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
+ ifneq (,$(filter user userdebug eng,$(TARGET_BUILD_VARIANT)))
  LOCAL_CFLAGS += -DALLOW_ADBD_DISABLE_VERITY=1
  LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1
  endif
2.添加su

①去掉root,shell的判断

# /system/extras/su/su.cpp

int main(int argc, char** argv) {
+    #if 0
     uid_t current_uid = getuid();
     if (current_uid != AID_ROOT && current_uid != AID_SHELL) error(1, 0, "not allowed");
+    #endif
     // Handle -h and --help.

②修改su权限

# /system/core/rootdir/init.rc

+    chmod 6755 /system/xbin/su
+ 
     # Assume SMP uses shared cpufreq policy for all CPUs
     
# /system/core/libcutils/fs_config.cpp 

-    { 04750, AID_ROOT,      AID_SHELL,     0, "system/xbin/su" },
+    { 06755, AID_ROOT,      AID_SHELL,     0, "system/xbin/su" },

③修改su模块在所有模式下都编译

# /system/extras/su/Android.mk

- LOCAL_MODULE_TAGS := debug
+ LOCAL_MODULE_TAGS := optional

④修改 /frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

 static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
+  #if 0
   for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
    int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
    if (rc == -1) {
      if (errno == EINVAL) {
        ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
              "your kernel is compiled with file capabilities support");
      } else {
        *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
        return false;
      }
    }
  }
+ #endif
   return true;
 }

⑤在device.mk下添加su模块

# /device/mediatek/common/device.mk

PRODUCT_PACKAGES += su
3.关闭selinux

① Android 8.1

  # /system/core/init/init.cpp
 static bool selinux_is_enforcing(void){   
    return false; //add to close selinux
    if (ALLOW_PERMISSIVE_SELINUX) {
        return selinux_status_from_cmdline() == SELINUX_ENFORCING;
    }
    return true;
 }

② Android 9.0

  # /system/core/init/selinux.cpp
 bool IsEnforcing() {
 	return false; //add to close selinux
  	if (ALLOW_PERMISSIVE_SELINUX) {
    	return StatusFromCmdline() == SELINUX_ENFORCING;
   	}
  	return true;
 }

最后,app验证su功能

private boolean silentInstall(File apkPath){
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
             while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
           
            if (!msg.contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            LogUtil.e(" "+ e.getMessage());
        } finally {
        	try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                LogUtil.d("  "+e.getMessage());
            }
        }
        return result;
    }
  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Android 9.0 及以上版本,为了进一步增强应用程序的安全性,Android 引入了更严格的后台限制,禁止所有未在前台运行的应用程序启动服务。如果您想在后台启动服务,需要使用 `startForegroundService()` 方法,并且需要在 5 秒钟内调用 `startForeground()` 方法将服务设置为前台服务。 以下是一个使用 `startForegroundService()` 和 `startForeground()` 的示例代码: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 创建一个 NotificationChannel NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT); // 向系统注册 NotificationChannel NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); } // 创建一个 Intent,启动你的服务 Intent serviceIntent = new Intent(this, YourService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 在 Android 9.0 及以上版本上,需要调用 startForegroundService() 方法启动服务。 startForegroundService(serviceIntent); // 在启动服务后,5 秒钟内调用 startForeground() 方法将服务设置为前台服务。 // 如果在 5 秒钟内没有调用 startForeground() 方法,系统会认为服务无法正常启动,会抛出异常。 new Handler().postDelayed(new Runnable() { @Override public void run() { startForeground(1, new Notification()); } }, 5000); } else { // 在 Android 9.0 以下版本上,可以直接调用 startService() 方法启动服务。 startService(serviceIntent); } ``` 注意:在 Android 9.0 及以上版本上,如果你使用的是 `startForeground()` 方法,会在 5 秒钟后抛出 `ANR` 异常,因为 Android 9.0 及以上版本要求服务必须在 5 秒钟内设置为前台服务。如果你想在后台运行服务,必须使用 `startForegroundService()` 和 `startForeground()` 方法。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值