github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/socket_capability.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Subset of socket tests that need Linux-specific headers (compared to POSIX
    16  // headers).
    17  
    18  #include "gtest/gtest.h"
    19  #include "test/syscalls/linux/socket_test_util.h"
    20  #include "test/util/capability_util.h"
    21  #include "test/util/file_descriptor.h"
    22  #include "test/util/test_util.h"
    23  
    24  namespace gvisor {
    25  namespace testing {
    26  
    27  TEST(SocketTest, UnixConnectNeedsWritePerm) {
    28    SKIP_IF(IsRunningWithVFS1());
    29  
    30    FileDescriptor bound =
    31        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));
    32  
    33    struct sockaddr_un addr =
    34        ASSERT_NO_ERRNO_AND_VALUE(UniqueUnixAddr(/*abstract=*/false, AF_UNIX));
    35    ASSERT_THAT(bind(bound.get(), reinterpret_cast<struct sockaddr*>(&addr),
    36                     sizeof(addr)),
    37                SyscallSucceeds());
    38    ASSERT_THAT(listen(bound.get(), 1), SyscallSucceeds());
    39  
    40    // Drop capabilites that allow us to override permision checks. Otherwise if
    41    // the test is run as root, the connect below will bypass permission checks
    42    // and succeed unexpectedly.
    43    AutoCapability cap(CAP_DAC_OVERRIDE, false);
    44  
    45    // Connect should fail without write perms.
    46    ASSERT_THAT(chmod(addr.sun_path, 0500), SyscallSucceeds());
    47    FileDescriptor client =
    48        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));
    49    ASSERT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),
    50                        sizeof(addr)),
    51                SyscallFailsWithErrno(EACCES));
    52  
    53    // Connect should succeed with write perms.
    54    ASSERT_THAT(chmod(addr.sun_path, 0200), SyscallSucceeds());
    55    EXPECT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),
    56                        sizeof(addr)),
    57                SyscallSucceeds());
    58  }
    59  
    60  }  // namespace testing
    61  }  // namespace gvisor