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_FILTERING_H_ 16 #define SANDBOXED_API_SANDBOX2_NETWORK_PROXY_FILTERING_H_ 17 18 #include <netinet/in.h> 19 20 #include <cstdint> 21 #include <string> 22 #include <vector> 23 24 #include "absl/status/status.h" 25 #include "absl/status/statusor.h" 26 #include "sandboxed_api/sandbox2/comms.h" 27 28 namespace sandbox2 { 29 30 // Converts sockaddr_in or sockaddr_in6 structure into a string 31 // representation. 32 absl::StatusOr<std::string> AddrToString(const struct sockaddr* saddr); 33 34 struct IPv4 { 35 in_addr_t ip; 36 in_addr_t mask; 37 uint32_t port; IPv4IPv438 IPv4(in_addr_t IP, in_addr_t mask, uint32_t port) 39 : ip(IP), mask(mask), port(port) {} 40 }; 41 42 struct IPv6 { 43 in6_addr ip; 44 in6_addr mask; 45 uint32_t port; IPv6IPv646 IPv6(in6_addr IP, in6_addr mask, uint32_t port) 47 : ip(IP), mask(mask), port(port) {} 48 }; 49 50 // Keeps a list of allowed pairs of IP, mask and port. Port equal to 0 means 51 // that all ports are allowed. 52 class AllowedHosts { 53 public: 54 // ip_and_mask should have one of following formats: IP, IP/mask, IP/cidr. 55 absl::Status AllowIPv4(const std::string& ip_and_mask, uint32_t port = 0); 56 // ip_and_mask should have following format: IP or IP/cidr. 57 absl::Status AllowIPv6(const std::string& ip_and_mask, uint32_t port = 0); 58 // Checks if this host is allowed. 59 bool IsHostAllowed(const struct sockaddr* saddr) const; 60 61 private: 62 absl::Status AllowIPv4(const std::string& ip, const std::string& mask, 63 uint32_t cidr, uint32_t port); 64 absl::Status AllowIPv6(const std::string& ip, uint32_t cidr, uint32_t port); 65 bool IsIPv4Allowed(const struct sockaddr_in* saddr) const; 66 bool IsIPv6Allowed(const struct sockaddr_in6* saddr) const; 67 68 std::vector<IPv4> allowed_IPv4_; 69 std::vector<IPv6> allowed_IPv6_; 70 }; 71 72 } // namespace sandbox2 73 74 #endif // SANDBOXED_API_SANDBOX2_NETWORK_PROXY_FILTERING_H_ 75