1 // Copyright 2019 Google LLC 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 // https://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 #ifndef SANDBOXED_API_SANDBOX2_NETWORK_PROXY_CLIENT_H_ 16 #define SANDBOXED_API_SANDBOX2_NETWORK_PROXY_CLIENT_H_ 17 18 #include <sys/socket.h> 19 20 #include <cstdint> 21 22 #include "absl/base/thread_annotations.h" 23 #include "absl/status/status.h" 24 #include "absl/status/statusor.h" 25 #include "absl/synchronization/mutex.h" 26 #include "sandboxed_api/sandbox2/comms.h" 27 #include "sandboxed_api/sandbox2/util/syscall_trap.h" 28 #include "sandboxed_api/util/fileops.h" 29 30 namespace sandbox2 { 31 32 class NetworkProxyClient { 33 public: 34 static constexpr char kFDName[] = "sb2_networkproxy"; 35 NetworkProxyClient(int fd)36 explicit NetworkProxyClient(int fd) : comms_(fd) {} 37 38 NetworkProxyClient(const NetworkProxyClient&) = delete; 39 NetworkProxyClient& operator=(const NetworkProxyClient&) = delete; 40 41 // Establishes a new network connection with semantics similar to a regular 42 // connect() call. Arguments are sent to network proxy server, which sends 43 // back a connected socket. 44 absl::Status Connect(int sockfd, const struct sockaddr* addr, 45 socklen_t addrlen); 46 47 private: 48 absl::StatusOr<sapi::file_util::fileops::FDCloser> ConnectInternal( 49 const struct sockaddr* addr, socklen_t addrlen); 50 51 // Needed to make the Proxy thread safe. 52 absl::Mutex mutex_; 53 Comms comms_ ABSL_GUARDED_BY(mutex_); 54 }; 55 56 class NetworkProxyHandler { 57 public: 58 // Installs the handler that redirects connect() syscalls to the trap 59 // function. This function exchanges data with NetworkProxyServer that checks 60 // if this connection is allowed and sends the connected socket to us. 61 static absl::Status InstallNetworkProxyHandler(NetworkProxyClient* npc); 62 63 static bool ProcessSeccompTrap(int nr, SyscallTrap::Args args, uintptr_t* rv); 64 65 static NetworkProxyClient* network_proxy_client_; 66 }; 67 68 } // namespace sandbox2 69 70 #endif // SANDBOXED_API_SANDBOX2_NETWORK_PROXY_CLIENT_H_ 71