public SecureMemorySecretFactory(IConfiguration configuration)
        {
            Debug.WriteLine("ProtectedMemorySecretFactory ctor");
            lock (allocatorLock)
            {
                this.configuration = configuration;
                if (allocator != null)
                {
                    refCount++;
                    Debug.WriteLine($"ProtectedMemorySecretFactory: Using existing allocator refCount: {refCount}");
                    return;
                }

                allocator = DetectViaRuntimeInformation(configuration)
                            ?? DetectViaOsVersionPlatform(configuration)
                            ?? DetectOsDescription(configuration);

                if (allocator == null)
                {
                    throw new PlatformNotSupportedException("Could not detect supported platform for protected memory");
                }

                Debug.WriteLine("ProtectedMemorySecretFactory: Created new allocator");
                refCount++;
                Debug.WriteLine($"ProtectedMemorySecretFactory: Using new allocator refCount: {refCount}");
            }
        }
        public void Dispose()
        {
            Debug.WriteLine("ProtectedMemorySecretFactory: Dispose");
            lock (allocatorLock)
            {
                if (allocator == null)
                {
                    throw new Exception("ProtectedMemorySecretFactory.Dispose: Allocator is null!");
                }

                Debug.WriteLine("ProtectedMemorySecretFactory: Allocator is not null");
                refCount--;
                if (refCount == 0)
                {
                    Debug.WriteLine("ProtectedMemorySecretFactory: refCount is zero, disposing");
                    allocator.Dispose();
                    Debug.WriteLine("ProtectedMemorySecretFactory: Setting allocator to null");
                    allocator = null;
                }
                else
                {
                    Debug.WriteLine($"ProtectedMemorySecretFactory: New refCount is {refCount}");
                }
            }
        }
Exemple #3
0
 private void TestNullConfiguration(ISecureMemoryAllocator protectedMemoryAllocator)
 {
     Debug.WriteLine("TestNullConfiguration");
     using (var secret = new SecureMemorySecret(new byte[] { 0, 1 }, protectedMemoryAllocator, null))
     {
     }
 }
        private void TestDefaultMlockConfigurationForMac()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));

            ISecureMemoryAllocator allocator = SecureMemorySecretFactory.ConfigureForMacOS64(configuration);

            Assert.IsType <MacOSProtectedMemoryAllocatorLP64>(allocator);
            Assert.IsNotType <MacOSSecureMemoryAllocatorLP64>(allocator);
        }
Exemple #5
0
        private void TestWithSecretUtf8CharsWithClosedSecretShouldFail(ISecureMemoryAllocator protectedMemoryAllocator)
        {
            Debug.WriteLine("TestWithSecretUtf8CharsWithClosedSecretShouldFail");
            char[]             secretChars = { 'a', 'b' };
            SecureMemorySecret secret      =
                SecureMemorySecret.FromCharArray(secretChars, protectedMemoryAllocator, configuration);

            secret.Close();
            Assert.Throws <InvalidOperationException>(() => { secret.WithSecretUtf8Chars(decryptedChars => true); });
        }
Exemple #6
0
        private void TestWithSecretBytesWithClosedSecretShouldFail(ISecureMemoryAllocator protectedMemoryAllocator)
        {
            Debug.WriteLine("TestWithSecretBytesWithClosedSecretShouldFail");
            byte[]             secretBytes = { 0, 1 };
            SecureMemorySecret secret      =
                new SecureMemorySecret((byte[])secretBytes.Clone(), protectedMemoryAllocator, configuration);

            secret.Close();
            Assert.Throws <InvalidOperationException>(() => { secret.WithSecretBytes(decryptedBytes => true); });
        }
Exemple #7
0
 internal static SecureMemorySecret FromCharArray(char[] sourceChars, ISecureMemoryAllocator allocator, IConfiguration configuration)
 {
     byte[] sourceBytes = Encoding.UTF8.GetBytes(sourceChars);
     try
     {
         return(new SecureMemorySecret(sourceBytes, allocator, configuration));
     }
     finally
     {
         SecureZeroMemory(sourceBytes);
     }
 }
Exemple #8
0
 private void TestWithSecretBytesAction(ISecureMemoryAllocator protectedMemoryAllocator)
 {
     Debug.WriteLine("TestWithSecretBytesAction");
     byte[] secretBytes = { 0, 1 };
     using (SecureMemorySecret secret =
                new SecureMemorySecret((byte[])secretBytes.Clone(), protectedMemoryAllocator, configuration))
     {
         secret.WithSecretBytes(decryptedBytes =>
         {
             Assert.Equal(secretBytes, decryptedBytes);
         });
     }
 }
Exemple #9
0
 private void TestWithSecretUtf8CharsAction(ISecureMemoryAllocator protectedMemoryAllocator)
 {
     Debug.WriteLine("TestWithSecretUtf8CharsAction");
     char[] secretChars = { 'a', 'b' };
     using (SecureMemorySecret secret =
                SecureMemorySecret.FromCharArray(secretChars, protectedMemoryAllocator, configuration))
     {
         secret.WithSecretUtf8Chars(decryptedChars =>
         {
             Assert.Equal(secretChars, decryptedChars);
         });
     }
 }
Exemple #10
0
        internal SecureMemorySecret(byte[] sourceBytes, ISecureMemoryAllocator allocator, IConfiguration configuration)
        {
            Debug.WriteLine("SecureMemorySecret ctor");
            this.allocator     = allocator;
            this.configuration = configuration;

            if (configuration != null)
            {
                if (configuration["debugSecrets"] == "true")
                {
                    creationStackTrace = Environment.StackTrace;
                }

                if (configuration["requireSecretDisposal"] == "true")
                {
                    requireSecretDisposal = true;
                }
            }

            length  = (ulong)sourceBytes.Length;
            pointer = this.allocator.Alloc((ulong)sourceBytes.Length);

            if (pointer == IntPtr.Zero)
            {
                throw new SecureMemoryAllocationFailedException("Protected memory allocation failed");
            }

            try
            {
                Marshal.Copy(sourceBytes, 0, pointer, (int)length);
                this.allocator.SetNoAccess(pointer, length);
            }
            catch
            {
                try
                {
                    this.allocator.SetReadWriteAccess(pointer, length);
                }
                finally
                {
                    this.allocator.Free(pointer, length);
                    pointer = IntPtr.Zero;
                }

                throw;
            }

            // Only clear the client's source buffer if we're successful
            SecureZeroMemory(sourceBytes);
        }
Exemple #11
0
 private void TestWithSecretIntPtrActionSuccess(ISecureMemoryAllocator protectedMemoryAllocator)
 {
     Debug.WriteLine("TestWithSecretIntPtrActionSuccess");
     char[] secretChars = { 'a', 'b' };
     using (SecureMemorySecret secret =
                SecureMemorySecret.FromCharArray(secretChars, protectedMemoryAllocator, configuration))
     {
         secret.WithSecretIntPtr((ptr, len) =>
         {
             Assert.NotEqual(ptr, IntPtr.Zero);
             Assert.True(len == 2);
         });
     }
 }
        private void TestMlockConfigurationSettingForLinux()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Linux));

            IConfigurationRoot configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary <string, string>
            {
                { "mlock", "disabled" }
            }).Build();

            ISecureMemoryAllocator allocator = SecureMemorySecretFactory.ConfigureForLinux64(configuration);

            Assert.IsType <LinuxSecureMemoryAllocatorLP64>(allocator);
            Assert.IsNotType <LinuxProtectedMemoryAllocatorLP64>(allocator);
        }
        public SecureMemoryAllocatorTest()
        {
            Trace.Listeners.Clear();
            var consoleListener = new ConsoleTraceListener();

            Trace.Listeners.Add(consoleListener);

            configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary <string, string>()
            {
                { "heapSize", "32000" },
                { "minimumAllocationSize", "128" },
            }).Build();

            Debug.WriteLine("SecureMemoryAllocatorTest ctor");
            secureMemoryAllocator = GetPlatformAllocator(configuration);
        }
Exemple #14
0
        private void TestWithSecretIntPtrDisposed(ISecureMemoryAllocator protectedMemoryAllocator)
        {
            Debug.WriteLine("TestWithSecretIntPtrDisposed");
            char[]             secretChars = { 'a', 'b' };
            SecureMemorySecret secret      =
                SecureMemorySecret.FromCharArray(secretChars, protectedMemoryAllocator, configuration);

            secret.Dispose();
            Assert.Throws <InvalidOperationException>(() =>
            {
                secret.WithSecretIntPtr((ptr, len) =>
                {
                    return(true);
                });
            });
        }
Exemple #15
0
        private void TestAllocatorSetNoDumpFailure()
        {
            Debug.WriteLine("TestAllocatorSetNoDumpFailure");
            byte[] secretBytes = { 0, 1 };
            ISecureMemoryAllocator allocator = null;

            // TODO : Need to determine if we can stub out the protectedMemoryAllocatorMock.
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Mock <MacOSProtectedMemoryAllocatorLP64> secureMemoryAllocatorMacOSMock =
                    new Mock <MacOSProtectedMemoryAllocatorLP64> {
                    CallBase = true
                };

                secureMemoryAllocatorMacOSMock.Setup(x => x.SetNoDump(It.IsAny <IntPtr>(), It.IsAny <ulong>()))
                .Throws(new Exception());

                allocator = secureMemoryAllocatorMacOSMock.Object;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Mock <LinuxOpenSSL11ProtectedMemoryAllocatorLP64> protectedMemoryAllocatorLinuxMock =
                    new Mock <LinuxOpenSSL11ProtectedMemoryAllocatorLP64>(configuration)
                {
                    CallBase = true
                };

                protectedMemoryAllocatorLinuxMock.Setup(x => x.SetNoDump(It.IsAny <IntPtr>(), It.IsAny <ulong>()))
                .Throws(new Exception());

                allocator = secureMemoryAllocatorMock.Object;
            }
            else
            {
                return;
            }

            Assert.Throws <SecureMemoryAllocationFailedException>(() =>
            {
                using SecureMemorySecret secret =
                          new SecureMemorySecret(secretBytes, allocator, configuration);
            });
        }