blob: 3996d90b8bc173e183855d7f8d077d8360508696 [file] [log] [blame]
Elliott Hughesc2efd4d2018-10-25 13:14:55 -07001/*
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
David Sehr10db8fe2018-07-18 11:01:20 -070019#if !defined(_WIN32)
Elliott Hughesc2efd4d2018-10-25 13:14:55 -070020#include <pwd.h>
21#include <sys/socket.h>
David Sehr10db8fe2018-07-18 11:01:20 -070022#endif
Elliott Hughesc2efd4d2018-10-25 13:14:55 -070023
24#include <android-base/logging.h>
25
26namespace art {
27
28// Returns true if the user on the other end of the socket is root or shell.
29#ifdef ART_TARGET_ANDROID
30bool 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
47bool SocketPeerIsTrusted(int /* fd */) {
48 return true;
49}
50#endif
51
52} // namespace art