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 
17 #include "socket_peer_is_trusted.h"
18 
19 #if !defined(_WIN32)
20 #include <pwd.h>
21 #include <sys/socket.h>
22 #endif
23 
24 #include <android-base/logging.h>
25 
26 namespace art {
27 
28 // Returns true if the user on the other end of the socket is root or shell.
29 #ifdef ART_TARGET_ANDROID
30 bool SocketPeerIsTrusted(int fd) {
31   ucred cr;
32   socklen_t cr_length = sizeof(cr);
33   if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_length) != 0) {
34     PLOG(ERROR) << "couldn't get socket credentials";
35     return false;
36   }
37 
38   passwd* shell = getpwnam("shell");
39   if (cr.uid != 0 && cr.uid != shell->pw_uid) {
40     LOG(ERROR) << "untrusted uid " << cr.uid << " on other end of socket";
41     return false;
42   }
43 
44   return true;
45 }
46 #else
47 bool SocketPeerIsTrusted(int /* fd */) {
48   return true;
49 }
50 #endif
51 
52 }  // namespace art
53