| 1 | """Bounded guest probes. Output contains observations, never file contents.""" |
| 2 | import base64 |
| 3 | import ipaddress |
| 4 | import json |
| 5 | import locale |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import socket |
| 9 | import subprocess |
| 10 | import sys |
| 11 | import time |
| 12 | import urllib.error |
| 13 | import urllib.request |
| 14 | |
| 15 | args = json.loads(base64.b64decode(sys.argv[1])) |
| 16 | result = {} |
| 17 | |
| 18 | |
| 19 | def connected(address, family=socket.AF_INET): |
| 20 | try: |
| 21 | connection = socket.socket(family, socket.SOCK_STREAM) |
| 22 | except OSError: |
| 23 | return False |
| 24 | connection.settimeout(1.5) |
| 25 | try: |
| 26 | connection.connect(address) |
| 27 | return True |
| 28 | except OSError: |
| 29 | return False |
| 30 | finally: |
| 31 | connection.close() |
| 32 | |
| 33 | |
| 34 | def udp_attempted(address, payload): |
| 35 | |
| 36 | |
| 37 | udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 38 | try: |
| 39 | udp.sendto(payload, address) |
| 40 | return True |
| 41 | except OSError: |
| 42 | return False |
| 43 | finally: |
| 44 | udp.close() |
| 45 | |
| 46 | |
| 47 | def ip_json(*arguments): |
| 48 | output = subprocess.run(["ip", "-j", *arguments], capture_output=True, text=True, timeout=3, check=True) |
| 49 | return json.loads(output.stdout) |
| 50 | |
| 51 | |
| 52 | def resolver_observation(management_host): |
| 53 | |
| 54 | |
| 55 | |
| 56 | servers = set() |
| 57 | readable = 0 |
| 58 | for name in ("/etc/resolv.conf", "/run/systemd/resolve/resolv.conf"): |
| 59 | try: |
| 60 | text = Path(name).read_text() |
| 61 | except OSError: |
| 62 | continue |
| 63 | readable += 1 |
| 64 | for line in text.splitlines(): |
| 65 | fields = line.split() |
| 66 | if len(fields) >= 2 and fields[0] == "nameserver": |
| 67 | servers.add(fields[1].split("%")[0]) |
| 68 | if not readable: |
| 69 | return {"count": -1, "confined": False} |
| 70 | allowed = [ipaddress.ip_network("198.18.0.0/15")] |
| 71 | try: |
| 72 | allowed.append(ipaddress.ip_network(management_host + "/24", strict=False)) |
| 73 | except ValueError: |
| 74 | pass |
| 75 | confined = bool(servers) |
| 76 | for server in servers: |
| 77 | try: |
| 78 | address = ipaddress.ip_address(server) |
| 79 | except ValueError: |
| 80 | confined = False |
| 81 | continue |
| 82 | if not address.is_loopback and not any(address in network for network in allowed): |
| 83 | confined = False |
| 84 | return {"count": len(servers), "confined": confined} |
| 85 | |
| 86 | |
| 87 | def probe(path): |
| 88 | |
| 89 | opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) |
| 90 | request = urllib.request.Request("http://198.18.0.254" + path) |
| 91 | try: |
| 92 | with opener.open(request, timeout=16) as response: |
| 93 | return {"status": response.status, **json.loads(response.read(4096))} |
| 94 | except urllib.error.HTTPError as error: |
| 95 | return {"status": error.code} |
| 96 | except (OSError, ValueError): |
| 97 | return {"status": 0} |
| 98 | |
| 99 | |
| 100 | def timezone_observation(expected): |
| 101 | now = time.time() |
| 102 | observation = {"localtime_target": "", "utc_offset_actual": time.localtime(now).tm_gmtoff} |
| 103 | try: |
| 104 | observation["localtime_target"] = os.readlink("/etc/localtime") |
| 105 | except OSError: |
| 106 | pass |
| 107 | try: |
| 108 | from datetime import datetime, timezone |
| 109 | from zoneinfo import ZoneInfo |
| 110 | instant = datetime.fromtimestamp(now, timezone.utc) |
| 111 | |
| 112 | with open("/etc/localtime", "rb") as localtime: |
| 113 | system_zone = ZoneInfo.from_file(localtime) |
| 114 | observation["utc_offset_system"] = int(instant.astimezone(system_zone).utcoffset().total_seconds()) |
| 115 | except (OSError, ValueError, ImportError): |
| 116 | pass |
| 117 | if expected: |
| 118 | try: |
| 119 | offset = instant.astimezone(ZoneInfo(expected)).utcoffset() |
| 120 | observation["utc_offset_expected"] = int(offset.total_seconds()) |
| 121 | except Exception: |
| 122 | pass |
| 123 | return observation |
| 124 | |
| 125 | |
| 126 | if args["stage"] in ("boundary", "environment"): |
| 127 | result.update(tz=os.environ.get("TZ", ""), lang=os.environ.get("LANG", ""), lc_all=os.environ.get("LC_ALL", "")) |
| 128 | try: |
| 129 | result["system_timezone"] = Path("/etc/timezone").read_text().strip() |
| 130 | locale.setlocale(locale.LC_ALL, "") |
| 131 | result["locale_valid"] = True |
| 132 | except (OSError, locale.Error): |
| 133 | result["locale_valid"] = False |
| 134 | result.update(timezone_observation(args.get("timezone", ""))) |
| 135 | |
| 136 | if args["stage"] == "boundary": |
| 137 | result["public_connected"] = connected(("1.1.1.1", 443)) |
| 138 | result["management_connected"] = connected((args["management_host"], args["control_port"])) |
| 139 | result["link_local_connected"] = connected(("169.254.169.254", 80)) |
| 140 | if args.get("proxy_host") and args.get("proxy_port"): |
| 141 | family = socket.AF_INET6 if ":" in args["proxy_host"] else socket.AF_INET |
| 142 | result["proxy_endpoint_connected"] = connected((args["proxy_host"], int(args["proxy_port"])), family) |
| 143 | result["ipv6_connected"] = connected(("2606:4700:4700::1111", 443), socket.AF_INET6) |
| 144 | try: |
| 145 | result["ipv6_default_routes"] = len(ip_json("-6", "route", "show", "default")) |
| 146 | except (OSError, ValueError, subprocess.SubprocessError): |
| 147 | result["ipv6_default_routes"] = -1 |
| 148 | try: |
| 149 | result["ipv6_global_addresses"] = sum(len(link.get("addr_info", [])) for link in ip_json("-6", "addr", "show", "scope", "global")) |
| 150 | except (OSError, ValueError, subprocess.SubprocessError, AttributeError): |
| 151 | result["ipv6_global_addresses"] = -1 |
| 152 | result["udp_attempted"] = udp_attempted(("1.1.1.1", 3478), b"Cage network boundary probe") |
| 153 | result["dns_udp_attempted"] = udp_attempted(("1.1.1.1", 53), b"Cage DNS boundary probe") |
| 154 | result["dns_tcp_connected"] = connected(("1.1.1.1", 53)) |
| 155 | result["dot_connected"] = connected(("1.1.1.1", 853)) |
| 156 | result["resolvers"] = resolver_observation(args["management_host"]) |
| 157 | try: |
| 158 | socket.getaddrinfo(args["nonce"] + ".example.com", 443) |
| 159 | result["public_dns_answered"] = True |
| 160 | except socket.gaierror: |
| 161 | result["public_dns_answered"] = False |
| 162 | root_probe = """import os,sys |
| 163 | try: |
| 164 | fd=os.open(sys.argv[1],os.O_RDONLY|os.O_NONBLOCK) |
| 165 | os.close(fd) |
| 166 | print('readable') |
| 167 | except (FileNotFoundError,PermissionError): print('unreachable') |
| 168 | except OSError: print('unknown') |
| 169 | """ |
| 170 | result["private_file"] = "unknown" |
| 171 | try: |
| 172 | check = subprocess.run(["sudo", "-n", "python3", "-c", root_probe, args["private_file"]], capture_output=True, text=True, timeout=3, check=True) |
| 173 | result["private_file"] = check.stdout.strip() |
| 174 | except (OSError, subprocess.SubprocessError): |
| 175 | pass |
| 176 | result["shared_file"] = False |
| 177 | try: |
| 178 | fd = os.open(args["shared_file"], os.O_RDWR | os.O_NOFOLLOW) |
| 179 | with os.fdopen(fd, "r+") as shared: |
| 180 | if shared.read(256) == args["challenge"]: |
| 181 | shared.seek(0) |
| 182 | shared.write(args["challenge"] + ":guest") |
| 183 | shared.truncate() |
| 184 | shared.flush() |
| 185 | result["shared_file"] = True |
| 186 | except OSError: |
| 187 | pass |
| 188 | |
| 189 | if args["stage"] == "network": |
| 190 | result["egress"] = probe("/egress") |
| 191 | result["dns"] = probe("/dns") |
| 192 | |
| 193 | print(json.dumps(result)) |