1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.seccomp.cts.app;
17 
18 import android.app.Service;
19 import android.content.Intent;
20 import android.os.Handler;
21 import android.os.IBinder;
22 import android.os.Message;
23 import android.os.Messenger;
24 import android.os.Process;
25 import android.os.RemoteException;
26 import android.util.Log;
27 
28 public class IsolatedService extends Service {
29     static final String TAG = "IsolatedService";
30 
31     static final int MSG_GET_SECCOMP_RESULT = 1;
32 
33     static final int MSG_SECCOMP_RESULT = 2;
34     final Messenger mMessenger = new Messenger(new ServiceHandler());
35 
36     @Override
onBind(Intent intent)37     public IBinder onBind(Intent intent) {
38         return mMessenger.getBinder();
39     }
40 
41     static class ServiceHandler extends Handler {
42         @Override
handleMessage(Message msg)43         public void handleMessage(Message msg) {
44             switch (msg.what) {
45                 case (MSG_GET_SECCOMP_RESULT):
46                     int result = ZygotePreload.getSeccomptestResult() ? 1 : 0;
47                     if (result != 0) {
48                         // Verify that my UID falls within the verified isolated range
49                         int rangeBegin = ZygotePreload.getStartOfIsolatedRange();
50                         int rangeEnd = ZygotePreload.getStartOfIsolatedRange()
51                             + Process.NUM_UIDS_PER_APP_ZYGOTE - 1;
52                         if (Process.myUid() < rangeBegin || Process.myUid() > rangeEnd) {
53                             Log.e(TAG, "Isolated UID " + Process.myUid()
54                                     + " doesn't match allowed isolated range of app zygote: ["
55                                     + rangeBegin + "," + rangeEnd + "]");
56                             result = 0;
57                         }
58                     }
59                     try {
60                         msg.replyTo.send(Message.obtain(null, MSG_SECCOMP_RESULT, result, 0));
61                     } catch (RemoteException e) {
62                         Log.e(TAG, "Failed to send seccomp test result", e);
63                     }
64                     break;
65                 default:
66                     super.handleMessage(msg);
67             }
68         }
69     }
70 }
71