authentik.enterprise.endpoints.connectors.fleet.controller
1import re 2from plistlib import loads 3from typing import Any 4 5from cryptography.hazmat.primitives import serialization 6from cryptography.x509 import load_der_x509_certificate 7from django.db import transaction 8from requests import RequestException 9from rest_framework.exceptions import ValidationError 10 11from authentik.core.models import User 12from authentik.crypto.models import CertificateKeyPair 13from authentik.endpoints.controller import BaseController, Capabilities, ConnectorSyncException 14from authentik.endpoints.facts import ( 15 DeviceFacts, 16 OSFamily, 17) 18from authentik.endpoints.models import ( 19 Device, 20 DeviceAccessGroup, 21 DeviceConnection, 22 DeviceUserBinding, 23) 24from authentik.enterprise.endpoints.connectors.fleet.models import FleetConnector as DBC 25from authentik.events.utils import sanitize_item 26from authentik.lib.utils.http import get_http_session 27from authentik.policies.utils import delete_none_values 28 29 30class FleetController(BaseController[DBC]): 31 def __init__(self, *args, **kwargs): 32 super().__init__(*args, **kwargs) 33 base_url = self.connector.url 34 if base_url.endswith("/"): 35 base_url = base_url[:-1] 36 self._base_url = base_url 37 self._session = get_http_session() 38 self._session.headers["Authorization"] = f"Bearer {self.connector.token}" 39 if self.connector.headers_mapping: 40 self._session.headers.update( 41 sanitize_item( 42 self.connector.headers_mapping.evaluate( 43 user=None, 44 request=None, 45 connector=self.connector, 46 ) 47 ) 48 ) 49 50 @staticmethod 51 def vendor_identifier() -> str: 52 return "fleetdm.com" 53 54 def capabilities(self) -> list[Capabilities]: 55 return [Capabilities.STAGE_ENDPOINTS, Capabilities.ENROLL_AUTOMATIC_API] 56 57 def _url(self, path: str) -> str: 58 return f"{self._base_url}{path}" 59 60 def _paginate_hosts(self): 61 try: 62 page = 0 63 while True: 64 self.logger.info("Fetching page of hosts...", page=page) 65 res = self._session.get( 66 self._url("/api/v1/fleet/hosts"), 67 params={ 68 "order_key": "hardware_serial", 69 "page": page, 70 # Small page size as Fleet's API response, with the populate fields below 71 # can be quite large and eat a lot of memory 72 "per_page": 1, 73 "device_mapping": "true", 74 "populate_software": "without_vulnerability_details", 75 "populate_users": "true", 76 "populate_policies": "true", 77 }, 78 ) 79 res.raise_for_status() 80 hosts: list[dict[str, Any]] = res.json()["hosts"] 81 if len(hosts) < 1: 82 self.logger.info("No more hosts, finished") 83 break 84 self.logger.info("Got hosts", count=len(hosts)) 85 yield from hosts 86 page += 1 87 except RequestException as exc: 88 raise ConnectorSyncException(exc) from exc 89 90 @property 91 def mtls_ca_managed(self) -> str: 92 return f"goauthentik.io/endpoints/connectors/fleet/{self.connector.pk}" 93 94 def _sync_mtls_ca(self): 95 """Sync conditional access Root CA for mTLS""" 96 try: 97 # Fleet doesn't have an API to just get the Conditional Access Root CA Cert (yet), 98 # hence we fetch the apple config profile and extract it 99 res = self._session.get(self._url("/api/v1/fleet/conditional_access/idp/apple/profile")) 100 res.raise_for_status() 101 profile = loads(res.text).get("PayloadContent", []) 102 raw_cert = None 103 for payload in profile: 104 if payload.get("PayloadIdentifier", "") != "com.fleetdm.conditional-access-ca": 105 continue 106 raw_cert = payload.get("PayloadContent") 107 if not raw_cert: 108 raise ConnectorSyncException("Failed to get conditional acccess CA") 109 except RequestException as exc: 110 raise ConnectorSyncException(exc) from exc 111 cert = load_der_x509_certificate(raw_cert) 112 CertificateKeyPair.objects.update_or_create( 113 managed=self.mtls_ca_managed, 114 defaults={ 115 "name": f"Fleet Endpoint connector {self.connector.name}", 116 "certificate_data": cert.public_bytes( 117 encoding=serialization.Encoding.PEM, 118 ).decode("utf-8"), 119 }, 120 ) 121 122 @transaction.atomic 123 def sync_endpoints(self) -> None: 124 try: 125 self._sync_mtls_ca() 126 except ConnectorSyncException as exc: 127 self.logger.warning("Failed to sync conditional access CA", exc=exc) 128 for host in self._paginate_hosts(): 129 serial = host["hardware_serial"] 130 device = Device.get_or_create( 131 identifier=serial, name=host["hostname"], defaults={"expiring": False} 132 ) 133 connection, _ = DeviceConnection.objects.update_or_create( 134 device=device, 135 connector=self.connector, 136 ) 137 if self.connector.map_users: 138 self.map_users(host, device) 139 if self.connector.map_teams_access_group: 140 self.map_access_group(host, device) 141 try: 142 connection.create_snapshot(self.convert_host_data(host)) 143 except ValidationError as exc: 144 self.logger.warning( 145 "failed to create snapshot for host", host=host["hostname"], exc=exc 146 ) 147 148 def map_users(self, host: dict[str, Any], device: Device): 149 for raw_user in host.get("device_mapping", []) or []: 150 user = User.objects.filter(email=raw_user["email"]).first() 151 if not user: 152 continue 153 DeviceUserBinding.objects.update_or_create( 154 target=device, 155 user=user, 156 create_defaults={ 157 "is_primary": True, 158 "order": 0, 159 }, 160 ) 161 162 def map_access_group(self, host: dict[str, Any], device: Device): 163 team_name = host.get("team_name") 164 if not team_name: 165 return 166 group, _ = DeviceAccessGroup.objects.get_or_create(name=team_name) 167 group.attributes["io.goauthentik.endpoints.connectors.fleet.team_id"] = host["team_id"] 168 if device.access_group: 169 return 170 device.access_group = group 171 device.save() 172 173 @staticmethod 174 def os_family(host: dict[str, Any]) -> OSFamily: 175 if host["platform_like"] in ["debian", "rhel"]: 176 return OSFamily.linux 177 if host["platform_like"] == "windows": 178 return OSFamily.windows 179 if host["platform_like"] == "darwin": 180 return OSFamily.macOS 181 if host["platform"] == "android": 182 return OSFamily.android 183 if host["platform"] in ["ipados", "ios"]: 184 return OSFamily.iOS 185 return OSFamily.other 186 187 def map_os(self, host: dict[str, Any]) -> dict[str, str]: 188 family = FleetController.os_family(host) 189 os = { 190 "arch": self.or_none(host["cpu_type"]), 191 "family": family, 192 "name": self.or_none(host["platform_like"]), 193 "version": self.or_none(host["os_version"]), 194 } 195 if not host["os_version"]: 196 return delete_none_values(os) 197 version = re.search(r"(\d+\.(?:\d+\.?)+)", host["os_version"]) 198 if not version: 199 return delete_none_values(os) 200 os["version"] = host["os_version"][version.start() :].strip() 201 os["name"] = host["os_version"][0 : version.start()].strip() 202 return delete_none_values(os) 203 204 def or_none(self, value) -> Any | None: 205 if value == "": 206 return None 207 return value 208 209 def convert_host_data(self, host: dict[str, Any]) -> dict[str, Any]: 210 """Convert host data from fleet to authentik""" 211 fleet_version = "" 212 for pkg in host.get("software") or []: 213 if pkg["name"] in ["fleet-osquery", "fleet-desktop"]: 214 fleet_version = pkg["version"] 215 data = { 216 "os": self.map_os(host), 217 "disks": [], 218 "network": delete_none_values( 219 {"hostname": self.or_none(host["hostname"]), "interfaces": []} 220 ), 221 "hardware": delete_none_values( 222 { 223 "model": self.or_none(host["hardware_model"]), 224 "manufacturer": self.or_none(host["hardware_vendor"]), 225 "serial": self.or_none(host["hardware_serial"]), 226 "cpu_name": self.or_none(host["cpu_brand"]), 227 "cpu_count": self.or_none(host["cpu_logical_cores"]), 228 "memory_bytes": self.or_none(host["memory"]), 229 } 230 ), 231 "software": [ 232 delete_none_values( 233 { 234 "name": x["name"], 235 "version": x["version"], 236 "source": x["source"], 237 } 238 ) 239 for x in (host.get("software") or []) 240 ], 241 "vendor": { 242 self.vendor_identifier(): { 243 "policies": [ 244 delete_none_values({"name": policy["name"], "status": policy["response"]}) 245 for policy in (host.get("policies") or []) 246 ], 247 "agent_version": fleet_version, 248 # Host UUID is required for conditional access matching 249 "uuid": (host.get("uuid") or "").lower(), 250 }, 251 }, 252 } 253 facts = DeviceFacts(data=data) 254 facts.is_valid(raise_exception=True) 255 return facts.validated_data
class
FleetController(authentik.endpoints.controller.BaseController[authentik.enterprise.endpoints.connectors.fleet.models.FleetConnector]):
31class FleetController(BaseController[DBC]): 32 def __init__(self, *args, **kwargs): 33 super().__init__(*args, **kwargs) 34 base_url = self.connector.url 35 if base_url.endswith("/"): 36 base_url = base_url[:-1] 37 self._base_url = base_url 38 self._session = get_http_session() 39 self._session.headers["Authorization"] = f"Bearer {self.connector.token}" 40 if self.connector.headers_mapping: 41 self._session.headers.update( 42 sanitize_item( 43 self.connector.headers_mapping.evaluate( 44 user=None, 45 request=None, 46 connector=self.connector, 47 ) 48 ) 49 ) 50 51 @staticmethod 52 def vendor_identifier() -> str: 53 return "fleetdm.com" 54 55 def capabilities(self) -> list[Capabilities]: 56 return [Capabilities.STAGE_ENDPOINTS, Capabilities.ENROLL_AUTOMATIC_API] 57 58 def _url(self, path: str) -> str: 59 return f"{self._base_url}{path}" 60 61 def _paginate_hosts(self): 62 try: 63 page = 0 64 while True: 65 self.logger.info("Fetching page of hosts...", page=page) 66 res = self._session.get( 67 self._url("/api/v1/fleet/hosts"), 68 params={ 69 "order_key": "hardware_serial", 70 "page": page, 71 # Small page size as Fleet's API response, with the populate fields below 72 # can be quite large and eat a lot of memory 73 "per_page": 1, 74 "device_mapping": "true", 75 "populate_software": "without_vulnerability_details", 76 "populate_users": "true", 77 "populate_policies": "true", 78 }, 79 ) 80 res.raise_for_status() 81 hosts: list[dict[str, Any]] = res.json()["hosts"] 82 if len(hosts) < 1: 83 self.logger.info("No more hosts, finished") 84 break 85 self.logger.info("Got hosts", count=len(hosts)) 86 yield from hosts 87 page += 1 88 except RequestException as exc: 89 raise ConnectorSyncException(exc) from exc 90 91 @property 92 def mtls_ca_managed(self) -> str: 93 return f"goauthentik.io/endpoints/connectors/fleet/{self.connector.pk}" 94 95 def _sync_mtls_ca(self): 96 """Sync conditional access Root CA for mTLS""" 97 try: 98 # Fleet doesn't have an API to just get the Conditional Access Root CA Cert (yet), 99 # hence we fetch the apple config profile and extract it 100 res = self._session.get(self._url("/api/v1/fleet/conditional_access/idp/apple/profile")) 101 res.raise_for_status() 102 profile = loads(res.text).get("PayloadContent", []) 103 raw_cert = None 104 for payload in profile: 105 if payload.get("PayloadIdentifier", "") != "com.fleetdm.conditional-access-ca": 106 continue 107 raw_cert = payload.get("PayloadContent") 108 if not raw_cert: 109 raise ConnectorSyncException("Failed to get conditional acccess CA") 110 except RequestException as exc: 111 raise ConnectorSyncException(exc) from exc 112 cert = load_der_x509_certificate(raw_cert) 113 CertificateKeyPair.objects.update_or_create( 114 managed=self.mtls_ca_managed, 115 defaults={ 116 "name": f"Fleet Endpoint connector {self.connector.name}", 117 "certificate_data": cert.public_bytes( 118 encoding=serialization.Encoding.PEM, 119 ).decode("utf-8"), 120 }, 121 ) 122 123 @transaction.atomic 124 def sync_endpoints(self) -> None: 125 try: 126 self._sync_mtls_ca() 127 except ConnectorSyncException as exc: 128 self.logger.warning("Failed to sync conditional access CA", exc=exc) 129 for host in self._paginate_hosts(): 130 serial = host["hardware_serial"] 131 device = Device.get_or_create( 132 identifier=serial, name=host["hostname"], defaults={"expiring": False} 133 ) 134 connection, _ = DeviceConnection.objects.update_or_create( 135 device=device, 136 connector=self.connector, 137 ) 138 if self.connector.map_users: 139 self.map_users(host, device) 140 if self.connector.map_teams_access_group: 141 self.map_access_group(host, device) 142 try: 143 connection.create_snapshot(self.convert_host_data(host)) 144 except ValidationError as exc: 145 self.logger.warning( 146 "failed to create snapshot for host", host=host["hostname"], exc=exc 147 ) 148 149 def map_users(self, host: dict[str, Any], device: Device): 150 for raw_user in host.get("device_mapping", []) or []: 151 user = User.objects.filter(email=raw_user["email"]).first() 152 if not user: 153 continue 154 DeviceUserBinding.objects.update_or_create( 155 target=device, 156 user=user, 157 create_defaults={ 158 "is_primary": True, 159 "order": 0, 160 }, 161 ) 162 163 def map_access_group(self, host: dict[str, Any], device: Device): 164 team_name = host.get("team_name") 165 if not team_name: 166 return 167 group, _ = DeviceAccessGroup.objects.get_or_create(name=team_name) 168 group.attributes["io.goauthentik.endpoints.connectors.fleet.team_id"] = host["team_id"] 169 if device.access_group: 170 return 171 device.access_group = group 172 device.save() 173 174 @staticmethod 175 def os_family(host: dict[str, Any]) -> OSFamily: 176 if host["platform_like"] in ["debian", "rhel"]: 177 return OSFamily.linux 178 if host["platform_like"] == "windows": 179 return OSFamily.windows 180 if host["platform_like"] == "darwin": 181 return OSFamily.macOS 182 if host["platform"] == "android": 183 return OSFamily.android 184 if host["platform"] in ["ipados", "ios"]: 185 return OSFamily.iOS 186 return OSFamily.other 187 188 def map_os(self, host: dict[str, Any]) -> dict[str, str]: 189 family = FleetController.os_family(host) 190 os = { 191 "arch": self.or_none(host["cpu_type"]), 192 "family": family, 193 "name": self.or_none(host["platform_like"]), 194 "version": self.or_none(host["os_version"]), 195 } 196 if not host["os_version"]: 197 return delete_none_values(os) 198 version = re.search(r"(\d+\.(?:\d+\.?)+)", host["os_version"]) 199 if not version: 200 return delete_none_values(os) 201 os["version"] = host["os_version"][version.start() :].strip() 202 os["name"] = host["os_version"][0 : version.start()].strip() 203 return delete_none_values(os) 204 205 def or_none(self, value) -> Any | None: 206 if value == "": 207 return None 208 return value 209 210 def convert_host_data(self, host: dict[str, Any]) -> dict[str, Any]: 211 """Convert host data from fleet to authentik""" 212 fleet_version = "" 213 for pkg in host.get("software") or []: 214 if pkg["name"] in ["fleet-osquery", "fleet-desktop"]: 215 fleet_version = pkg["version"] 216 data = { 217 "os": self.map_os(host), 218 "disks": [], 219 "network": delete_none_values( 220 {"hostname": self.or_none(host["hostname"]), "interfaces": []} 221 ), 222 "hardware": delete_none_values( 223 { 224 "model": self.or_none(host["hardware_model"]), 225 "manufacturer": self.or_none(host["hardware_vendor"]), 226 "serial": self.or_none(host["hardware_serial"]), 227 "cpu_name": self.or_none(host["cpu_brand"]), 228 "cpu_count": self.or_none(host["cpu_logical_cores"]), 229 "memory_bytes": self.or_none(host["memory"]), 230 } 231 ), 232 "software": [ 233 delete_none_values( 234 { 235 "name": x["name"], 236 "version": x["version"], 237 "source": x["source"], 238 } 239 ) 240 for x in (host.get("software") or []) 241 ], 242 "vendor": { 243 self.vendor_identifier(): { 244 "policies": [ 245 delete_none_values({"name": policy["name"], "status": policy["response"]}) 246 for policy in (host.get("policies") or []) 247 ], 248 "agent_version": fleet_version, 249 # Host UUID is required for conditional access matching 250 "uuid": (host.get("uuid") or "").lower(), 251 }, 252 }, 253 } 254 facts = DeviceFacts(data=data) 255 facts.is_valid(raise_exception=True) 256 return facts.validated_data
Abstract base class for generic types.
On Python 3.12 and newer, generic classes implicitly inherit from Generic when they declare a parameter list after the class's name::
class Mapping[KT, VT]:
def __getitem__(self, key: KT) -> VT:
...
# Etc.
On older versions of Python, however, generic classes have to explicitly inherit from Generic.
After a class has been declared to be generic, it can then be used as follows::
def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
try:
return mapping[key]
except KeyError:
return default
FleetController(*args, **kwargs)
32 def __init__(self, *args, **kwargs): 33 super().__init__(*args, **kwargs) 34 base_url = self.connector.url 35 if base_url.endswith("/"): 36 base_url = base_url[:-1] 37 self._base_url = base_url 38 self._session = get_http_session() 39 self._session.headers["Authorization"] = f"Bearer {self.connector.token}" 40 if self.connector.headers_mapping: 41 self._session.headers.update( 42 sanitize_item( 43 self.connector.headers_mapping.evaluate( 44 user=None, 45 request=None, 46 connector=self.connector, 47 ) 48 ) 49 )
@transaction.atomic
def
sync_endpoints(self) -> None:
123 @transaction.atomic 124 def sync_endpoints(self) -> None: 125 try: 126 self._sync_mtls_ca() 127 except ConnectorSyncException as exc: 128 self.logger.warning("Failed to sync conditional access CA", exc=exc) 129 for host in self._paginate_hosts(): 130 serial = host["hardware_serial"] 131 device = Device.get_or_create( 132 identifier=serial, name=host["hostname"], defaults={"expiring": False} 133 ) 134 connection, _ = DeviceConnection.objects.update_or_create( 135 device=device, 136 connector=self.connector, 137 ) 138 if self.connector.map_users: 139 self.map_users(host, device) 140 if self.connector.map_teams_access_group: 141 self.map_access_group(host, device) 142 try: 143 connection.create_snapshot(self.convert_host_data(host)) 144 except ValidationError as exc: 145 self.logger.warning( 146 "failed to create snapshot for host", host=host["hostname"], exc=exc 147 )
149 def map_users(self, host: dict[str, Any], device: Device): 150 for raw_user in host.get("device_mapping", []) or []: 151 user = User.objects.filter(email=raw_user["email"]).first() 152 if not user: 153 continue 154 DeviceUserBinding.objects.update_or_create( 155 target=device, 156 user=user, 157 create_defaults={ 158 "is_primary": True, 159 "order": 0, 160 }, 161 )
def
map_access_group( self, host: dict[str, typing.Any], device: authentik.endpoints.models.Device):
163 def map_access_group(self, host: dict[str, Any], device: Device): 164 team_name = host.get("team_name") 165 if not team_name: 166 return 167 group, _ = DeviceAccessGroup.objects.get_or_create(name=team_name) 168 group.attributes["io.goauthentik.endpoints.connectors.fleet.team_id"] = host["team_id"] 169 if device.access_group: 170 return 171 device.access_group = group 172 device.save()
174 @staticmethod 175 def os_family(host: dict[str, Any]) -> OSFamily: 176 if host["platform_like"] in ["debian", "rhel"]: 177 return OSFamily.linux 178 if host["platform_like"] == "windows": 179 return OSFamily.windows 180 if host["platform_like"] == "darwin": 181 return OSFamily.macOS 182 if host["platform"] == "android": 183 return OSFamily.android 184 if host["platform"] in ["ipados", "ios"]: 185 return OSFamily.iOS 186 return OSFamily.other
def
map_os(self, host: dict[str, typing.Any]) -> dict[str, str]:
188 def map_os(self, host: dict[str, Any]) -> dict[str, str]: 189 family = FleetController.os_family(host) 190 os = { 191 "arch": self.or_none(host["cpu_type"]), 192 "family": family, 193 "name": self.or_none(host["platform_like"]), 194 "version": self.or_none(host["os_version"]), 195 } 196 if not host["os_version"]: 197 return delete_none_values(os) 198 version = re.search(r"(\d+\.(?:\d+\.?)+)", host["os_version"]) 199 if not version: 200 return delete_none_values(os) 201 os["version"] = host["os_version"][version.start() :].strip() 202 os["name"] = host["os_version"][0 : version.start()].strip() 203 return delete_none_values(os)
def
convert_host_data(self, host: dict[str, typing.Any]) -> dict[str, typing.Any]:
210 def convert_host_data(self, host: dict[str, Any]) -> dict[str, Any]: 211 """Convert host data from fleet to authentik""" 212 fleet_version = "" 213 for pkg in host.get("software") or []: 214 if pkg["name"] in ["fleet-osquery", "fleet-desktop"]: 215 fleet_version = pkg["version"] 216 data = { 217 "os": self.map_os(host), 218 "disks": [], 219 "network": delete_none_values( 220 {"hostname": self.or_none(host["hostname"]), "interfaces": []} 221 ), 222 "hardware": delete_none_values( 223 { 224 "model": self.or_none(host["hardware_model"]), 225 "manufacturer": self.or_none(host["hardware_vendor"]), 226 "serial": self.or_none(host["hardware_serial"]), 227 "cpu_name": self.or_none(host["cpu_brand"]), 228 "cpu_count": self.or_none(host["cpu_logical_cores"]), 229 "memory_bytes": self.or_none(host["memory"]), 230 } 231 ), 232 "software": [ 233 delete_none_values( 234 { 235 "name": x["name"], 236 "version": x["version"], 237 "source": x["source"], 238 } 239 ) 240 for x in (host.get("software") or []) 241 ], 242 "vendor": { 243 self.vendor_identifier(): { 244 "policies": [ 245 delete_none_values({"name": policy["name"], "status": policy["response"]}) 246 for policy in (host.get("policies") or []) 247 ], 248 "agent_version": fleet_version, 249 # Host UUID is required for conditional access matching 250 "uuid": (host.get("uuid") or "").lower(), 251 }, 252 }, 253 } 254 facts = DeviceFacts(data=data) 255 facts.is_valid(raise_exception=True) 256 return facts.validated_data
Convert host data from fleet to authentik