Skip to content

Enforce CA5394 (insecure randomness) for shipping code - #39517

Merged
kubaflo merged 2 commits into
mainfrom
rolfbjarne-ca5394-insecure-randomness-guard
Nov 17, 2026
Merged

kubaflo merged 2 commits into
mainfrom
rolfbjarne-ca5394-insecure-randomness-guard

Conversation

@rolfbjarne

@rolfbjarne rolfbjarne commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description of Change

Enable the CA5394 analyzer ("Do not use insecure randomness") as an error for shipping code, so that a future use of System.Random there fails the build. Nothing guards against that today: CA5394 is off by default and isn't configured anywhere in the repo.

The change is 11 lines in .editorconfig:

  • dotnet_diagnostic.CA5394.severity = error, next to the other analyzer rules. It is error instead of warning because the CI Build stage (/p:TreatWarningsAsErrors=false), the Helix unit test stage (-warnAsError 0) and the macOS pack (-warnAsError false) don't fail on warnings, so a warning would go unnoticed there. The neighbouring rules are error as well.
  • CA5394 is set to none for src/**/{test,tests,samples}/**.cs and src/TestUtils/**.cs, because tests, samples, benchmarks and the test infrastructure use System.Random to generate test data. This follows the existing XamlTypeInfo.g.cs override at the end of the file.

The exemptions are path based instead of using the SampleProject and MauiTestProject properties that gate eng/BannedApis.targets, because those aren't set on many test projects (for example Controls.Core.UnitTests, Controls.Xaml.UnitTests, Core.Benchmarks, Essentials.UnitTests and Graphics.Tests). A new directory that isn't exempted is guarded by default.

The analyzer already runs for every shipping project on all of its target frameworks, including netstandard2.0 and netstandard2.1, because eng/BannedApis.targets references the Microsoft.CodeAnalysis.NetAnalyzers package.

CA5394 reports invocations of System.Random instance methods (Next, NextDouble, NextBytes, Random.Shared.Next, Shuffle, ...). It doesn't report new Random() on its own, method groups, other random number generators, or generated code (so not the C# in .razor files either).

Without the exemptions CA5394 reports the invocations below, none of them in shipping code, and it would fail the builds that run with TreatWarningsAsErrors=true: the UI test host app, the device tests and the integration tests that build the samples.

Project Diagnostics
Controls.Sample 103
Controls.TestCases.HostApp 69
Core.Benchmarks 7
Controls.ManualTests 7
Controls.Core.UnitTests 2
Controls.DeviceTests 2
Core.UnitTests 2
Controls.Xaml.UnitTests 1
Total 193

I measured these on net11.0. For main they are derived from the source, not measured: all 193 reported lines are still in the same files, unchanged, and the 60 test, sample and benchmark files that mention Random have no new line that mentions it.

The only other use of System.Random outside tests and samples is Weather.razor in the maui-blazor and maui-blazor-solution templates, which calls Random.Shared.Next. These are dotnet new template sources that no project in this repository compiles, and CA5394 doesn't analyze Razor-generated code anyway, so it doesn't affect a build.

Validation

First on net11.0 (4b41c78), before rebasing onto main. macOS, .NET SDK 11.0.100-rtm.26514.118, Xcode 27.0. The iOS and MacCatalyst target frameworks were built; Android, Windows and Tizen were not.

  • Microsoft.Maui-mac.slnf with CA5394 as a warning, no exemptions, and a new Random().Next() injected into every compilation to prove the analyzer runs: it was reported in all 52 compilations of the shipping projects (16 projects, every target framework built). With the default TreatWarningsAsErrors=true the build failed with 186 CA5394 errors in 7 projects.
  • With this change, the same solution filter built with -p:TreatWarningsAsErrors=false succeeded without any CA5394 diagnostics, and with the default TreatWarningsAsErrors=true there were no CA5394 diagnostics either (on net11.0 that build still failed on 18 unrelated RS0030 errors from the AddHandler ban).
  • With this change, a new Random().Next() added to src/Core/src, src/Essentials/src or src/SingleProject/Resizetizer/src fails with error CA5394 on every target framework (netstandard2.0, netstandard2.1, net11.0, iOS, MacCatalyst), also with TreatWarningsAsErrors=false. The same call in src/Core/tests, src/Essentials/test, src/Graphics/tests, src/TestUtils/src or src/Controls/samples isn't reported.

Then on main (9f607de), after the rebase. Built with the repo-local .NET 11 SDK (main still pinned 10.0.113 then), and with the platform target frameworks excluded (-p:Include{Ios,Android,MacCatalyst,Windows,Tizen,MacOS}TargetFrameworks=false -p:TreatWarningsAsErrors=false):

  • dotnet build src/Graphics/src/Graphics/Graphics.csproj with a new Random().Next() added: error CA5394 on net10.0, netstandard2.0 and netstandard2.1.
  • dotnet build src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj with the same call added: succeeded, no diagnostics. With the exemption for tests temporarily set to error, the call is reported, so the exemption is what silences it.

After merging main again (8744f99) I didn't rebuild locally. I searched the merged tree instead: apart from the two Weather.razor files, no file outside the exempt paths mentions Random.

Not run: the Android, Windows and Tizen target frameworks, the complete solution build on main and the pipelines. CI will cover those.

Issues Fixed

None. This adds a guard; there is no bug report.

System.Random is not a cryptographically secure random number generator,
and nothing in the repository guards against it being used in shipping
code: CA5394 is disabled by default and not configured anywhere.

Enable CA5394 as an error, like the other analyzer rules in this block (so
that it is not silently downgraded by the pipelines that build with
TreatWarningsAsErrors=false), and exempt tests, samples, benchmarks and the
test infrastructure by path, because they use System.Random to generate
test data.

The analyzer already runs for every shipping project on every target
framework, including netstandard2.0 and netstandard2.1, because
eng/BannedApis.targets references the Microsoft.CodeAnalysis.NetAnalyzers
package.

Enabling the rule without the exemptions reports 193 invocations in 8
projects, none of them shipping code, and would fail the builds that run
with TreatWarningsAsErrors=true (the UI test host app, the device tests and
the integration sample builds):

| Project                    | Diagnostics |
|----------------------------|-------------|
| Controls.Sample            |         103 |
| Controls.TestCases.HostApp |          69 |
| Core.Benchmarks            |           7 |
| Controls.ManualTests       |           7 |
| Controls.Core.UnitTests    |           2 |
| Controls.DeviceTests       |           2 |
| Core.UnitTests             |           2 |
| Controls.Xaml.UnitTests    |           1 |

With the exemptions the Microsoft.Maui-mac.slnf build has no CA5394
diagnostics, and a System.Random call added to Core, Essentials or
Resizetizer fails the build on all of their target frameworks, also with
TreatWarningsAsErrors=false.

Known gap: CA5394 does not analyze generated code, so System.Random calls
in .razor files (for example the Blazor templates' Weather.razor) are not
reported.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39517

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39517"

@azure-pipelines

This comment has been minimized.

@github-actions github-actions Bot added the area-infrastructure CI, Maestro / Coherency, upstream dependencies/versions label Oct 21, 2026
@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 21, 2026
@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@rolfbjarne
rolfbjarne marked this pull request as ready for review November 17, 2026 13:29
Copilot AI balanced review requested due to automatic review settings November 17, 2026 13:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the build-time insecure-randomness safeguard.

No open issues 🎉

What changed in this PR

Adds a build-time safeguard against insecure randomness in .NET MAUI shipping code without changing runtime behavior.

Changes:

  • Enables CA5394 as an error, so reported System.Random calls fail builds even when warnings are not treated as errors.
  • Adds path-based exemptions for tests, samples, benchmarks, and test infrastructure, with comments explaining the policy.
File Description
.editorconfig Enables CA5394 enforcement and exempts test, sample, benchmark, and test-infrastructure source paths.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 17, 2026 13:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

There are no active review issues for the CA5394 configuration change.

No open issues 🎉

Review effort: Balanced

@kubaflo

kubaflo commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

/rebase

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@rolfbjarne — test-failure analysis for commit b54b39a.

Scope CI failures Commit b54b39a


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

🧪 maui-pr-uitests

CA5394-only changes leave runtime code unchanged. Target history is truncated; absent matches remain unresolved.


🧭 Follow-up — actions and refresh

Next action: Recover untruncated target diagnostics for unresolved failures; verify iOS Helix completion.

Maintainers: comment /review tests to refresh this report.

@kubaflo
kubaflo merged commit 9ae16b8 into main Nov 17, 2026
169 of 184 checks passed
@kubaflo
kubaflo deleted the rolfbjarne-ca5394-insecure-randomness-guard branch November 17, 2026 19:31
devanathan-vaithiyanathan pushed a commit to devanathan-vaithiyanathan/maui that referenced this pull request Nov 18, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Enable the CA5394 analyzer ("Do not use insecure randomness") as an
error for shipping code, so that a future use of `System.Random` there
fails the build. Nothing guards against that today: CA5394 is off by
default and isn't configured anywhere in the repo.

The change is 11 lines in `.editorconfig`:

- `dotnet_diagnostic.CA5394.severity = error`, next to the other
analyzer rules. It is `error` instead of `warning` because the CI Build
stage (`/p:TreatWarningsAsErrors=false`), the Helix unit test stage
(`-warnAsError 0`) and the macOS pack (`-warnAsError false`) don't fail
on warnings, so a warning would go unnoticed there. The neighbouring
rules are `error` as well.
- CA5394 is set to `none` for `src/**/{test,tests,samples}/**.cs` and
`src/TestUtils/**.cs`, because tests, samples, benchmarks and the test
infrastructure use `System.Random` to generate test data. This follows
the existing `XamlTypeInfo.g.cs` override at the end of the file.

The exemptions are path based instead of using the `SampleProject` and
`MauiTestProject` properties that gate `eng/BannedApis.targets`, because
those aren't set on many test projects (for example
`Controls.Core.UnitTests`, `Controls.Xaml.UnitTests`, `Core.Benchmarks`,
`Essentials.UnitTests` and `Graphics.Tests`). A new directory that isn't
exempted is guarded by default.

The analyzer already runs for every shipping project on all of its
target frameworks, including netstandard2.0 and netstandard2.1, because
`eng/BannedApis.targets` references the
`Microsoft.CodeAnalysis.NetAnalyzers` package.

CA5394 reports invocations of `System.Random` instance methods (`Next`,
`NextDouble`, `NextBytes`, `Random.Shared.Next`, `Shuffle`, ...). It
doesn't report `new Random()` on its own, method groups, other random
number generators, or generated code (so not the C# in `.razor` files
either).

Without the exemptions CA5394 reports the invocations below, none of
them in shipping code, and it would fail the builds that run with
`TreatWarningsAsErrors=true`: the UI test host app, the device tests and
the integration tests that build the samples.

| Project                    | Diagnostics |
|----------------------------|------------:|
| Controls.Sample            |         103 |
| Controls.TestCases.HostApp |          69 |
| Core.Benchmarks            |           7 |
| Controls.ManualTests       |           7 |
| Controls.Core.UnitTests    |           2 |
| Controls.DeviceTests       |           2 |
| Core.UnitTests             |           2 |
| Controls.Xaml.UnitTests    |           1 |
| Total                      |         193 |

I measured these on net11.0. For main they are derived from the source,
not measured: all 193 reported lines are still in the same files,
unchanged, and the 60 test, sample and benchmark files that mention
`Random` have no new line that mentions it.

The only other use of `System.Random` outside tests and samples is
`Weather.razor` in the `maui-blazor` and `maui-blazor-solution`
templates, which calls `Random.Shared.Next`. These are `dotnet new`
template sources that no project in this repository compiles, and CA5394
doesn't analyze Razor-generated code anyway, so it doesn't affect a
build.

### Validation

First on net11.0 (4b41c78), before rebasing onto main. macOS, .NET
SDK 11.0.100-rtm.26514.118, Xcode 27.0. The iOS and MacCatalyst target
frameworks were built; Android, Windows and Tizen were not.

- `Microsoft.Maui-mac.slnf` with CA5394 as a `warning`, no exemptions,
and a `new Random().Next()` injected into every compilation to prove the
analyzer runs: it was reported in all 52 compilations of the shipping
projects (16 projects, every target framework built). With the default
`TreatWarningsAsErrors=true` the build failed with 186 CA5394 errors in
7 projects.
- With this change, the same solution filter built with
`-p:TreatWarningsAsErrors=false` succeeded without any CA5394
diagnostics, and with the default `TreatWarningsAsErrors=true` there
were no CA5394 diagnostics either (on net11.0 that build still failed on
18 unrelated RS0030 errors from the `AddHandler` ban).
- With this change, a `new Random().Next()` added to `src/Core/src`,
`src/Essentials/src` or `src/SingleProject/Resizetizer/src` fails with
`error CA5394` on every target framework (netstandard2.0,
netstandard2.1, net11.0, iOS, MacCatalyst), also with
`TreatWarningsAsErrors=false`. The same call in `src/Core/tests`,
`src/Essentials/test`, `src/Graphics/tests`, `src/TestUtils/src` or
`src/Controls/samples` isn't reported.

Then on main (9f607de), after the rebase. Built with the repo-local
.NET 11 SDK (main still pinned 10.0.113 then), and with the platform
target frameworks excluded
(`-p:Include{Ios,Android,MacCatalyst,Windows,Tizen,MacOS}TargetFrameworks=false
-p:TreatWarningsAsErrors=false`):

- `dotnet build src/Graphics/src/Graphics/Graphics.csproj` with a `new
Random().Next()` added: `error CA5394` on net10.0, netstandard2.0 and
netstandard2.1.
- `dotnet build src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj`
with the same call added: succeeded, no diagnostics. With the exemption
for tests temporarily set to `error`, the call is reported, so the
exemption is what silences it.

After merging main again (8744f99) I didn't rebuild locally. I
searched the merged tree instead: apart from the two `Weather.razor`
files, no file outside the exempt paths mentions `Random`.

Not run: the Android, Windows and Tizen target frameworks, the complete
solution build on main and the pipelines. CI will cover those.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None. This adds a guard; there is no bug report.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
@kubaflo kubaflo mentioned this pull request Nov 18, 2026
1 task
@kubaflo kubaflo added this to the .NET 11 SR2 milestone Nov 24, 2026
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Enable the CA5394 analyzer ("Do not use insecure randomness") as an
error for shipping code, so that a future use of `System.Random` there
fails the build. Nothing guards against that today: CA5394 is off by
default and isn't configured anywhere in the repo.

The change is 11 lines in `.editorconfig`:

- `dotnet_diagnostic.CA5394.severity = error`, next to the other
analyzer rules. It is `error` instead of `warning` because the CI Build
stage (`/p:TreatWarningsAsErrors=false`), the Helix unit test stage
(`-warnAsError 0`) and the macOS pack (`-warnAsError false`) don't fail
on warnings, so a warning would go unnoticed there. The neighbouring
rules are `error` as well.
- CA5394 is set to `none` for `src/**/{test,tests,samples}/**.cs` and
`src/TestUtils/**.cs`, because tests, samples, benchmarks and the test
infrastructure use `System.Random` to generate test data. This follows
the existing `XamlTypeInfo.g.cs` override at the end of the file.

The exemptions are path based instead of using the `SampleProject` and
`MauiTestProject` properties that gate `eng/BannedApis.targets`, because
those aren't set on many test projects (for example
`Controls.Core.UnitTests`, `Controls.Xaml.UnitTests`, `Core.Benchmarks`,
`Essentials.UnitTests` and `Graphics.Tests`). A new directory that isn't
exempted is guarded by default.

The analyzer already runs for every shipping project on all of its
target frameworks, including netstandard2.0 and netstandard2.1, because
`eng/BannedApis.targets` references the
`Microsoft.CodeAnalysis.NetAnalyzers` package.

CA5394 reports invocations of `System.Random` instance methods (`Next`,
`NextDouble`, `NextBytes`, `Random.Shared.Next`, `Shuffle`, ...). It
doesn't report `new Random()` on its own, method groups, other random
number generators, or generated code (so not the C# in `.razor` files
either).

Without the exemptions CA5394 reports the invocations below, none of
them in shipping code, and it would fail the builds that run with
`TreatWarningsAsErrors=true`: the UI test host app, the device tests and
the integration tests that build the samples.

| Project                    | Diagnostics |
|----------------------------|------------:|
| Controls.Sample            |         103 |
| Controls.TestCases.HostApp |          69 |
| Core.Benchmarks            |           7 |
| Controls.ManualTests       |           7 |
| Controls.Core.UnitTests    |           2 |
| Controls.DeviceTests       |           2 |
| Core.UnitTests             |           2 |
| Controls.Xaml.UnitTests    |           1 |
| Total                      |         193 |

I measured these on net11.0. For main they are derived from the source,
not measured: all 193 reported lines are still in the same files,
unchanged, and the 60 test, sample and benchmark files that mention
`Random` have no new line that mentions it.

The only other use of `System.Random` outside tests and samples is
`Weather.razor` in the `maui-blazor` and `maui-blazor-solution`
templates, which calls `Random.Shared.Next`. These are `dotnet new`
template sources that no project in this repository compiles, and CA5394
doesn't analyze Razor-generated code anyway, so it doesn't affect a
build.

### Validation

First on net11.0 (4b41c78), before rebasing onto main. macOS, .NET
SDK 11.0.100-rtm.26514.118, Xcode 27.0. The iOS and MacCatalyst target
frameworks were built; Android, Windows and Tizen were not.

- `Microsoft.Maui-mac.slnf` with CA5394 as a `warning`, no exemptions,
and a `new Random().Next()` injected into every compilation to prove the
analyzer runs: it was reported in all 52 compilations of the shipping
projects (16 projects, every target framework built). With the default
`TreatWarningsAsErrors=true` the build failed with 186 CA5394 errors in
7 projects.
- With this change, the same solution filter built with
`-p:TreatWarningsAsErrors=false` succeeded without any CA5394
diagnostics, and with the default `TreatWarningsAsErrors=true` there
were no CA5394 diagnostics either (on net11.0 that build still failed on
18 unrelated RS0030 errors from the `AddHandler` ban).
- With this change, a `new Random().Next()` added to `src/Core/src`,
`src/Essentials/src` or `src/SingleProject/Resizetizer/src` fails with
`error CA5394` on every target framework (netstandard2.0,
netstandard2.1, net11.0, iOS, MacCatalyst), also with
`TreatWarningsAsErrors=false`. The same call in `src/Core/tests`,
`src/Essentials/test`, `src/Graphics/tests`, `src/TestUtils/src` or
`src/Controls/samples` isn't reported.

Then on main (9f607de), after the rebase. Built with the repo-local
.NET 11 SDK (main still pinned 10.0.113 then), and with the platform
target frameworks excluded
(`-p:Include{Ios,Android,MacCatalyst,Windows,Tizen,MacOS}TargetFrameworks=false
-p:TreatWarningsAsErrors=false`):

- `dotnet build src/Graphics/src/Graphics/Graphics.csproj` with a `new
Random().Next()` added: `error CA5394` on net10.0, netstandard2.0 and
netstandard2.1.
- `dotnet build src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj`
with the same call added: succeeded, no diagnostics. With the exemption
for tests temporarily set to `error`, the call is reported, so the
exemption is what silences it.

After merging main again (8744f99) I didn't rebuild locally. I
searched the merged tree instead: apart from the two `Weather.razor`
files, no file outside the exempt paths mentions `Random`.

Not run: the Android, Windows and Tizen target frameworks, the complete
solution build on main and the pipelines. CI will cover those.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None. This adds a guard; there is no bug report.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-infrastructure CI, Maestro / Coherency, upstream dependencies/versions s/agent-review-in-progress AI review is currently running for this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants