gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/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/util/capability_util.h"
    20  #include "test/util/file_descriptor.h"
    21  #include "test/util/socket_util.h"
    22  #include "test/util/test_util.h"
    23  
    24  namespace gvisor {
    25  namespace testing {
    26  
    27  TEST(SocketTest, UnixConnectNeedsWritePerm) {
    28    FileDescriptor bound =
    29        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));
    30  
    31    struct sockaddr_un addr =
    32        ASSERT_NO_ERRNO_AND_VALUE(UniqueUnixAddr(/*abstract=*/false, AF_UNIX));
    33    ASSERT_THAT(bind(bound.get(), reinterpret_cast<struct sockaddr*>(&addr),
    34                     sizeof(addr)),
    35                SyscallSucceeds());
    36    ASSERT_THAT(listen(bound.get(), 1), SyscallSucceeds());
    37  
    38    // Drop capabilites that allow us to override permision checks. Otherwise if
    39    // the test is run as root, the connect below will bypass permission checks
    40    // and succeed unexpectedly.
    41    AutoCapability cap(CAP_DAC_OVERRIDE, false);
    42  
    43    // Connect should fail without write perms.
    44    ASSERT_THAT(chmod(addr.sun_path, 0500), SyscallSucceeds());
    45    FileDescriptor client =
    46        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));
    47    ASSERT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),
    48                        sizeof(addr)),
    49                SyscallFailsWithErrno(EACCES));
    50  
    51    // Connect should succeed with write perms.
    52    ASSERT_THAT(chmod(addr.sun_path, 0200), SyscallSucceeds());
    53    EXPECT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),
    54                        sizeof(addr)),
    55                SyscallSucceeds());
    56  }
    57  
    58  }  // namespace testing
    59  }  // namespace gvisor