1use crate::dsregcmd::models::{
2 DsregcmdAnalysisResult, DsregcmdDiagnosticInsight, DsregcmdJoinType,
3};
4use crate::intune::models::IntuneDiagnosticSeverity;
5
6use super::derive::issue;
7
8pub fn apply_enrollment_cross_reference(result: &mut DsregcmdAnalysisResult) {
11 if result.derived.mdm_enrolled.is_some() {
12 return;
13 }
14 if let (Some(enrollment), Some(tasks)) =
15 (&result.enrollment_evidence, &result.scheduled_task_evidence)
16 {
17 let confirmed = enrollment.enrollments.iter().any(|e| {
18 e.enrollment_state == Some(1)
19 && e.guid.as_ref().is_some_and(|g| {
20 tasks
21 .enterprise_mgmt_guids
22 .iter()
23 .any(|t| t.eq_ignore_ascii_case(g))
24 })
25 });
26 if confirmed {
27 result.derived.mdm_enrolled = Some(true);
28 }
29 }
30}
31
32pub fn build_extended_diagnostics(
34 result: &DsregcmdAnalysisResult,
35) -> Vec<DsregcmdDiagnosticInsight> {
36 let mut diagnostics = Vec::new();
37
38 if let Some(os) = result.os_version.as_ref() {
39 let build_num = os
40 .current_build
41 .as_deref()
42 .and_then(|b| b.parse::<u32>().ok());
43
44 let cloud_trust_configured = result
45 .policy_evidence
46 .use_cloud_trust_for_on_prem_auth
47 .display_value
48 == Some(true);
49
50 if let Some(build) = build_num {
51 if build < 22000 && cloud_trust_configured {
52 diagnostics.push(issue(
53 "os-build-below-cloud-trust",
54 IntuneDiagnosticSeverity::Warning,
55 "configuration",
56 "OS build is below the minimum required for cloud trust",
57 "Cloud trust for on-premises authentication requires Windows 11 (build 22000+), but this device is running an older build.",
58 vec![
59 format!("CurrentBuild: {build}"),
60 "UseCloudTrustForOnPremAuth: YES".to_string(),
61 ],
62 vec!["Upgrade the OS to Windows 11 or later to use cloud trust.".to_string()],
63 vec!["Upgrade the device OS or switch to certificate-based on-premises authentication.".to_string()],
64 ));
65 }
66
67 if build < 19041 {
68 diagnostics.push(issue(
69 "os-build-outdated",
70 IntuneDiagnosticSeverity::Info,
71 "configuration",
72 "OS build is older than Windows 10 version 2004",
73 "This device is running a build prior to 19041 (Windows 10 2004). Some modern device registration features may not be available.",
74 vec![format!("CurrentBuild: {build}")],
75 vec!["Confirm the OS version is still in support and meets tenant requirements.".to_string()],
76 Vec::new(),
77 ));
78 }
79 }
80 }
81
82 if let Some(proxy) = result.proxy_evidence.as_ref() {
83 let proxy_detected = proxy.proxy_enabled == Some(true)
84 || proxy.proxy_server.is_some()
85 || proxy.auto_config_url.is_some();
86
87 if proxy_detected {
88 diagnostics.push(issue(
89 "proxy-configured",
90 IntuneDiagnosticSeverity::Info,
91 "network",
92 "Proxy configuration detected",
93 "The device has proxy settings configured, which can affect connectivity to Entra ID endpoints.",
94 vec![
95 format!("ProxyEnabled: {}", proxy.proxy_enabled.map(|v| if v { "YES" } else { "NO" }).unwrap_or("(not set)")),
96 format!("ProxyServer: {}", proxy.proxy_server.as_deref().unwrap_or("(not set)")),
97 format!("AutoConfigURL: {}", proxy.auto_config_url.as_deref().unwrap_or("(not set)")),
98 ],
99 vec!["Confirm the proxy allows traffic to required Microsoft Entra endpoints.".to_string()],
100 Vec::new(),
101 ));
102 }
103
104 let has_join_failures = result
105 .diagnostics
106 .iter()
107 .any(|d| d.severity == IntuneDiagnosticSeverity::Error);
108
109 if proxy.wpad_detected && has_join_failures {
110 diagnostics.push(issue(
111 "proxy-wpad-with-join-failure",
112 IntuneDiagnosticSeverity::Warning,
113 "network",
114 "WPAD proxy detected alongside join failures",
115 "The device is using WPAD proxy auto-discovery, which can cause intermittent connectivity failures during device registration if the SYSTEM context cannot resolve the WPAD endpoint.",
116 vec![
117 format!("AutoConfigURL: {}", proxy.auto_config_url.as_deref().unwrap_or("(wpad)")),
118 ],
119 vec![
120 "Verify the SYSTEM context can resolve the WPAD endpoint.".to_string(),
121 "Consider configuring explicit WinHTTP proxy for the machine context.".to_string(),
122 ],
123 vec!["Configure an explicit proxy or ensure WPAD resolves from the machine context.".to_string()],
124 ));
125 }
126 }
127
128 if let Some(enrollment) = result.enrollment_evidence.as_ref() {
129 let is_joined = result.facts.join_state.azure_ad_joined == Some(true);
130
131 if enrollment.enrollment_count == 0
132 && is_joined
133 && result.derived.mdm_enrolled != Some(true)
134 {
135 diagnostics.push(issue(
136 "enrollment-missing-on-joined",
137 IntuneDiagnosticSeverity::Warning,
138 "configuration",
139 "No MDM enrollment found on a joined device",
140 "The device is Entra ID joined but has no enrollment entries in the registry, which may indicate MDM enrollment has not completed or was removed.",
141 vec![format!("EnrollmentCount: {}", enrollment.enrollment_count)],
142 vec![
143 "Check whether automatic MDM enrollment is configured for this tenant and user scope.".to_string(),
144 "Verify enrollment status in the Intune portal for this device.".to_string(),
145 ],
146 vec!["Trigger MDM enrollment or re-register the device.".to_string()],
147 ));
148 }
149
150 if enrollment.enrollment_count > 1 {
151 diagnostics.push(issue(
152 "multiple-enrollments",
153 IntuneDiagnosticSeverity::Info,
154 "configuration",
155 "Multiple MDM enrollment entries detected",
156 "The device has more than one enrollment entry in the registry, which can indicate dual management or stale enrollment records.",
157 vec![format!("EnrollmentCount: {}", enrollment.enrollment_count)],
158 vec!["Review enrollment entries and confirm only the expected MDM enrollment is active.".to_string()],
159 Vec::new(),
160 ));
161 }
162 }
163
164 let mdm_urls_absent = result.facts.management_details.mdm_url.is_none()
166 && result.facts.management_details.mdm_compliance_url.is_none();
167 if result.derived.mdm_enrolled == Some(true) && mdm_urls_absent {
168 let mut evidence_lines = Vec::new();
169 if let (Some(ref enrollment), Some(ref tasks)) =
170 (&result.enrollment_evidence, &result.scheduled_task_evidence)
171 {
172 for entry in &enrollment.enrollments {
173 let guid_matched = entry.enrollment_state == Some(1)
174 && entry.guid.as_ref().is_some_and(|g| {
175 tasks
176 .enterprise_mgmt_guids
177 .iter()
178 .any(|t| t.eq_ignore_ascii_case(g))
179 });
180 if guid_matched {
181 let guid_display = entry.guid.as_deref().unwrap_or("(unknown)");
182 let upn_display = entry.upn.as_deref().unwrap_or("(no UPN)");
183 evidence_lines.push(format!(
184 "GUID: {} — UPN: {} — EnrollmentState: 1 — matched scheduled task",
185 guid_display, upn_display
186 ));
187 }
188 }
189 evidence_lines.push(format!(
190 "EnterpriseMgmt scheduled task GUIDs: {}",
191 if tasks.enterprise_mgmt_guids.is_empty() {
192 "(none)".to_string()
193 } else {
194 tasks.enterprise_mgmt_guids.join(", ")
195 }
196 ));
197 }
198 diagnostics.push(issue(
199 "mdm-confirmed-via-registry",
200 IntuneDiagnosticSeverity::Info,
201 "configuration",
202 "MDM enrollment confirmed via scheduled tasks and registry",
203 "The dsregcmd output does not contain MDM URLs, but the device has active enrollment entries in the registry whose GUIDs match scheduled tasks under \\Microsoft\\Windows\\EnterpriseMgmt. This confirms the device is MDM-enrolled.",
204 evidence_lines,
205 vec![
206 "The dsregcmd MDM URL fields are tenant-dependent and often absent on enrolled devices.".to_string(),
207 "The registry cross-reference with scheduled tasks provides a definitive enrollment signal.".to_string(),
208 ],
209 Vec::new(),
210 ));
211 }
212
213 diagnostics
214}
215
216pub fn build_active_diagnostics_rules(
218 result: &DsregcmdAnalysisResult,
219) -> Vec<DsregcmdDiagnosticInsight> {
220 let mut diagnostics = Vec::new();
221
222 let active = match result.active_evidence.as_ref() {
223 Some(a) => a,
224 None => return diagnostics,
225 };
226
227 let has_join_failures = result
228 .diagnostics
229 .iter()
230 .any(|d| d.severity == IntuneDiagnosticSeverity::Error);
231
232 for test in &active.connectivity_tests {
233 if !test.reachable {
234 let endpoint_lower = test.endpoint.to_ascii_lowercase();
235
236 if endpoint_lower.contains("enterpriseregistration") && has_join_failures {
237 diagnostics.push(issue(
238 "endpoint-unreachable-drs",
239 IntuneDiagnosticSeverity::Error,
240 "connectivity",
241 "DRS endpoint is unreachable and join is failing",
242 "The device cannot reach enterpriseregistration.windows.net, which is required for device registration.",
243 vec![
244 format!("Endpoint: {}", test.endpoint),
245 format!("Error: {}", test.error_message.as_deref().unwrap_or("(unknown)")),
246 ],
247 vec!["Restore network access to the DRS endpoint before retrying join.".to_string()],
248 vec!["Fix firewall, proxy, or DNS rules blocking the DRS endpoint.".to_string()],
249 ));
250 }
251
252 if endpoint_lower.contains("login.microsoftonline.com")
253 && !endpoint_lower.contains("device.login")
254 {
255 diagnostics.push(issue(
256 "endpoint-unreachable-login",
257 IntuneDiagnosticSeverity::Error,
258 "connectivity",
259 "Microsoft Entra login endpoint is unreachable",
260 "The device cannot reach login.microsoftonline.com, which is required for authentication.",
261 vec![
262 format!("Endpoint: {}", test.endpoint),
263 format!("Error: {}", test.error_message.as_deref().unwrap_or("(unknown)")),
264 ],
265 vec!["Restore connectivity to login.microsoftonline.com.".to_string()],
266 vec!["Fix network path to the Microsoft Entra login endpoint.".to_string()],
267 ));
268 }
269
270 if endpoint_lower.contains("device.login") {
271 diagnostics.push(issue(
272 "endpoint-unreachable-device-login",
273 IntuneDiagnosticSeverity::Error,
274 "connectivity",
275 "Device login endpoint is unreachable",
276 "The device cannot reach device.login.microsoftonline.com, which is needed for device code flows and conditional access.",
277 vec![
278 format!("Endpoint: {}", test.endpoint),
279 format!("Error: {}", test.error_message.as_deref().unwrap_or("(unknown)")),
280 ],
281 vec!["Restore connectivity to device.login.microsoftonline.com.".to_string()],
282 vec!["Fix network path to the device login endpoint.".to_string()],
283 ));
284 }
285
286 let is_hybrid = result.derived.join_type == DsregcmdJoinType::HybridEntraIdJoined
287 || result.facts.join_state.domain_joined == Some(true);
288
289 if endpoint_lower.contains("autologon") && is_hybrid {
290 diagnostics.push(issue(
291 "seamless-sso-unreachable",
292 IntuneDiagnosticSeverity::Warning,
293 "connectivity",
294 "Seamless SSO endpoint is unreachable on a hybrid device",
295 "The device cannot reach autologon.microsoftazuread-sso.com, which is used for seamless SSO on hybrid-joined devices.",
296 vec![
297 format!("Endpoint: {}", test.endpoint),
298 format!("Error: {}", test.error_message.as_deref().unwrap_or("(unknown)")),
299 ],
300 vec!["Check whether seamless SSO is configured and the endpoint is reachable.".to_string()],
301 Vec::new(),
302 ));
303 }
304 }
305
306 if let Some(latency) = test.latency_ms {
307 if latency > 2000 {
308 diagnostics.push(issue(
309 "endpoint-high-latency",
310 IntuneDiagnosticSeverity::Warning,
311 "connectivity",
312 "High latency detected to an authentication endpoint",
313 &format!(
314 "The connectivity test to {} completed but took {}ms, which exceeds the 2000ms threshold and may cause timeouts during registration.",
315 test.endpoint, latency
316 ),
317 vec![
318 format!("Endpoint: {}", test.endpoint),
319 format!("Latency: {}ms", latency),
320 ],
321 vec!["Investigate network path quality and proxy overhead for this endpoint.".to_string()],
322 Vec::new(),
323 ));
324 }
325 }
326 }
327
328 if let Some(scp) = active.scp_query.as_ref() {
329 let is_domain_joined = result.facts.join_state.domain_joined == Some(true);
330
331 if !scp.scp_found && is_domain_joined {
332 diagnostics.push(issue(
333 "scp-not-found",
334 IntuneDiagnosticSeverity::Error,
335 "configuration",
336 "Service Connection Point not found in Active Directory",
337 "The device is domain-joined but no SCP was found for hybrid join configuration. This prevents automatic tenant discovery.",
338 vec![
339 format!("SCP found: NO"),
340 format!("Error: {}", scp.error.as_deref().unwrap_or("(none)")),
341 ],
342 vec![
343 "Verify the SCP is configured in Active Directory for this forest.".to_string(),
344 "Check Azure AD Connect SCP configuration.".to_string(),
345 ],
346 vec!["Configure the SCP in Active Directory using Azure AD Connect or manually.".to_string()],
347 ));
348 }
349
350 if scp.scp_found {
351 let dsregcmd_tenant = result.facts.tenant_details.domain_name.as_deref();
352 let scp_tenant = scp.tenant_domain.as_deref();
353
354 if let (Some(dsregcmd_domain), Some(scp_domain)) = (dsregcmd_tenant, scp_tenant) {
355 if !dsregcmd_domain.eq_ignore_ascii_case(scp_domain) {
356 diagnostics.push(issue(
357 "scp-tenant-mismatch-active",
358 IntuneDiagnosticSeverity::Error,
359 "configuration",
360 "SCP tenant domain does not match dsregcmd tenant",
361 "The SCP in Active Directory points to a different tenant than what dsregcmd reports. This can cause hybrid join to target the wrong tenant.",
362 vec![
363 format!("SCP tenant: {scp_domain}"),
364 format!("dsregcmd tenant: {dsregcmd_domain}"),
365 ],
366 vec!["Update the SCP to point to the correct verified tenant domain.".to_string()],
367 vec!["Correct the SCP tenant targeting in Active Directory.".to_string()],
368 ));
369 }
370 }
371 }
372 }
373
374 diagnostics
375}
376
377pub fn build_event_log_diagnostics(
379 result: &DsregcmdAnalysisResult,
380) -> Vec<DsregcmdDiagnosticInsight> {
381 let mut diagnostics = Vec::new();
382
383 let event_log = match result.event_log_analysis.as_ref() {
384 Some(a) => a,
385 None => return diagnostics,
386 };
387
388 let has_join_failures = result.diagnostics.iter().any(|d| {
389 d.severity == IntuneDiagnosticSeverity::Error
390 && (d.category == "authentication"
391 || d.category == "join"
392 || d.category == "configuration")
393 });
394
395 let has_tpm_errors = result.diagnostics.iter().any(|d| d.id.starts_with("tpm-"));
396
397 let time_sync_errors = event_log.entries.iter().any(|e| {
399 let channel_display = e.channel_display.to_ascii_lowercase();
400 let message_lower = e.message.to_ascii_lowercase();
401 (channel_display.contains("time service") || channel_display.contains("system"))
402 && (message_lower.contains("time skew")
403 || message_lower.contains("time synchronization")
404 || message_lower.contains("clock"))
405 });
406
407 if time_sync_errors && has_join_failures {
408 diagnostics.push(issue(
409 "event-log-time-skew",
410 IntuneDiagnosticSeverity::Warning,
411 "configuration",
412 "Event logs show time synchronization issues near join failures",
413 "The Windows event logs contain time sync or clock skew events that may correlate with authentication or join failures.",
414 vec!["Time sync events detected in System or Time Service logs.".to_string()],
415 vec![
416 "Check device clock accuracy and NTP configuration.".to_string(),
417 "Review whether time skew is causing certificate validation or token failures.".to_string(),
418 ],
419 vec!["Fix time synchronization before retrying device registration.".to_string()],
420 ));
421 }
422
423 let dpapi_failures = event_log.entries.iter().any(|e| {
425 let channel_display = e.channel_display.to_ascii_lowercase();
426 let message_lower = e.message.to_ascii_lowercase();
427 channel_display.contains("dpapi")
428 && (message_lower.contains("failed")
429 || message_lower.contains("error")
430 || message_lower.contains("cannot"))
431 });
432
433 if dpapi_failures && has_tpm_errors {
434 diagnostics.push(issue(
435 "event-log-dpapi-failure",
436 IntuneDiagnosticSeverity::Warning,
437 "configuration",
438 "DPAPI key failures detected alongside TPM errors",
439 "The DPAPI operational log shows key protection failures that may be related to the TPM issues observed in the dsregcmd output.",
440 vec!["DPAPI operational log errors present alongside TPM diagnostics.".to_string()],
441 vec![
442 "Check TPM health and whether DPAPI key material is protected by the TPM.".to_string(),
443 "Review whether clearing the TPM or re-provisioning keys would resolve the issue.".to_string(),
444 ],
445 Vec::new(),
446 ));
447 }
448
449 let aad_errors = event_log
451 .entries
452 .iter()
453 .filter(|e| {
454 let channel_display = e.channel_display.to_ascii_lowercase();
455 channel_display.contains("aad")
456 && e.severity.is_error_or_warning()
457 && !matches!(e.severity, crate::intune::models::EventLogSeverity::Warning)
458 })
459 .count();
460
461 if aad_errors > 0 {
462 diagnostics.push(issue(
463 "event-log-aad-errors",
464 IntuneDiagnosticSeverity::Info,
465 "authentication",
466 "AAD operational event log errors present",
467 &format!(
468 "The AAD Operational event log contains {} error(s) that may provide additional context for authentication or join issues.",
469 aad_errors
470 ),
471 vec![format!("AAD Operational error count: {aad_errors}")],
472 vec!["Review the AAD Operational event log entries for additional diagnostic detail.".to_string()],
473 Vec::new(),
474 ));
475 }
476
477 diagnostics
478}