Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

教你在 Android 源碼中製作自己的 su

編輯:關於 Android 程式設計

本文原博客:https://hubingforever.blog.163.com/blog/static/171040579201372915716149/

在 Android 源碼的 system/extras(例如 Android4.0 的 system/extras)下新建一個目錄,比如 su_robin。該目錄下需包含三個檔案。

su.h 檔案

定義版本資訊、請求者路徑、intent action、協定版本,以及 su_initiator、su_request、su_context 等結構與資料庫狀態列舉(其內容可按需精簡):

#ifndef SU_h
#define SU_h 1
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "robin"
#define REQUESTOR "com.noshufou.android.su"
#define REQUESTOR_DATA_PATH "/data/data/" REQUESTOR
#define DEFAULT_SHELL "/system/bin/sh"
#define VERSION "3.1.1"
#define VERSION_CODE 17
#define DATABASE_VERSION 6
#define PROTO_VERSION 0
struct su_initiator {
    pid_t pid;
    unsigned uid;
    char bin[PATH_MAX];
    char args[4096];
};
struct su_request {
    unsigned uid;
    int login;
    int keepenv;
    char *shell;
    char *command;
    char **argv;
    int argc;
    int optind;
};
struct su_context {
    struct su_initiator from;
    struct su_request to;
    mode_t umask;
};
enum { DB_INTERACTIVE, DB_DENY, DB_ALLOW };
#endif

su.c 檔案

這裡示範的是一個精簡版:取得 root 後直接切換到 shell:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include "su.h"
int main(int argc, char *argv[]){
    int uid = 0;
    int gid = 0;
    if(setgid(gid) || setuid(uid)) {
        fprintf(stderr, "su: permission denied\n");
        return 1;
    }
    /* 預設執行 shell */
    execlp("/system/bin/sh", "sh", NULL);
    fprintf(stderr, "su: exec failed\n");
    return 1;
}

Android.mk 檔案

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := sur
LOCAL_SRC_FILES := su.c
LOCAL_STATIC_LIBRARIES := \
    liblog \
    libc
LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
LOCAL_MODULE_TAGS := eng debug
LOCAL_FORCE_STATIC_EXECUTABLE := true
include $(BUILD_EXECUTABLE)

編譯 Android 源碼生成 rom(若還不熟悉如何編譯,請參照 https://source.android.com/source/building-running.html)。完成後可在 out/target/product/generic/system/xbin 目錄下找到生成的可執行檔 sur,這就是我們自己製作的 su。

接著用 adb push 把它推到手機的 system/xbin 目錄,先透過系統原帶的 su 切換到 root 用戶,再對 sur 執行 chmod 6777 sur,使屬性變為 rwsrwsrwx(如下所示):

rwsrwsrwx root root 58960 2013-08-29 11:31 sur

之後就能透過執行 sur 切換到 root 用戶了。關於 chmod 6777 與 setuid 的更多說明,可參考相關的 chmod 與 setuid()/setgid() 文章。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved