Repository navigation
Enforce CA5394 (insecure randomness) for shipping code - #39517
Conversation
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>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39517Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39517" |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟢 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.Randomcalls 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
|
/rebase |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Tests Failure Analysis
🧪 CI Analysis — click to expand📊 maui-prNo failures found. 🧪 maui-pr-devicetests
🧪 maui-pr-uitestsCA5394-only changes leave runtime code unchanged. Target history is truncated; absent matches remain unresolved.
🧭 Follow-up — actions and refreshNext action: Recover untruncated target diagnostics for unresolved failures; verify iOS Helix completion.
|
<!-- 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>
<!-- 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>
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.Randomthere 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 iserrorinstead ofwarningbecause 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 areerroras well.noneforsrc/**/{test,tests,samples}/**.csandsrc/TestUtils/**.cs, because tests, samples, benchmarks and the test infrastructure useSystem.Randomto generate test data. This follows the existingXamlTypeInfo.g.csoverride at the end of the file.The exemptions are path based instead of using the
SampleProjectandMauiTestProjectproperties that gateeng/BannedApis.targets, because those aren't set on many test projects (for exampleControls.Core.UnitTests,Controls.Xaml.UnitTests,Core.Benchmarks,Essentials.UnitTestsandGraphics.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.targetsreferences theMicrosoft.CodeAnalysis.NetAnalyzerspackage.CA5394 reports invocations of
System.Randominstance methods (Next,NextDouble,NextBytes,Random.Shared.Next,Shuffle, ...). It doesn't reportnew Random()on its own, method groups, other random number generators, or generated code (so not the C# in.razorfiles 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.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
Randomhave no new line that mentions it.The only other use of
System.Randomoutside tests and samples isWeather.razorin themaui-blazorandmaui-blazor-solutiontemplates, which callsRandom.Shared.Next. These aredotnet newtemplate 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.slnfwith CA5394 as awarning, no exemptions, and anew 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 defaultTreatWarningsAsErrors=truethe build failed with 186 CA5394 errors in 7 projects.-p:TreatWarningsAsErrors=falsesucceeded without any CA5394 diagnostics, and with the defaultTreatWarningsAsErrors=truethere were no CA5394 diagnostics either (on net11.0 that build still failed on 18 unrelated RS0030 errors from theAddHandlerban).new Random().Next()added tosrc/Core/src,src/Essentials/srcorsrc/SingleProject/Resizetizer/srcfails witherror CA5394on every target framework (netstandard2.0, netstandard2.1, net11.0, iOS, MacCatalyst), also withTreatWarningsAsErrors=false. The same call insrc/Core/tests,src/Essentials/test,src/Graphics/tests,src/TestUtils/srcorsrc/Controls/samplesisn'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.csprojwith anew Random().Next()added:error CA5394on net10.0, netstandard2.0 and netstandard2.1.dotnet build src/Graphics/tests/Graphics.Tests/Graphics.Tests.csprojwith the same call added: succeeded, no diagnostics. With the exemption for tests temporarily set toerror, 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.razorfiles, no file outside the exempt paths mentionsRandom.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.