android IPC通訊中的UID和PID識別

來源:互聯網
上載者:User

 

 

IPCThreadState對象維護了2個變數

 

            pid_t               mCallingPid;

 

            uid_t               mCallingUid;

 

    從變數名稱來看,這2個變數儲存了進程的PID和UID,並且由於這兩個變數由IPCThreadState對象維護,可見它們是與IPC相關的。具體它們儲存的是IPC發送方的PID和UID還是當前進程的IPD和UID,視情況而定。

 

    在IPC調用過程中,被呼叫者需要知道調用方的UID和PID,以便被呼叫者用於許可權檢測;所以需要一種方式來提供調用方的UID和PID,因此上述2個變數的主要作用就是用於許可權檢測。

 

    那麼我們想象一下,下面描述的情況下,mCallingPid和mCallingUid又應該儲存誰的UID和PID?假如有2個進程process A和process B,我們站在process B的角度來分析,process A IPC調用process B, 而process B 又調用同樣處於process B的Service的介面(儘管此時實際上不是遠程調用,並且開發人員是知道的,但是對於Binder調用機制來說,它本身並不知道當前的調用是否為遠程調用,前幾篇文章中有分析系統如何確定是否為遠程調用,這個過程是在binder driver中實現的),那麼此時mCallingPid和mCallingUid是不是應該儲存process B的UID和PID?

 

1.       process B在被process A IPC調用時, process B需知道process A的UID和PID,來檢查process A的存取權限,此時mCallingUid和mCallingPid儲存的是process A的UID和PID。

 

2.       在IPC遠程調用process B的過程中,process B的方法調用了同進程中的service的介面,process B既是調用方也是被呼叫者,雖然這個過程比較無聊,但是鑒於IPC過程的不透明性,因此process B仍然需要進行許可權檢測。

 

 

    前面的文章中分析過,binder driver會判斷當前的Binder調用是否為遠程調用,如果是同進程調用的話,BD就不會再嚮應用提供進程的PID和UID。因此在process B中需要顯示的設定當前的PID和UID。

 

    為實現以上case,android提供了一組函數

 

    public static final native long clearCallingIdentity();

 

    public static final native void restoreCallingIdentity(long token);

 

    process B的方法調用了同進程中的service的介面前,clearCallingIdentity()方法會清除process A的UID和PID,重設為process B的UID和PID。

 

    process B的方法調用了同進程中的service的介面後,此時仍然處在process A遠程調用process B方法的過程中,此時需要restore  process A的UID和PID。

 

    本文描述的case,雖然在application 開發中並不常見,但是在system_server中很常見,比如client調用ActivityManagerService的方法,而ActivityManagerService又調用了PackageManagerService的方法,並且ActivityManagerService和PackageManagerService均會運行在system_server進程中。

 

摘自 杜文濤的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.