Private/Diagnostics.ps1
|
# Error log and support diagnostics. Every failure gets an error id and a line in errors.log (data folder). The Details button # on an error builds a diagnostics report the admin can attach to a support request. Nothing here ever holds a password, # client secret or token: the token is only decoded for its permission claims and never kept, and every text is scrubbed. function Protect-STMDiagText { param([string]$Text) if (-not $Text) { return $Text } $t = $Text $t = [regex]::Replace($t, 'eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]*', '[token removed]') $t = [regex]::Replace($t, '(?i)(bearer\s+)[A-Za-z0-9\-\._~\+/]+=*', '$1[removed]') $t = [regex]::Replace($t, '(?i)("?(client_?secret|secret|password|code_verifier|refresh_token|access_token)"?\s*[:=]\s*)("[^"]*"|[^\s,;&]+)', '$1[removed]') if ($script:STM.HeldSecret) { $plain = $null try { $plain = [System.Net.NetworkCredential]::new('', $script:STM.HeldSecret).Password if ($plain -and $plain.Length -ge 8) { $t = $t.Replace($plain, '[secret removed]') } } catch { } finally { $plain = $null } } return $t } function Write-STMErrorLog { # Returns the error id. One JSON line per failure in errors.log; the last 50 also stay in memory for the report. param([Parameter(Mandatory)][System.Exception]$Exception, [string]$Source = 'Tool', [string]$Route, [string]$Stack) if ($Exception.Data -and $Exception.Data['ErrorId']) { return [string]$Exception.Data['ErrorId'] } $id = ([guid]::NewGuid().ToString('N')).Substring(0, 8).ToUpperInvariant() $entry = [ordered]@{ errorId = $id; timeUtc = [DateTime]::UtcNow.ToString('o'); source = $Source; route = $Route message = (Protect-STMDiagText ([string]$Exception.Message)); exceptionType = $Exception.GetType().FullName } foreach ($k in 'Kind', 'Status', 'Method', 'Uri', 'GraphCode', 'RequestId', 'ClientRequestId', 'Date', 'WwwAuthenticate', 'RawMessage', 'ExceptionType', 'Body') { if ($Exception.Data -and $Exception.Data.Contains($k) -and $null -ne $Exception.Data[$k] -and "$($Exception.Data[$k])" -ne '') { $entry[$k.Substring(0, 1).ToLowerInvariant() + $k.Substring(1)] = Protect-STMDiagText ([System.Net.WebUtility]::HtmlDecode([string]$Exception.Data[$k])) } } $inner = @(); $x = $Exception.InnerException while ($x -and $inner.Count -lt 5) { $inner += (Protect-STMDiagText "$($x.GetType().FullName): $($x.Message)"); $x = $x.InnerException } if ($inner.Count) { $entry.inner = $inner } if ($Stack) { $entry.stack = Protect-STMDiagText $Stack } $entry.signIn = [ordered]@{ backend = $script:STM.Backend; mode = $script:STM.Mode; appOnly = [bool]$script:STM.AppOnly; tenant = $script:STM.TenantId; clientId = $script:STM.ClientId } try { $Exception.Data['ErrorId'] = $id } catch { } if (-not $script:STM.Errors) { $script:STM.Errors = [System.Collections.Generic.List[object]]::new() } $script:STM.Errors.Add([pscustomobject]$entry) while ($script:STM.Errors.Count -gt 50) { $script:STM.Errors.RemoveAt(0) } try { Add-Content -LiteralPath (Join-Path (Get-STMDataRoot) 'errors.log') -Value ($entry | ConvertTo-Json -Compress -Depth 6) -Encoding utf8 } catch { } return $id } function ConvertFrom-STMTokenClaims { # Only the claims that say who the token is for and what it may do. The token itself is not returned or kept. param([string]$Token) if (-not $Token -or $Token -notmatch '\.') { return $null } $payload = $Token.Split('.')[1].Replace('-', '+').Replace('_', '/') switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } $c = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json $epoch = [DateTime]::new(1970, 1, 1, 0, 0, 0, [DateTimeKind]::Utc) [ordered]@{ audience = [string]$c.aud; tenant = [string]$c.tid; appId = [string]$c.appid; appName = [string]$c.app_displayname tokenType = if ($c.idtyp) { [string]$c.idtyp } elseif ($c.scp) { 'user' } else { 'app' } applicationPermissions = @($c.roles | Where-Object { $_ } | Sort-Object) delegatedPermissions = @(([string]$c.scp).Split(' ') | Where-Object { $_ } | Sort-Object) entraRoleIds = @($c.wids | Where-Object { $_ }) issuedUtc = if ($c.iat) { $epoch.AddSeconds([double]$c.iat).ToString('o') } else { '' } expiresUtc = if ($c.exp) { $epoch.AddSeconds([double]$c.exp).ToString('o') } else { '' } } } function Get-STMTokenCheck { # One small read (the first scope tag) to prove the sign-in works, plus what the token carries. Read-only. if ($script:STM.Backend -ne 'Graph') { return $null } $uri = "$(Get-STMGraphBase)/deviceManagement/roleScopeTags?`$top=1" $o = [ordered]@{ checkedUtc = [DateTime]::UtcNow.ToString('o'); request = "GET $uri"; ok = $false; status = 0; error = ''; graphCode = ''; requestId = ''; claims = $null } $req = $null; $resp = $null try { $resp = Invoke-MgGraphRequest -Method GET -Uri $uri -OutputType HttpResponseMessage -ErrorAction Stop } catch { $d = Get-STMHttpErrorDetail -ErrorRecord $_ $o.status = $d.Status; $o.requestId = $d.RequestId $o.error = $d.Body try { $req = $_.Exception.Response.RequestMessage } catch { } } if ($resp) { $o.status = [int]$resp.StatusCode; $o.ok = [bool]$resp.IsSuccessStatusCode; $req = $resp.RequestMessage if (-not $o.ok) { try { $o.error = [string]$resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } catch { } $o.requestId = Get-STMHeaderValue $resp 'request-id' } } if ($o.error) { $pe = ConvertFrom-STMGraphErrorBody -Body $o.error if ($pe.Message) { $o.error = $pe.Message } if ($pe.Code) { $o.graphCode = $pe.Code } if (-not $o.requestId -and $pe.RequestId) { $o.requestId = $pe.RequestId } $o.error = Protect-STMDiagText $o.error } try { if ($req -and $req.Headers.Authorization) { $o.claims = ConvertFrom-STMTokenClaims $req.Headers.Authorization.Parameter } } catch { } $req = $null return [pscustomobject]$o } function Get-STMTokenCheckView { $t = $script:STM.TokenCheck if (-not $t) { return $null } $short = [string]$t.error if ($short.Length -gt 300) { $short = $short.Substring(0, 300) + '...' } [ordered]@{ ok = [bool]$t.ok; status = [int]$t.status; error = $short; permissions = if ($t.claims) { @($t.claims.applicationPermissions) + @($t.claims.delegatedPermissions) } else { @() } } } function Get-STMDiagnosticsReport { <# Builds the support report, saves it in the data folder and returns its text and path. Holds no secret or token. #> param([switch]$NoTokenCheck) if ($script:STM.Backend -eq 'Graph' -and -not $NoTokenCheck) { try { $script:STM.TokenCheck = Get-STMTokenCheck } catch { } } $nl = "`r`n" $sb = [System.Text.StringBuilder]::new() $line = { param($k, $v) [void]$sb.Append(('{0,-26}{1}' -f ($k + ':'), $v) + $nl) } $head = { param($t) [void]$sb.Append($nl + '== ' + $t + ' ==' + $nl) } [void]$sb.Append('Intune Scope Tag Manager - diagnostics' + $nl) [void]$sb.Append('This report holds no password, client secret or token. Attach it to a support request.' + $nl) & $head 'Tool' & $line 'Version' $script:STM.Version & $line 'Edition' (Get-STMEdition) & $line 'Created (UTC)' ([DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss')) & $line 'Created (local)' ([DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss zzz')) & $line 'Computer OS' ([Environment]::OSVersion.VersionString) & $line 'PowerShell' ("$($PSVersionTable.PSVersion) $($PSVersionTable.PSEdition)") $g = $null; try { $g = Get-STMGraphModuleInfo } catch { } & $line 'Graph sign-in module' $(if ($g -and $g.installed) { "installed $($g.version)" } else { 'not installed' }) $all = @(Get-Module -ListAvailable -Name 'Microsoft.Graph.Authentication' -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Version)" }) if ($all.Count -gt 1) { & $line 'Graph versions found' ($all -join ', ') } $loaded = Get-Module -Name 'Microsoft.Graph.Authentication' if ($loaded) { & $line 'Graph version loaded' "$($loaded.Version)" } & $line 'Data folder' (Get-STMDataRoot) & $head 'Sign-in' & $line 'Signed in' ([bool]$script:STM.Backend) & $line 'Sign-in type' $(if (-not $script:STM.Backend) { '' } elseif ($script:STM.Backend -eq 'Mock') { 'sample data' } elseif ($script:STM.AppOnly) { "app (client secret or certificate), $(if (Test-STMAppCanWrite) { 'can write: ' + (@(Get-STMAppWritePermissions) -join ', ') } else { 'read-only' })" } else { "user ($($script:STM.Mode))" }) & $line 'Profile' $script:STM.Profile & $line 'Tenant id' $script:STM.TenantId & $line 'App (client) id' $script:STM.ClientId & $line 'Account' $script:STM.Account if ($script:STM.Backend -eq 'Graph') { $ctx = $null; try { $ctx = Get-MgContext } catch { } if ($ctx) { & $line 'Auth type' ([string]$ctx.AuthType) & $line 'Credential type' ([string]$ctx.TokenCredentialType) & $line 'Context scope' ([string]$ctx.ContextScope) & $line 'Cloud' ([string]$ctx.Environment) & $line 'Permissions (context)' ((@($ctx.Scopes) | Sort-Object) -join ', ') } else { & $line 'Graph context' 'none (the Graph sign-in is gone; sign in again)' } } if ($script:STM.MissingScopes -and @($script:STM.MissingScopes).Count) { & $line 'Missing permissions' (@($script:STM.MissingScopes) -join ', ') } if ($script:STM.RoleInfo) { & $line 'Intune or Entra roles' (@($script:STM.RoleInfo.Roles) -join ', ') } $t = $script:STM.TokenCheck if ($t) { & $head 'Test read (one scope tag)' & $line 'Checked (UTC)' $t.checkedUtc & $line 'Request' $t.request & $line 'Result' $(if ($t.ok) { "OK (HTTP $($t.status))" } else { "FAILED (HTTP $($t.status))" }) if ($t.graphCode) { & $line 'Graph error code' $t.graphCode } if ($t.error) { & $line 'Graph error' $t.error } if ($t.requestId) { & $line 'Request id' $t.requestId } if ($t.claims) { $c = $t.claims & $line 'Token audience' $c.audience & $line 'Token tenant' $c.tenant & $line 'Token app id' $c.appId & $line 'Token app name' $c.appName & $line 'Token type' $c.tokenType & $line 'App permissions' $(if (@($c.applicationPermissions).Count) { @($c.applicationPermissions) -join ', ' } else { '(none)' }) if ($c.tokenType -ne 'app') { & $line 'Delegated permissions' (@($c.delegatedPermissions) -join ', ') } & $line 'Token issued (UTC)' $c.issuedUtc & $line 'Token expires (UTC)' $c.expiresUtc if ($c.tenant -and $script:STM.TenantId -and $c.tenant -ne $script:STM.TenantId) { & $line 'WARNING' 'token tenant differs from the signed-in tenant' } if ($c.tokenType -eq 'app') { $need = 'DeviceManagementConfiguration.Read.All', 'DeviceManagementApps.Read.All', 'DeviceManagementRBAC.Read.All', 'DeviceManagementManagedDevices.Read.All' $have = @($c.applicationPermissions) $miss = @($need | Where-Object { $have -notcontains $_ -and $have -notcontains ($_ -replace 'Read\.All$', 'ReadWrite.All') }) & $line 'Intune app permissions' $(if ($miss.Count) { 'MISSING ' + ($miss -join ', ') } else { 'all present' }) if (-not @($c.applicationPermissions).Count) { & $line 'LIKELY CAUSE' 'The token has no application permissions, so Intune refuses every read (HTTP 401/403).' & $line 'FIX' 'Entra admin: on this app registration add the Intune Read.All permissions as Application (not Delegated) Microsoft Graph permissions, press Grant admin consent, then sign out of this tool and sign in again.' } } } else { & $line 'Token' 'could not be read (no token was issued, or the request never left this computer)' } } $ts = @($script:STM.TypeStatus.Values | Where-Object { $_.State -notin 'Loaded', 'NotLoaded', 'Loading', 'NotAvailable', 'AppSignInNotSupported', '' -and $_.State }) if ($ts.Count) { & $head 'Object types not loaded' foreach ($x in $ts) { [void]$sb.Append(('{0}: {1} {2}' -f $x.Label, $x.State, (Protect-STMDiagText ([string]$x.Error))) + $nl) } } & $head 'Recent errors (newest first)' $errs = @() if ($script:STM.Errors) { $errs = @($script:STM.Errors) } if (-not $errs.Count) { try { $f = Join-Path (Get-STMDataRoot) 'errors.log' if (Test-Path -LiteralPath $f) { $errs = @(Get-Content -LiteralPath $f -Tail 25 -Encoding utf8 | ForEach-Object { try { $_ | ConvertFrom-Json } catch { } }) } } catch { } } if (-not $errs.Count) { [void]$sb.Append('None recorded.' + $nl) } $n = 0 for ($i = $errs.Count - 1; $i -ge 0 -and $n -lt 25; $i--) { $e = $errs[$i]; $n++ [void]$sb.Append($nl + "[$($e.errorId)] $($e.timeUtc) $($e.source) $($e.route)" + $nl) foreach ($p in $e.PSObject.Properties) { if ($p.Name -in 'errorId', 'timeUtc', 'source', 'route') { continue } $v = if ($p.Value -is [System.Collections.IEnumerable] -and $p.Value -isnot [string]) { (@($p.Value) | ForEach-Object { if ($_ -is [string]) { $_ } else { ($_ | ConvertTo-Json -Compress -Depth 4) } }) -join ' | ' } elseif ($p.Value -is [pscustomobject] -or $p.Value -is [System.Collections.IDictionary]) { $p.Value | ConvertTo-Json -Compress -Depth 4 } else { [string]$p.Value } if ($v) { [void]$sb.Append((' {0,-18}{1}' -f ($p.Name + ':'), $v) + $nl) } } } $text = Protect-STMDiagText $sb.ToString() $dir = Join-Path (Get-STMDataRoot) 'Diagnostics' if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } $file = Join-Path $dir ('ScopeTagManager-Diagnostics_{0}.txt' -f [DateTime]::Now.ToString('yyyyMMdd-HHmmss')) [IO.File]::WriteAllText($file, $text, [Text.UTF8Encoding]::new($false)) Write-STMAudit -Event 'DiagnosticsSaved' -Data @{ file = $file } return [ordered]@{ text = $text; path = $file; folder = $dir } } |