diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 index 628513e899..86eddea483 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 @@ -68,7 +68,10 @@ # by a link title (`[name](url "title")`). $linkPattern = '\[(?(?:[^\[\]]|\[[^\[\]]*\])+)\]\((?https://[^)\s]+)(?:\s+"[^"]*")?\)|(?https://[^\s)\]]+)' # Markdown backslash escapes (\( \_ \* ...) that result markdown adds around display names. - $markdownEscape = '\\([\\`*_{}\[\]()#+\-.!|<>])' + # Must stay a superset of what Get-MtSafeMarkdown escapes, or a name keeps a literal + # backslash on the affected-objects page. `:` and `@` were added there for GFM autolink + # literals; `~` has been escaped by the helper for longer and was missing here too. + $markdownEscape = '\\([\\`*_{}\[\]()#+\-.!|<>~:@])' foreach ($link in [regex]::Matches($Markdown, $linkPattern)) { $url = $link.Groups['url'].Value diff --git a/powershell/public/report/Get-MtSafeMarkdown.ps1 b/powershell/public/report/Get-MtSafeMarkdown.ps1 index eada50f4ce..436d6d251a 100644 --- a/powershell/public/report/Get-MtSafeMarkdown.ps1 +++ b/powershell/public/report/Get-MtSafeMarkdown.ps1 @@ -11,8 +11,11 @@ named '![x](https://attacker.example/pixel.png)' or '[Sign in again](https://phish.example)' would be rendered by the report as a remote image or a clickable link, and a '|' would break table layout. - Characters with meaning in markdown are backslash-escaped and line breaks are replaced with spaces, - so the value is displayed exactly as entered. + Characters with meaning in markdown are backslash-escaped, and so are the ones that make GFM + turn text into a link on its own: a bare 'https://host', 'ftp://host', 'www.host', 'a@b' or + 'mailto:a@b' is an autolink literal, not markdown syntax, and the report renders with + 'gfm: true'. Line breaks are replaced with spaces. Every backslash added here is consumed by + the renderer, so the value is displayed exactly as entered. .PARAMETER Text The text to escape @@ -44,6 +47,21 @@ # Keep values on a single line so they can't start new markdown blocks or table rows. $Text = $Text -replace '\r\n|\r|\n', ' ' - # A single pass, so backslashes added here are never escaped again. - $Text -replace '([\\`*_\[\]()!|<>~])', '\$1' + # Two passes, and the order matters. The first escapes every character that is either + # markdown syntax or part of an autolink literal; it runs once, so the backslashes it + # adds are never escaped again. The second handles the one autolink form that contains + # no such character: GFM links a bare `www.host`, so the dot after `www` is escaped + # too. It cannot double-escape, because it only ever matches a dot. There is + # deliberately no word boundary before `www`: GFM accepts `_` immediately before the + # `www.`, and `_` is a word character, so `\bwww` does not match `_www.` - the first + # pass escapes the underscore, the renderer consumes that backslash, and the link comes + # back. Escaping the dot in any `www.` is harmless: in `awww.host`, which GFM does not + # autolink anyway, the extra backslash is consumed by the renderer. + # + # `:` and `@` are not markdown syntax. They are here because the report renders with + # `gfm: true`, so `https://host`, `ftp://host`, `mailto:a@b` and a bare `a@b` in a + # tenant-controlled name each render as a live link without them. A plain `contoso.com` + # is deliberately left alone: GFM does not autolink it, and escaping every dot would be + # noise in the JSON output for no gain. + ($Text -replace '([\\`*_\[\]()!|<>~:@])', '\$1') -replace '(?<=www)\.', '\.' } diff --git a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 index 43aab858b5..ea1a192dd6 100644 --- a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 +++ b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 @@ -13,7 +13,9 @@ $link = Get-GraphObjectMarkdown -GraphObjects $policy -GraphObjectType ConditionalAccess -AsPlainTextLink - $link | Should -BeLike '`[Microsoft-managed: A \`[B\`] \| C`](*PolicyBlade/policyId/00000000-0000-0000-0000-000000000001)' + # The colon is escaped now: GFM would otherwise autolink a scheme inside a tenant name. + # It renders as a plain colon, so the reader sees the name unchanged. + $link | Should -BeLike '`[Microsoft-managed\: A \`[B\`] \| C`](*PolicyBlade/policyId/00000000-0000-0000-0000-000000000001)' } It 'keeps a plain display name unchanged in the list form' { diff --git a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 index dc867c0837..86d42d3f8f 100644 --- a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 +++ b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 @@ -185,6 +185,30 @@ Describe 'Affected objects' { $affectedObject.DisplayName | Should -Be 'AzMfa Test (Require MFA) test_21783' } + It 'Should remove every escape Get-MtSafeMarkdown adds, not a subset' { + # The parser's pattern has to stay a superset of the helper's, or a name keeps a + # literal backslash on the affected-objects page. This drives the whole set through + # both sides rather than naming a few characters, so adding one to the helper without + # adding it here fails this case instead of reaching the page. + # Every character Get-MtSafeMarkdown escapes, except '[' and ']'. Those two are left out + # for a reason that is not the unescape pattern: $linkPattern admits at most one level of + # brackets in a name, so an escaped bracket breaks the link match before the unescape is + # ever reached. That is a pre-existing limit of the link pattern and is unchanged here. + $chars = @('\', '`', '*', '_', '(', ')', '!', '|', '<', '>', '~', ':', '@') + foreach ($c in $chars) { + $nombre = InModuleScope Maester -Parameters @{ C = $c } { + param($C) + Get-MtSafeMarkdown ("Contoso" + $C + "App") + } + $markdown = "- [$nombre](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/44444444-4444-4444-4444-444444444444)" + $affectedObject = InModuleScope Maester -Parameters @{ Markdown = $markdown } { + param($Markdown) + Get-MtAffectedObjectFromMarkdown -Markdown $Markdown + } + $affectedObject.DisplayName | Should -Be ("Contoso" + $C + "App") -Because "the escape of [$c] must round-trip" + } + } + It 'Should capture an enterprise application linked by object id only' { $markdown = '- [Mailbox Migration Account](https://portal.azure.com/#view/Microsoft_AAD_IAM/ManagedAppMenuBlade/~/Overview/objectId/55555555-5555-5555-5555-555555555555) with Global Administrator' diff --git a/powershell/tests/functions/Get-MtSafeMarkdown.Tests.ps1 b/powershell/tests/functions/Get-MtSafeMarkdown.Tests.ps1 index 9b37b2047e..e0efa0b1e7 100644 --- a/powershell/tests/functions/Get-MtSafeMarkdown.Tests.ps1 +++ b/powershell/tests/functions/Get-MtSafeMarkdown.Tests.ps1 @@ -9,8 +9,8 @@ } It 'Escapes markdown syntax: ' -ForEach @( - @{ Text = '![x](https://attacker.example/p.png)'; Expected = '\!\[x\]\(https://attacker.example/p.png\)' } - @{ Text = '[Sign in](https://phish.example)'; Expected = '\[Sign in\]\(https://phish.example\)' } + @{ Text = '![x](https://attacker.example/p.png)'; Expected = '\!\[x\]\(https\://attacker.example/p.png\)' } + @{ Text = '[Sign in](https://phish.example)'; Expected = '\[Sign in\]\(https\://phish.example\)' } @{ Text = 'a | b'; Expected = 'a \| b' } @{ Text = '**bold** _em_ ~~del~~ `code`'; Expected = '\*\*bold\*\* \_em\_ \~\~del\~\~ \`code\`' } @{ Text = ''; Expected = '\' } @@ -19,6 +19,48 @@ Get-MtSafeMarkdown $Text | Should -BeExactly $Expected } + # GFM autolink literals are not markdown syntax, but the report renders with + # `gfm: true`, so a bare URL, a `www.` host or an email in a tenant-controlled + # name becomes a live link. The escapes below are consumed by the renderer, so + # the reader sees the original text. + It 'Escapes GFM autolink literals: ' -ForEach @( + @{ Text = 'Sign in at https://phish.example/login'; Expected = 'Sign in at https\://phish.example/login' } + @{ Text = 'Sign in at http://phish.example/login'; Expected = 'Sign in at http\://phish.example/login' } + @{ Text = 'Get it at ftp://phish.example/x'; Expected = 'Get it at ftp\://phish.example/x' } + @{ Text = 'Sign in at www.phish.example/login'; Expected = 'Sign in at www\.phish.example/login' } + @{ Text = 'Contact admin@phish.example'; Expected = 'Contact admin\@phish.example' } + @{ Text = 'Write to mailto:admin@phish.example'; Expected = 'Write to mailto\:admin\@phish.example' } + # Escaped case-insensitively on purpose. marked 18 does not autolink `WWW.` + # today, but a backslash the renderer consumes costs nothing, and this does + # not depend on that staying true. + @{ Text = 'WWW.contoso.com'; Expected = 'WWW\.contoso.com' } + # GFM accepts `_` immediately before the `www.`, and `_` is a word character, so a + # word boundary before `www` does not match `_www.`: the first pass escapes the + # underscore, the renderer consumes that backslash, and the autolink comes back. + # Reported by @SamErde on #2715 with a Marked + DOMPurify reproduction. + @{ Text = '_www.phish.example/login'; Expected = '\_www\.phish.example/login' } + @{ Text = 'a_www.phish.example/login'; Expected = 'a\_www\.phish.example/login' } + # The other characters GFM accepts in that position, for the same reason. + @{ Text = '*www.phish.example'; Expected = '\*www\.phish.example' } + @{ Text = '~www.phish.example'; Expected = '\~www\.phish.example' } + @{ Text = '(www.phish.example'; Expected = '\(www\.phish.example' } + # Over-escaped on purpose: GFM does not autolink `awww.`, but the backslash is + # consumed by the renderer, so covering it costs nothing and keeps the rule simple. + @{ Text = 'awww.host'; Expected = 'awww\.host' } + ) { + Get-MtSafeMarkdown $Text | Should -BeExactly $Expected + } + + It 'Leaves a plain host alone, so the escape does not widen to every dot: ' -ForEach @( + @{ Text = 'Cuenta de contoso.com' } + @{ Text = 'mail.contoso.com' } + ) { + # GFM only autolinks a host when it starts with `www.`, so a plain domain needs + # no escaping. This guards the new rule from growing into every dot in every + # tenant name, which would be noise in the JSON output for no benefit. + Get-MtSafeMarkdown $Text | Should -BeExactly $Text + } + It 'Replaces line breaks so values stay on one line' { Get-MtSafeMarkdown "line1`r`n| --- |`nline3" | Should -BeExactly 'line1 \| --- \| line3' } diff --git a/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 b/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 index 6d349f6744..efcb91bab4 100644 --- a/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 @@ -321,7 +321,9 @@ Describe 'CISA.MS.EXO.4.1 with DNS mocked' { Test-MtCisaDmarcRecordExist | Should -BeTrue - $script:testResultMarkdown | Should -BeLike '*rua=mailto:a@contoso.com\!10m\|$1 |*' + # `mailto:` and the address are escaped now. A DMARC record is tenant-controlled text, + # and GFM autolinked both forms; escaped, it reads the same and no longer renders as a link. + $script:testResultMarkdown | Should -BeLike '*rua=mailto\:a\@contoso.com\!10m\|$1 |*' } It 'skips when no DNS resolver is available' { diff --git a/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 index 525dec0a8e..f98f9d470c 100644 --- a/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 @@ -69,7 +69,7 @@ } Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse - $script:TestResult | Should -Match 'alice@contoso.com' + $script:TestResult | Should -Match 'alice\\?@contoso\.com' $script:TestResult | Should -Match 'atRisk' } @@ -90,7 +90,7 @@ Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse $script:TestResult | Should -Not -Match '\| \[Sign in again\]\(' - $script:TestResult | Should -Match ([regex]::Escape('\[Sign in again\]\(https://phish.example\)')) + $script:TestResult | Should -Match ([regex]::Escape('\[Sign in again\]\(https\://phish.example\)')) } It 'fails when a high-risk user is confirmedCompromised (must not be treated as remediated)' { @@ -111,7 +111,7 @@ } Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse - $script:TestResult | Should -Match 'bob@contoso.com' + $script:TestResult | Should -Match 'bob\\?@contoso\.com' $script:TestResult | Should -Match 'confirmedCompromised' } @@ -152,8 +152,8 @@ } Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse - $script:TestResult | Should -Match 'alice@contoso.com' - $script:TestResult | Should -Not -Match 'carol@contoso.com' + $script:TestResult | Should -Match 'alice\\?@contoso\.com' + $script:TestResult | Should -Not -Match 'carol\\?@contoso\.com' $script:TestResult | Should -Match 'Found 1 high-risk' } @@ -213,7 +213,10 @@ $script:TestResult | Should -Match 'Global Administrator' $script:TestResult | Should -Match '1 of them hold a privileged directory role' # The privileged user is listed first. - $script:TestResult.IndexOf('bob@contoso.com') | Should -BeLessThan $script:TestResult.IndexOf('alice@contoso.com') + # Matched as a regex rather than IndexOf, so the position is found whether or not the + # escaping helper put a backslash before the @. + [regex]::Match($script:TestResult, 'bob\\?@contoso\.com').Index | + Should -BeLessThan ([regex]::Match($script:TestResult, 'alice\\?@contoso\.com').Index) } It 'treats a PIM-eligible privileged role as privileged' { @@ -255,7 +258,7 @@ Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { throw 'Forbidden' } Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse - $script:TestResult | Should -Match 'alice@contoso.com' + $script:TestResult | Should -Match 'alice\\?@contoso\.com' $script:TestResult | Should -Match 'privileged users were not identified' $script:Severity | Should -BeNullOrEmpty }