Use CryptographicallySecureRandomBytes for Guid generation (#42770)
authorJan Kotas <jkotas@microsoft.com>
Mon, 28 Sep 2020 01:52:38 +0000 (18:52 -0700)
committerGitHub <noreply@github.com>
Mon, 28 Sep 2020 01:52:38 +0000 (18:52 -0700)
Fixes #42752

src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetRandomBytes.cs
src/libraries/System.Private.CoreLib/src/System/Guid.Unix.cs
src/libraries/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/RandomNumberGeneratorImplementation.Browser.cs

index e79f865..c3389aa 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Security.Cryptography;
 using System.Runtime.InteropServices;
 
 internal static partial class Interop
@@ -19,8 +20,9 @@ internal static partial class Interop
         Sys.GetNonCryptographicallySecureRandomBytes(buffer, length);
     }
 
-    internal static unsafe int GetCryptographicallySecureRandomBytes(byte* buffer, int length)
+    internal static unsafe void GetCryptographicallySecureRandomBytes(byte* buffer, int length)
     {
-        return Sys.GetCryptographicallySecureRandomBytes(buffer, length);
+        if (Sys.GetCryptographicallySecureRandomBytes(buffer, length) != 0)
+            throw new CryptographicException();
     }
 }
index c40d43f..f7fc4c0 100644 (file)
@@ -9,7 +9,11 @@ namespace System
         public static unsafe Guid NewGuid()
         {
             Guid g;
-            Interop.GetRandomBytes((byte*)&g, sizeof(Guid));
+
+            // Guid.NewGuid is often used as a cheap source of random data that are sometimes used for security purposes.
+            // Windows implementation uses secure RNG to implement it. We use secure RNG for Unix too to avoid subtle security
+            // vulnerabilities in applications that depend on it. See https://github.com/dotnet/runtime/issues/42752 for details.
+            Interop.GetCryptographicallySecureRandomBytes((byte*)&g, sizeof(Guid));
 
             const ushort VersionMask = 0xF000;
             const ushort RandomGuidVersion = 0x4000;
index 8d34112..daedb5d 100644 (file)
@@ -1,7 +1,6 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System.IO;
 using System.Diagnostics;
 
 namespace System.Security.Cryptography
@@ -12,9 +11,7 @@ namespace System.Security.Cryptography
         {
             Debug.Assert(count > 0);
 
-            int res = Interop.GetCryptographicallySecureRandomBytes(pbBuffer, count);
-            if (res != 0)
-                throw new CryptographicException();
+            Interop.GetCryptographicallySecureRandomBytes(pbBuffer, count);
         }
     }
 }