Esempio n. 1
0
        public static void X509Certificate2CollectionConstructors()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                Assert.Equal(3, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c3, cc[2]);

                X509Certificate2Collection cc2 = new X509Certificate2Collection(cc);
                Assert.Equal(3, cc2.Count);
                Assert.Same(c1, cc2[0]);
                Assert.Same(c2, cc2[1]);
                Assert.Same(c3, cc2[2]);

                Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 }));

                using (X509Certificate c4 = new X509Certificate())
                {
                    X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 };
                    ((IList)collection).Add(c4); // Add non-X509Certificate2 object

                    Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection));
                }
            }
        }
Esempio n. 2
0
        public static void ImportX509PemFile()
        {
            var collection = new X509Certificate2Collection();
            collection.Import(Path.Combine("TestData", "MS.pem"));

            Assert.Equal(1, collection.Count);
        }
Esempio n. 3
0
        public static void ExportEmpty_Cert()
        {
            var collection = new X509Certificate2Collection();
            byte[] exported = collection.Export(X509ContentType.Cert);

            Assert.Null(exported);
        }
Esempio n. 4
0
        public static void ImportX509PemBytes()
        {
            var collection = new X509Certificate2Collection();
            collection.Import(TestData.MsCertificatePemBytes);

            Assert.Equal(1, collection.Count);
        }
Esempio n. 5
0
 public ImportedCollection(X509Certificate2Collection collection)
 {
     // Make an independent copy of the certs to dispose (in case the test mutates the collection after we return.)
     _certs = new X509Certificate2[collection.Count];
     collection.CopyTo(_certs, 0);
     Collection = collection;
 }
Esempio n. 6
0
        public static void X509Certificate2CollectionEnumerator()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                X509Certificate2Enumerator e = cc.GetEnumerator();
                object ignored;

                // Not started
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c1, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c2, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c3, e.Current);

                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());

                // ended.
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);
            }
        }
Esempio n. 7
0
        public static void ImportPkcs7PemBytes_Empty()
        {
            var collection = new X509Certificate2Collection();
            collection.Import(TestData.Pkcs7EmptyPemBytes);

            Assert.Equal(0, collection.Count);
        }
Esempio n. 8
0
        public static void ImportEmpty_Pkcs12()
        {
            var collection = new X509Certificate2Collection();

            collection.Import(TestData.EmptyPfx);

            Assert.Equal(0, collection.Count);
        }
Esempio n. 9
0
        public static void ExportEmpty_Pkcs12()
        {
            var collection = new X509Certificate2Collection();
            byte[] exported = collection.Export(X509ContentType.Pkcs12);

            // The empty PFX is legal, the answer won't be null.
            Assert.NotNull(exported);
        }
Esempio n. 10
0
        public static void ExportMultiplePrivateKeys()
        {
            var collection = new X509Certificate2Collection();

            try
            {
                collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), (string)null, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible);
                collection.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible);

                // Pre-condition, we have multiple private keys
                int originalPrivateKeyCount = collection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey);
                Assert.Equal(2, originalPrivateKeyCount);

                // Export, re-import.
                byte[] exported;

                try
                {
                    exported = collection.Export(X509ContentType.Pkcs12);
                }
                catch (PlatformNotSupportedException)
                {
                    // [ActiveIssue(2743, TestPlatforms.AnyUnix)]
                    // Our Unix builds can't export more than one private key in a single PFX, so this is
                    // their exit point.
                    //
                    // If Windows gets here, or any exception other than PlatformNotSupportedException is raised,
                    // let that fail the test.
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        throw;
                    }

                    return;
                }

                // As the other half of issue 2743, if we make it this far we better be Windows (or remove the catch
                // above)
                Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "RuntimeInformation.IsOSPlatform(OSPlatform.Windows)");

                using (ImportedCollection ic = Cert.Import(exported))
                {
                    X509Certificate2Collection importedCollection = ic.Collection;

                    Assert.Equal(collection.Count, importedCollection.Count);

                    int importedPrivateKeyCount = importedCollection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey);
                    Assert.Equal(originalPrivateKeyCount, importedPrivateKeyCount);
                }
            }
            finally
            {
                foreach (X509Certificate2 cert in collection)
                {
                    cert.Dispose();
                }
            }
        }
Esempio n. 11
0
        public static void AddDoesNotClone()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            {
                X509Certificate2Collection coll = new X509Certificate2Collection();
                coll.Add(c1);

                Assert.Same(c1, coll[0]);
            }
        }
Esempio n. 12
0
        public static void X509CertificateCollectionsProperties()
        {
            IList ilist = new X509CertificateCollection();
            Assert.False(ilist.IsSynchronized);
            Assert.False(ilist.IsFixedSize);
            Assert.False(ilist.IsReadOnly);

            ilist = new X509Certificate2Collection();
            Assert.False(ilist.IsSynchronized);
            Assert.False(ilist.IsFixedSize);
            Assert.False(ilist.IsReadOnly);
        }
Esempio n. 13
0
	static void AddCertificatesToStore(string cert , string password , StoreLocation loc)
		{
		//Import the pfx certificates
		X509Certificate2Collection certificates = new X509Certificate2Collection() ; 
		certificates.Import( cert , password , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
		
		//Add the Certificate
		X509Store store = new X509Store( storeName , loc) ; // , "Cool Store" ) ; 
		store.Open( OpenFlags.ReadWrite ) ;
		store.AddRange( certificates ) ; 			
		store.Close() ; 
		}
Esempio n. 14
0
        public static void BuildChainExtraStoreUntrustedRoot()
        {
            using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword))
            {
                X509Certificate2Collection collection = new X509Certificate2Collection();
                collection.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);

                X509Chain chain = new X509Chain();
                chain.ChainPolicy.ExtraStore.AddRange(collection);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);

                bool valid = chain.Build(testCert);

                Assert.False(valid);
                Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
            }
        }
Esempio n. 15
0
        public static void X509Certificate2CollectionEnumerator()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                object ignored;

                X509Certificate2Enumerator e = cc.GetEnumerator();
                for (int i = 0; i < 2; i++)
                {
                    // Not started
                    Assert.Throws<InvalidOperationException>(() => ignored = e.Current);

                    Assert.True(e.MoveNext());
                    Assert.Same(c1, e.Current);

                    Assert.True(e.MoveNext());
                    Assert.Same(c2, e.Current);

                    Assert.True(e.MoveNext());
                    Assert.Same(c3, e.Current);

                    Assert.False(e.MoveNext());
                    Assert.False(e.MoveNext());
                    Assert.False(e.MoveNext());
                    Assert.False(e.MoveNext());
                    Assert.False(e.MoveNext());

                    // Ended
                    Assert.Throws<InvalidOperationException>(() => ignored = e.Current);

                    e.Reset();
                }

                IEnumerator e2 = cc.GetEnumerator();
                TestNonGenericEnumerator(e2, c1, c2, c3);

                IEnumerator e3 = ((IEnumerable)cc).GetEnumerator();
                TestNonGenericEnumerator(e3, c1, c2, c3);
            }
        }
Esempio n. 16
0
        public static void ExportUnrelatedPfx()
        {
            // Export multiple certificates which are not part of any kind of certificate chain.
            // Nothing in the PKCS12 structure requires they're related, but it might be an underlying
            // assumption of the provider.
            using (var cert1 = new X509Certificate2(TestData.MsCertificate))
            using (var cert2 = new X509Certificate2(TestData.ComplexNameInfoCert))
            using (var cert3 = new X509Certificate2(TestData.CertWithPolicies))
            {
                var collection = new X509Certificate2Collection
                {
                    cert1,
                    cert2,
                    cert3,
                };

                byte[] exported = collection.Export(X509ContentType.Pkcs12);

                var importedCollection = new X509Certificate2Collection();
                importedCollection.Import(exported);

                // TODO (#3207): Make this test be order-required once ordering is guaranteed on all platforms.
                AssertEqualUnordered(collection, importedCollection);
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            #region X509
            X509Certificate2Collection certCollection = null;
            X509Store        store = null;
            X509Certificate2 SigningCertificate = null;
            string           certThumb          = Configuration["CertificateValidation:Thumbprint"];
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            Log.Debug("STORENAME: " + store.Name);
            Log.Debug("STORELOCATION: " + store.Location);
            store.Open(OpenFlags.ReadOnly);

            certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, certThumb, false);
            Log.Debug("CERTS FOUND: " + certCollection.Count.ToString());
            foreach (X509Certificate2 x509 in certCollection)
            {
                try
                {
                    Log.Debug("FOUND THUMBPRINT: " + x509.Thumbprint);
                    Log.Debug("SEARCHED THUMBPRINT: " + certThumb);
                    if (x509.Thumbprint.ToUpper() == certThumb.ToUpper())
                    {
                        SigningCertificate = x509;
                        break;
                    }
                }
                catch (CryptographicException ex)
                {
                    Log.Error(ex.Message);
                }
            }
            #endregion

            try
            {
                if (SigningCertificate != null)
                {
                    Log.Information("SIGNING CERTIFICATE AQUIRED WITH THUMBPRINT:  \"" + certThumb + "\"");
                    services.AddIdentityServer()
                    .AddSigningCredential(SigningCertificate) // Use this to add trusted certificate or rsa key
                    .AddConfigurationStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration["ConnectionStrings:IdentityServiceConnection"]);
                        options.DefaultSchema      = "IdentityService";
                    }
                                           )
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration["ConnectionStrings:IdentityServiceConnection"], sql => sql.MigrationsAssembly(migrationsAssembly));
                        options.DefaultSchema      = "IdentityService";
                    }
                                         );
                }
                else
                {
                    Log.Warning("UNABLE TO AQUIRE SIGNING CERTIFICATE WITH THUMBPRINT:  \"" + certThumb + "\" USING TEMPORARY SIGNING CREDENTIAL");
                    services.AddIdentityServer()
                    .AddDeveloperSigningCredential() // Use this for test purposes only
                    .AddConfigurationStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration["ConnectionStrings:IdentityServiceConnection"]);
                        options.DefaultSchema      = "IdentityService";
                    }
                                           )
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration["ConnectionStrings:IdentityServiceConnection"], sql => sql.MigrationsAssembly(migrationsAssembly));
                        options.DefaultSchema      = "IdentityService";
                    }
                                         );
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        internal static List <X509Certificate2> FindCandidates(
            X509Certificate2 leaf,
            X509Certificate2Collection extraStore,
            List <X509Certificate2> downloaded,
            ref TimeSpan remainingDownloadTime)
        {
            List <X509Certificate2>  candidates = new List <X509Certificate2>();
            Queue <X509Certificate2> toProcess  = new Queue <X509Certificate2>();

            toProcess.Enqueue(leaf);

            using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
                using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
                    using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
                        using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
                        {
                            systemRootStore.Open(OpenFlags.ReadOnly);
                            systemIntermediateStore.Open(OpenFlags.ReadOnly);
                            userRootStore.Open(OpenFlags.ReadOnly);
                            userIntermediateStore.Open(OpenFlags.ReadOnly);

                            X509Certificate2Collection systemRootCerts         = systemRootStore.Certificates;
                            X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates;
                            X509Certificate2Collection userRootCerts           = userRootStore.Certificates;
                            X509Certificate2Collection userIntermediateCerts   = userIntermediateStore.Certificates;

                            X509Certificate2Collection[] storesToCheck =
                            {
                                extraStore,
                                userIntermediateCerts,
                                systemIntermediateCerts,
                                userRootCerts,
                                systemRootCerts,
                            };

                            while (toProcess.Count > 0)
                            {
                                X509Certificate2 current = toProcess.Dequeue();

                                if (!candidates.Contains(current))
                                {
                                    candidates.Add(current);
                                }

                                List <X509Certificate2> results = FindIssuer(
                                    current,
                                    storesToCheck,
                                    downloaded,
                                    ref remainingDownloadTime);

                                if (results != null)
                                {
                                    foreach (X509Certificate2 result in results)
                                    {
                                        if (!candidates.Contains(result))
                                        {
                                            toProcess.Enqueue(result);
                                        }
                                    }
                                }
                            }
                        }

            return(candidates);
        }
        /// <summary>
        /// Uninstalls a UA application.
        /// </summary>
        public static async Task UninstallApplication(InstalledApplication application)
        {
            // validate the executable file.
            string executableFile = Utils.GetAbsoluteFilePath(application.ExecutableFile, true, true, false);

            // get the default application name from the executable file.
            FileInfo executableFileInfo = new FileInfo(executableFile);
            string   applicationName    = executableFileInfo.Name.Substring(0, executableFileInfo.Name.Length - 4);

            // choose a default configuration file.
            if (String.IsNullOrEmpty(application.ConfigurationFile))
            {
                application.ConfigurationFile = Utils.Format(
                    "{0}\\{1}.Config.xml",
                    executableFileInfo.DirectoryName,
                    applicationName);
            }

            // validate the configuration file.
            string configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, false, false);

            if (configurationFile != null)
            {
                // load the current configuration.
                Opc.Ua.Security.SecuredApplication security = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(configurationFile);

                // delete the application certificates.
                if (application.DeleteCertificatesOnUninstall)
                {
                    CertificateIdentifier id = Opc.Ua.Security.SecuredApplication.FromCertificateIdentifier(security.ApplicationCertificate);

                    // delete public key from trusted peers certificate store.
                    try
                    {
                        CertificateStoreIdentifier certificateStore = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(security.TrustedCertificateStore);

                        using (ICertificateStore store = certificateStore.OpenStore())
                        {
                            X509Certificate2Collection peerCertificates = await store.FindByThumbprint(id.Thumbprint);

                            if (peerCertificates.Count > 0)
                            {
                                await store.Delete(peerCertificates[0].Thumbprint);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message);
                    }

                    // delete private key from application certificate store.
                    try
                    {
                        using (ICertificateStore store = id.OpenStore())
                        {
                            await store.Delete(id.Thumbprint);
                        }
                    }
                    catch (Exception e)
                    {
                        Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message);
                    }

                    // permentently delete any UA defined stores if they are now empty.
                    try
                    {
                        WindowsCertificateStore store = new WindowsCertificateStore();
                        await store.Open("LocalMachine\\UA Applications");

                        X509Certificate2Collection collection = await store.Enumerate();

                        if (collection.Count == 0)
                        {
                            store.PermanentlyDeleteStore();
                        }
                    }
                    catch (Exception e)
                    {
                        Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message);
                    }
                }

                // remove the permissions for the HTTP endpoints used by the application.
                if (application.BaseAddresses != null && application.BaseAddresses.Count > 0)
                {
                    List <ApplicationAccessRule> noRules = new List <ApplicationAccessRule>();

                    for (int ii = 0; ii < application.BaseAddresses.Count; ii++)
                    {
                        Uri url = Utils.ParseUri(application.BaseAddresses[ii]);

                        if (url != null)
                        {
                            try
                            {
                                HttpAccessRule.SetAccessRules(url, noRules, true);
                                Utils.Trace("Removed HTTP access rules for URL: {0}", url);
                            }
                            catch (Exception e)
                            {
                                Utils.Trace("Could not remove HTTP access rules for URL: {0}. Error={1}", url, e.Message);
                            }
                        }
                    }
                }
            }
        }
        private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
        {
            unsafe
            {
                KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
                return(pal.WithCmsgCmsRecipientInfo <Exception>(
                           delegate(CMSG_KEY_AGREE_RECIPIENT_INFO * pKeyAgreeRecipientInfo)
                {
                    CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
                    decryptPara.cbSize = Marshal.SizeOf <CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
                    decryptPara.hProv = hKey;
                    decryptPara.dwKeySpec = keySpec;
                    decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
                    decryptPara.dwRecipientIndex = pal.Index;
                    decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
                    CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
                    switch (originatorChoice)
                    {
                    case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
                        {
                            X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
                            candidateCerts.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
                            candidateCerts.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
                            candidateCerts.AddRange(originatorCerts);
                            candidateCerts.AddRange(extraStore);
                            SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
                            X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
                            if (originatorCert == null)
                            {
                                return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
                            }
                            using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
                            {
                                CERT_CONTEXT *pOriginatorCertContext = hCertContext.DangerousGetCertContext();
                                decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;

                                // Do not factor this call out of the switch statement as leaving this "using" block will free up
                                // native memory that decryptPara points to.
                                return TryExecuteDecryptAgree(ref decryptPara);
                            }
                        }

                    case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
                        {
                            decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
                            return TryExecuteDecryptAgree(ref decryptPara);
                        }

                    default:
                        return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
                    }
                }));
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Specify the certificate authorities certificates to use
 /// when validating SSL peer certificates. This must be done
 /// before the plug-in is initialized; therefore, the application
 /// must define the property Ice.InitPlugins=0, set the certificates,
 /// and finally invoke initializePlugins on the PluginManager.
 /// When the application supplies its own certificate authorities
 /// certificates, the plug-in skips its normal property-based
 /// configuration.
 /// </summary>
 /// <param name="certs">The certificate authorities certificates to use.</param>
 public void SetCACertificates(X509Certificate2Collection certs) => _engine.SetCACertificates(certs);
Esempio n. 22
0
        public static X509Certificate2 GetClientCertificate()
        {
            X509Certificate2Collection certCollection = TestConfiguration.GetClientCertificateCollection();

            return(GetCertWithPrivateKey(certCollection));
        }
        // TODO: this is called from MsQuicListener and when it fails it wreaks havoc in MsQuicListener finalizer.
        //       Consider moving bigger logic like this outside of constructor call chains.
        private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, QUIC_CREDENTIAL_FLAGS flags, X509Certificate?certificate, SslStreamCertificateContext?certificateContext, List <SslApplicationProtocol>?alpnProtocols)
        {
            // TODO: some of these checks should be done by the QuicOptions type.
            if (alpnProtocols == null || alpnProtocols.Count == 0)
            {
                throw new Exception("At least one SslApplicationProtocol value must be present in SslClientAuthenticationOptions or SslServerAuthenticationOptions.");
            }

            if (options.MaxBidirectionalStreams > ushort.MaxValue)
            {
                throw new Exception("MaxBidirectionalStreams overflow.");
            }

            if (options.MaxBidirectionalStreams > ushort.MaxValue)
            {
                throw new Exception("MaxBidirectionalStreams overflow.");
            }

            if ((flags & QUIC_CREDENTIAL_FLAGS.CLIENT) == 0)
            {
                if (certificate == null && certificateContext == null)
                {
                    throw new Exception("Server must provide certificate");
                }
            }
            else
            {
                flags |= QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION;
            }

            if (!OperatingSystem.IsWindows())
            {
                // Use certificate handles on Windows, fall-back to ASN1 otherwise.
                flags |= QUIC_CREDENTIAL_FLAGS.USE_PORTABLE_CERTIFICATES;
            }

            Debug.Assert(!MsQuicApi.Api.Registration.IsInvalid);

            var settings = new QuicSettings
            {
                IsSetFlags = QuicSettingsIsSetFlags.PeerBidiStreamCount |
                             QuicSettingsIsSetFlags.PeerUnidiStreamCount,
                PeerBidiStreamCount  = (ushort)options.MaxBidirectionalStreams,
                PeerUnidiStreamCount = (ushort)options.MaxUnidirectionalStreams
            };

            if (options.IdleTimeout != Timeout.InfiniteTimeSpan)
            {
                if (options.IdleTimeout <= TimeSpan.Zero)
                {
                    throw new Exception("IdleTimeout must not be negative.");
                }

                ulong ms = (ulong)options.IdleTimeout.Ticks / TimeSpan.TicksPerMillisecond;
                if (ms > (1ul << 62) - 1)
                {
                    throw new Exception("IdleTimeout is too large (max 2^62-1 milliseconds)");
                }

                settings.IsSetFlags   |= QuicSettingsIsSetFlags.IdleTimeoutMs;
                settings.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds;
            }

            uint status;
            SafeMsQuicConfigurationHandle?configurationHandle;

            X509Certificate2[]? intermediates = null;

            MemoryHandle[]? handles = null;
            QuicBuffer[]? buffers   = null;
            try
            {
                MsQuicAlpnHelper.Prepare(alpnProtocols, out handles, out buffers);
                status = MsQuicApi.Api.ConfigurationOpenDelegate(MsQuicApi.Api.Registration, (QuicBuffer *)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)alpnProtocols.Count, ref settings, (uint)sizeof(QuicSettings), context: IntPtr.Zero, out configurationHandle);
            }
            finally
            {
                MsQuicAlpnHelper.Return(ref handles, ref buffers);
            }

            QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationOpen failed.");

            try
            {
                CredentialConfig config = default;
                config.Flags = flags; // TODO: consider using LOAD_ASYNCHRONOUS with a callback.

                if (certificateContext != null)
                {
                    certificate   = (X509Certificate2?)_contextCertificate.GetValue(certificateContext);
                    intermediates = (X509Certificate2[]?)_contextChain.GetValue(certificateContext);

                    if (certificate == null || intermediates == null)
                    {
                        throw new ArgumentException(nameof(certificateContext));
                    }
                }

                if (certificate != null)
                {
                    if (OperatingSystem.IsWindows())
                    {
                        config.Type        = QUIC_CREDENTIAL_TYPE.CONTEXT;
                        config.Certificate = certificate.Handle;
                        status             = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config);
                    }
                    else
                    {
                        CredentialConfigCertificatePkcs12 pkcs12Config;
                        byte[] asn1;

                        if (intermediates?.Length > 0)
                        {
                            X509Certificate2Collection collection = new X509Certificate2Collection();
                            collection.Add(certificate);
                            for (int i = 0; i < intermediates?.Length; i++)
                            {
                                collection.Add(intermediates[i]);
                            }

                            asn1 = collection.Export(X509ContentType.Pkcs12) !;
                        }
                        else
                        {
                            asn1 = certificate.Export(X509ContentType.Pkcs12);
                        }

                        fixed(void *ptr = asn1)
                        {
                            pkcs12Config.Asn1Blob           = (IntPtr)ptr;
                            pkcs12Config.Asn1BlobLength     = (uint)asn1.Length;
                            pkcs12Config.PrivateKeyPassword = IntPtr.Zero;

                            config.Type        = QUIC_CREDENTIAL_TYPE.PKCS12;
                            config.Certificate = (IntPtr)(&pkcs12Config);
                            status             = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config);
                        }
                    }
                }
                else
                {
                    config.Type = QUIC_CREDENTIAL_TYPE.NONE;
                    status      = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config);
                }

                QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationLoadCredential failed.");
            }
            catch
            {
                configurationHandle.Dispose();
                throw;
            }

            return(configurationHandle);
        }
Esempio n. 24
0
 public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates)
 {
     return(new ExportProvider(certificates));
 }
Esempio n. 25
0
    public static X509Certificate2 CreateCertificate(string certSubject, bool isCA)
    {
        string CAsubject          = certSubject;
        CX500DistinguishedName dn = new CX500DistinguishedName();

        dn.Encode("CN=" + CAsubject, X500NameFlags.XCN_CERT_NAME_STR_NONE);

        string strRfc822Name = certSubject;

        CAlternativeName  objRfc822Name       = new CAlternativeName();
        CAlternativeNames objAlternativeNames = new CAlternativeNames();
        CX509ExtensionAlternativeNames objExtensionAlternativeNames = new CX509ExtensionAlternativeNames();

        // Set Alternative RFC822 Name
        objRfc822Name.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, strRfc822Name);

        // Set Alternative Names
        objAlternativeNames.Add(objRfc822Name);
        objExtensionAlternativeNames.InitializeEncode(objAlternativeNames);
        //objPkcs10.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames);



        //Issuer Property for cleanup
        string issuer = "__Interceptor_Trusted_Root";
        CX500DistinguishedName issuerdn = new CX500DistinguishedName();

        issuerdn.Encode("CN=" + issuer, X500NameFlags.XCN_CERT_NAME_STR_NONE);
        // Create a new Private Key

        CX509PrivateKey key = new CX509PrivateKey();

        key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"; //"Microsoft Enhanced Cryptographic Provider v1.0"
                                                                                    // Set CAcert to 1 to be used for Signature
        if (isCA)
        {
            key.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
        }
        else
        {
            key.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
        }
        key.Length         = 2048;
        key.MachineContext = true;
        key.Create();

        // Create Attributes
        //var serverauthoid = new X509Enrollment.CObjectId();
        CObjectId serverauthoid = new CObjectId();

        serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1");
        CObjectIds ekuoids = new CObjectIds();

        ekuoids.Add(serverauthoid);
        CX509ExtensionEnhancedKeyUsage ekuext = new CX509ExtensionEnhancedKeyUsage();

        ekuext.InitializeEncode(ekuoids);

        CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate();

        cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, key, "");
        cert.Subject   = dn;
        cert.Issuer    = issuerdn;
        cert.NotBefore = (DateTime.Now).AddDays(-1); //Backup One day to Avoid Timing Issues
        cert.NotAfter  = cert.NotBefore.AddDays(90); //Arbitrary... Change to persist longer...
                                                     //Use Sha256
        CObjectId hashAlgorithmObject = new CObjectId();

        hashAlgorithmObject.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, 0, 0, "SHA256");
        cert.HashAlgorithm = hashAlgorithmObject;

        cert.X509Extensions.Add((CX509Extension)ekuext);
        cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames);
        //https://blogs.msdn.microsoft.com/alejacma/2011/11/07/how-to-add-subject-alternative-name-to-your-certificate-requests-c/
        if (isCA)
        {
            CX509ExtensionBasicConstraints basicConst = new CX509ExtensionBasicConstraints();
            basicConst.InitializeEncode(true, 1);
            cert.X509Extensions.Add((CX509Extension)basicConst);
        }
        else
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection signer = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false);

            CSignerCertificate signerCertificate = new CSignerCertificate();
            signerCertificate.Initialize(true, 0, EncodingType.XCN_CRYPT_STRING_HEX, signer[0].Thumbprint);
            cert.SignerCertificate = signerCertificate;
        }
        cert.Encode();

        CX509Enrollment enrollment = new CX509Enrollment();

        enrollment.InitializeFromRequest(cert);
        string certdata = enrollment.CreateRequest(0);

        enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, certdata, 0, "");

        if (isCA)
        {
            //Install CA Root Certificate
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certList = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false);
            store.Close();

            X509Store rootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            rootStore.Open(OpenFlags.ReadWrite);
            X509Certificate2Collection rootcertList = rootStore.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false);
            rootStore.Add(certList[0]);
            rootStore.Close();
            return(certList[0]);
        }
        else
        {
            //Return Per Domain Cert
            X509Store xstore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            xstore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certList = xstore.Certificates.Find(X509FindType.FindBySubjectName, certSubject, false);
            xstore.Close();
            return(certList[0]);
        }
    }
Esempio n. 26
0
    public static void Main(string[] args)
    {
        IPEndPoint  endpoint = new IPEndPoint(IPAddress.Any, 8081);
        TcpListener listener = new TcpListener(endpoint);
        TcpClient   client   = new TcpClient();

        //Setup CA Certificate;
        X509Store CAstore = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        CAstore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certList = CAstore.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false);

        if (certList.Count > 0)
        {
            Console.WriteLine(certList[0].Thumbprint);
        }
        else
        {
            Console.WriteLine("Installing Trusted Root");
            X509Certificate2 x509 = CreateCertificate("__Interceptor_Trusted_Root", true);
            CAstore.Close();
            Console.WriteLine("Ready");
        }



        listener.Start();

        while (true)
        {
            client = listener.AcceptTcpClient();
            if (client != null)
            {
                NetworkStream nwStream = client.GetStream();
                byte[]        buffer   = new byte[client.ReceiveBufferSize];

                int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

                string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received : \n" + dataReceived);
                string requestString = Encoding.UTF8.GetString(buffer);
                if (requestString.StartsWith("CONNECT"))
                {
                    //Client is requesting SSL, Promote the Stream;
                    // Get Domain Requested
                    string[] requestArray = requestString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                    string[] DomainParse  = requestArray[0].Split(new string[] { " ", ":" }, StringSplitOptions.None);
                    Console.WriteLine("*** SSL REQUEST TO {0} ***", DomainParse[1]);
                    //Spoof Success Response
                    byte[] connectSpoof = Encoding.ASCII.GetBytes("HTTP/1.1 200 Connection Established\r\nTimeStamp: " + DateTime.Now.ToString() + "\r\n\r\n");
                    nwStream.Write(connectSpoof, 0, connectSpoof.Length);
                    nwStream.Flush();

                    SslStream sslStream = new SslStream(nwStream, false);
                    //Check if certificate already exists
                    CAstore.Open(OpenFlags.ReadOnly);
                    X509Certificate2Collection tempCertCheck = CAstore.Certificates.Find(X509FindType.FindBySubjectName, DomainParse[1], false);
                    X509Certificate2           tempCert;
                    if (tempCertCheck.Count > 0)
                    {
                        tempCert = tempCertCheck[0];
                    }
                    else
                    {
                        tempCert = CreateCertificate(DomainParse[1], false);
                    }
                    sslStream.AuthenticateAsServer(tempCert, false, System.Security.Authentication.SslProtocols.Tls12, false);

                    byte[] responseBytes = Encoding.UTF8.GetBytes("<html><H1>Yup!</H1></html>");
                    sslStream.Write(responseBytes, 0, responseBytes.Length);
                }
                else
                {
                    byte[] responseBytes = Encoding.UTF8.GetBytes("<html><H1>Yup!</H1></html>");
                    nwStream.Write(responseBytes, 0, responseBytes.Length);
                }

                //client.Close();
                //listener.Stop();
                //Console.ReadLine();
            }
        }
    }
Esempio n. 27
0
        public override DecryptorPal Decode(
            ReadOnlySpan <byte> encodedMessage,
            out int version,
            out ContentInfo contentInfo,
            out AlgorithmIdentifier contentEncryptionAlgorithm,
            out X509Certificate2Collection originatorCerts,
            out CryptographicAttributeObjectCollection unprotectedAttributes)
        {
            // Read using BER because the CMS specification says the encoding is BER.
            byte[]           copy = CopyContent(encodedMessage);
            EnvelopedDataAsn data = EnvelopedDataAsn.Decode(copy, AsnEncodingRules.BER);

            version = data.Version;

            contentInfo = new ContentInfo(
                new Oid(data.EncryptedContentInfo.ContentType),
                data.EncryptedContentInfo.EncryptedContent?.ToArray() ?? Array.Empty <byte>());

            contentEncryptionAlgorithm =
                data.EncryptedContentInfo.ContentEncryptionAlgorithm.ToPresentationObject();

            originatorCerts = new X509Certificate2Collection();

            if (data.OriginatorInfo.HasValue && data.OriginatorInfo.Value.CertificateSet != null)
            {
                foreach (CertificateChoiceAsn certChoice in data.OriginatorInfo.Value.CertificateSet)
                {
                    if (certChoice.Certificate != null)
                    {
                        originatorCerts.Add(new X509Certificate2(certChoice.Certificate.Value.ToArray()));
                    }
                }
            }

            unprotectedAttributes = SignerInfo.MakeAttributeCollection(data.UnprotectedAttributes);

            var recipientInfos = new List <RecipientInfo>();

            foreach (RecipientInfoAsn recipientInfo in data.RecipientInfos)
            {
                if (recipientInfo.Ktri.HasValue)
                {
                    recipientInfos.Add(new KeyTransRecipientInfo(new ManagedKeyTransPal(recipientInfo.Ktri.Value)));
                }
                else if (recipientInfo.Kari.HasValue)
                {
                    for (int i = 0; i < recipientInfo.Kari.Value.RecipientEncryptedKeys.Length; i++)
                    {
                        recipientInfos.Add(
                            new KeyAgreeRecipientInfo(new ManagedKeyAgreePal(recipientInfo.Kari.Value, i)));
                    }
                }
                else
                {
                    Debug.Fail($"{nameof(RecipientInfoAsn)} deserialized with an unknown recipient type");
                    throw new CryptographicException();
                }
            }

            return(new ManagedDecryptorPal(copy, data, new RecipientInfoCollection(recipientInfos)));
        }
Esempio n. 28
0
        public static void X509Certificate2CollectionRemoveRangeCollection()
        {
            using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
            using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer))
            using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate))
            using (X509Certificate c3 = new X509Certificate())
            {
                X509Certificate2[] array = new X509Certificate2[] { c1, c2 };

                X509Certificate2Collection cc = new X509Certificate2Collection(array);
                cc.RemoveRange(new X509Certificate2Collection { c1, c2 });
                Assert.Equal(0, cc.Count);

                cc = new X509Certificate2Collection(array);
                cc.RemoveRange(new X509Certificate2Collection { c2, c1 });
                Assert.Equal(0, cc.Count);

                cc = new X509Certificate2Collection(array);
                cc.RemoveRange(new X509Certificate2Collection { c1 });
                Assert.Equal(1, cc.Count);
                Assert.Same(c2, cc[0]);

                cc = new X509Certificate2Collection(array);
                X509Certificate2Collection collection = new X509Certificate2Collection();
                collection.Add(c1);
                collection.Add(c2);
                ((IList)collection).Add(c3); // Add non-X509Certificate2 object
                Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection));
                Assert.Equal(2, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);

                cc = new X509Certificate2Collection(array);
                collection = new X509Certificate2Collection();
                collection.Add(c1);
                ((IList)collection).Add(c3); // Add non-X509Certificate2 object
                collection.Add(c2);
                Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection));
                Assert.Equal(2, cc.Count);
                Assert.Same(c2, cc[0]);
                Assert.Same(c1, cc[1]);

                // Remove c1Clone (success)
                // Remove c1 (exception)
                // Add c1Clone back
                // End state: { c1, c2 } => { c2, c1Clone }
                cc = new X509Certificate2Collection(array);
                collection = new X509Certificate2Collection
                {
                    c1Clone,
                    c1,
                    c2,
                };
                Assert.Throws<ArgumentException>(() => cc.RemoveRange(collection));
                Assert.Equal(2, cc.Count);
                Assert.Same(c2, cc[0]);
                Assert.Same(c1Clone, cc[1]);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Creates the certificate.
        /// </summary>
        /// <returns></returns>
        public X509Certificate2 CreateCertificate()
        {
            X509Certificate2Collection certificateCollection = GetCertificateCollection();

            return(certificateCollection.Count > 0 ? certificateCollection[0] : null);
        }
Esempio n. 30
0
        private static void OnRequestSendingRequest(WinHttpRequestState state)
        {
            Debug.Assert(state != null, "OnRequestSendingRequest: state is null");
            Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null");
            Debug.Assert(state.RequestMessage != null, "OnRequestSendingRequest: state.RequestMessage is null");
            Debug.Assert(state.RequestMessage.RequestUri != null, "OnRequestSendingRequest: state.RequestMessage.RequestUri is null");

            if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https)
            {
                // Not SSL/TLS.
                return;
            }

            // Grab the channel binding token (CBT) information from the request handle and put it into
            // the TransportContext object.
            state.TransportContext.SetChannelBinding(state.RequestHandle);

            if (state.ServerCertificateValidationCallback != null)
            {
                IntPtr certHandle     = IntPtr.Zero;
                uint   certHandleSize = (uint)IntPtr.Size;

                if (!Interop.WinHttp.WinHttpQueryOption(
                        state.RequestHandle,
                        Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT,
                        ref certHandle,
                        ref certHandleSize))
                {
                    int lastError = Marshal.GetLastWin32Error();
                    if (NetEventSource.Log.IsEnabled())
                    {
                        NetEventSource.Error(state, $"Error getting WINHTTP_OPTION_SERVER_CERT_CONTEXT, {lastError}");
                    }

                    if (lastError == Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE)
                    {
                        // Not yet an SSL/TLS connection. This occurs while connecting thru a proxy where the
                        // CONNECT verb hasn't yet been processed due to the proxy requiring authentication.
                        // We need to ignore this notification. Another notification will be sent once the final
                        // connection thru the proxy is completed.
                        return;
                    }

                    throw WinHttpException.CreateExceptionUsingError(lastError, "WINHTTP_CALLBACK_STATUS_SENDING_REQUEST/WinHttpQueryOption");
                }

                // Get any additional certificates sent from the remote server during the TLS/SSL handshake.
                X509Certificate2Collection remoteCertificateStore = new X509Certificate2Collection();
                UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(certHandle, remoteCertificateStore);

                // Create a managed wrapper around the certificate handle. Since this results in duplicating
                // the handle, we will close the original handle after creating the wrapper.
                var serverCertificate = new X509Certificate2(certHandle);
                Interop.Crypt32.CertFreeCertificateContext(certHandle);

                X509Chain?      chain = null;
                SslPolicyErrors sslPolicyErrors;
                bool            result = false;

                try
                {
                    WinHttpCertificateHelper.BuildChain(
                        serverCertificate,
                        remoteCertificateStore,
                        state.RequestMessage.RequestUri.Host,
                        state.CheckCertificateRevocationList,
                        out chain,
                        out sslPolicyErrors);

                    result = state.ServerCertificateValidationCallback(
                        state.RequestMessage,
                        serverCertificate,
                        chain,
                        sslPolicyErrors);
                }
                catch (Exception ex)
                {
                    throw WinHttpException.CreateExceptionUsingError(
                              (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "X509Chain.Build", ex);
                }
                finally
                {
                    chain?.Dispose();
                    serverCertificate.Dispose();
                }

                if (!result)
                {
                    throw WinHttpException.CreateExceptionUsingError(
                              (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "ServerCertificateValidationCallback");
                }
            }
        }
 // Checks if any certificates in the collection are expired
 private bool AnyCertificatesExpired(X509Certificate2Collection certificates)
 {
     return(certificates.OfType <X509Certificate2>().Any(c => c.NotAfter < DateTime.Now));
 }
        public unsafe sealed override ContentInfo TryDecrypt(
            RecipientInfo recipientInfo,
            X509Certificate2 cert,
            AsymmetricAlgorithm privateKey,
            X509Certificate2Collection originatorCerts,
            X509Certificate2Collection extraStore,
            out Exception exception)
        {
            Debug.Assert((cert != null) ^ (privateKey != null));

            if (privateKey != null)
            {
                RSA key = privateKey as RSA;

                if (key == null)
                {
                    exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired);
                    return(null);
                }

                ContentInfo contentInfo = _hCryptMsg.GetContentInfo();
                byte[]      cek         = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
                    cert,
                    key,
                    recipientInfo.EncryptedKey,
                    recipientInfo.KeyEncryptionAlgorithm.Oid.Value,
                    recipientInfo.KeyEncryptionAlgorithm.Parameters,
                    out exception);

                // Pin CEK to prevent it from getting copied during heap compaction.
                fixed(byte *pinnedCek = cek)
                {
                    try
                    {
                        if (exception != null)
                        {
                            return(null);
                        }

                        return(AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore(
                                   cek,
                                   contentInfo.ContentType.Value,
                                   contentInfo.Content,
                                   _contentEncryptionAlgorithm,
                                   out exception));
                    }
                    finally
                    {
                        if (cek != null)
                        {
                            Array.Clear(cek, 0, cek.Length);
                        }
                    }
                }
            }

            Debug.Assert(recipientInfo != null);
            Debug.Assert(cert != null);
            Debug.Assert(originatorCerts != null);
            Debug.Assert(extraStore != null);

            CryptKeySpec keySpec;

            exception = TryGetKeySpecForCertificate(cert, out keySpec);
            if (exception != null)
            {
                return(null);
            }

            // .NET Framework compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
            const bool Silent = false;
            // Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
            // because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features
            // (such as RC4 support) to break.
            const bool PreferNCrypt = false;

            using (SafeProvOrNCryptKeyHandle hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
            {
                if (hKey == null)
                {
                    return(null);
                }

                RecipientInfoType type = recipientInfo.Type;
                switch (type)
                {
                case RecipientInfoType.KeyTransport:
                    exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
                    break;

                case RecipientInfoType.KeyAgreement:
                    exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
                    break;

                default:
                    // Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
                    // returning to the caller.
                    Debug.Fail($"Unexpected RecipientInfoType: {type}");
                    throw new NotSupportedException();
                }

                if (exception != null)
                {
                    return(null);
                }

                // If we got here, we successfully decrypted. Return the decrypted content.
                return(_hCryptMsg.GetContentInfo());
            }
        }
Esempio n. 33
0
    public static string assinaXML(string XMLString, string RefUri, X509Certificate2 X509Cert)
    {
        XmlDocument XMLDoc;

        try
        {
            string _xnome = "";
            if (X509Cert != null)
            {
                _xnome = X509Cert.Subject.ToString();
            }
            X509Certificate2 _X509Cert = new X509Certificate2();
            X509Store        store     = new X509Store("MY", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection  = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, _xnome, false);
            if (collection1.Count == 0)
            {
                throw new Exception("Problemas no certificado digital");
            }
            else
            {
                _X509Cert = collection1[0];
                string x;
                x = _X509Cert.GetKeyAlgorithm().ToString();
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;

                try
                {
                    doc.LoadXml(XMLString);
                    int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                    if (qtdeRefUri == 0)
                    {
                        throw new Exception("A tag de assinatura " + RefUri.Trim() + " inexiste");
                    }
                    else
                    {
                        if (qtdeRefUri > 1)
                        {
                            throw new Exception("A tag de assinatura " + RefUri.Trim() + " não é unica");
                        }
                        else
                        {
                            try
                            {
                                SignedXml signedXml = new SignedXml(doc);

                                signedXml.SigningKey = _X509Cert.PrivateKey;

                                Reference reference = new Reference();

                                XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes;
                                foreach (XmlAttribute _atributo in _Uri)
                                {
                                    if (_atributo.Name == "Id")
                                    {
                                        reference.Uri = "#" + _atributo.InnerText;
                                    }
                                }

                                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                reference.AddTransform(env);

                                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                reference.AddTransform(c14);

                                signedXml.AddReference(reference);

                                KeyInfo keyInfo = new KeyInfo();

                                keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));

                                signedXml.KeyInfo = keyInfo;

                                signedXml.ComputeSignature();

                                XmlElement xmlDigitalSignature = signedXml.GetXml();

                                doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                XMLDoc = new XmlDocument();
                                XMLDoc.PreserveWhitespace = false;
                                XMLDoc = doc;
                                return(XMLDoc.OuterXml);
                            }
                            catch (Exception caught)
                            {
                                throw new Exception("Erro: Ao assinar o documento - " + caught.Message);
                            }
                        }
                    }
                }
                catch (Exception caught)
                {
                    throw new Exception("Erro: XML mal formado - " + caught.Message);
                }
            }
        }
        catch (Exception caught)
        {
            throw new Exception("Erro: Problema ao acessar o certificado digital" + caught.Message);
        }
    }
Esempio n. 34
0
        public static void X509Certificate2CollectionThrowsArgumentOutOfRangeException()
        {
            using (X509Certificate2 certificate = new X509Certificate2())
            {
                X509Certificate2Collection collection = new X509Certificate2Collection { certificate };

                Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count));

                IList ilist = (IList)collection;
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count));
            }
        }
Esempio n. 35
0
        public static void X509Certificate2CollectionEnumeratorModification()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                X509Certificate2Enumerator e = cc.GetEnumerator();

                cc.Add(c1);

                // Collection changed.
                Assert.Throws<InvalidOperationException>(() => e.MoveNext());
                Assert.Throws<InvalidOperationException>(() => e.Reset());
            }
        }
Esempio n. 36
0
        public ClusterVNodeSettings(Guid instanceId, int debugIndex,
                                    Func <ClusterNodeOptions> loadConfigFunc,
                                    IPEndPoint internalTcpEndPoint,
                                    IPEndPoint internalSecureTcpEndPoint,
                                    IPEndPoint externalTcpEndPoint,
                                    IPEndPoint externalSecureTcpEndPoint,
                                    IPEndPoint httpEndPoint,
                                    GossipAdvertiseInfo gossipAdvertiseInfo,
                                    bool enableTrustedAuth,
                                    X509Certificate2 certificate,
                                    X509Certificate2Collection trustedRootCerts,
                                    string certificateReservedNodeCommonName,
                                    int workerThreads,
                                    bool discoverViaDns,
                                    string clusterDns,
                                    EndPoint[] gossipSeeds,
                                    TimeSpan minFlushDelay,
                                    int clusterNodeCount,
                                    int prepareAckCount,
                                    int commitAckCount,
                                    TimeSpan prepareTimeout,
                                    TimeSpan commitTimeout,
                                    TimeSpan writeTimeout,
                                    bool disableInternalTcpTls,
                                    bool disableExternalTcpTls,
                                    TimeSpan statsPeriod,
                                    StatsStorage statsStorage,
                                    int nodePriority,
                                    AuthenticationProviderFactory authenticationProviderFactory,
                                    AuthorizationProviderFactory authorizationProviderFactory,
                                    bool disableScavengeMerging,
                                    int scavengeHistoryMaxAge,
                                    bool adminOnPublic,
                                    bool statsOnPublic,
                                    bool gossipOnPublic,
                                    TimeSpan gossipInterval,
                                    TimeSpan gossipAllowedTimeDifference,
                                    TimeSpan gossipTimeout,
                                    TimeSpan intTcpHeartbeatTimeout,
                                    TimeSpan intTcpHeartbeatInterval,
                                    TimeSpan extTcpHeartbeatTimeout,
                                    TimeSpan extTcpHeartbeatInterval,
                                    TimeSpan deadMemberRemovalPeriod,
                                    bool verifyDbHash,
                                    int maxMemtableEntryCount,
                                    int hashCollisionReadLimit,
                                    bool startStandardProjections,
                                    bool disableHTTPCaching,
                                    bool logHttpRequests,
                                    int connectionPendingSendBytesThreshold,
                                    int connectionQueueSizeThreshold,
                                    int ptableMaxReaderCount,
                                    int streamInfoCacheCapacity,
                                    string index             = null, bool enableHistograms = false,
                                    bool skipIndexVerify     = false,
                                    int indexCacheDepth      = 16,
                                    byte indexBitnessVersion = 4,
                                    bool optimizeIndexMerge  = false,
                                    IPersistentSubscriptionConsumerStrategyFactory[] additionalConsumerStrategies = null,
                                    bool unsafeIgnoreHardDeletes            = false,
                                    int readerThreadsCount                  = 4,
                                    bool alwaysKeepScavenged                = false,
                                    bool gossipOnSingleNode                 = false,
                                    bool skipIndexScanOnReads               = false,
                                    bool reduceFileCachePressure            = false,
                                    int initializationThreads               = 1,
                                    bool faultOutOfOrderProjections         = false,
                                    int maxAutoMergeIndexLevel              = 1000,
                                    bool disableFirstLevelHttpAuthorization = false,
                                    bool logFailedAuthenticationAttempts    = false,
                                    long maxTruncation           = 256 * 1024 * 1024,
                                    bool readOnlyReplica         = false,
                                    int maxAppendSize            = 1024 * 1024,
                                    bool unsafeAllowSurplusNodes = false,
                                    bool enableExternalTCP       = false,
                                    bool enableAtomPubOverHTTP   = true,
                                    bool disableHttps            = false)
        {
            Ensure.NotEmptyGuid(instanceId, "instanceId");
            Ensure.Equal(false, internalTcpEndPoint == null && internalSecureTcpEndPoint == null, "Both internal TCP endpoints are null");

            Ensure.NotNull(httpEndPoint, nameof(httpEndPoint));
            if ((clusterNodeCount > 1 && internalSecureTcpEndPoint != null) || externalSecureTcpEndPoint != null || !disableHttps)
            {
                Ensure.NotNull(certificate, "certificate");
            }
            Ensure.Positive(workerThreads, "workerThreads");
            Ensure.NotNull(clusterDns, "clusterDns");
            Ensure.NotNull(gossipSeeds, "gossipSeeds");
            Ensure.Positive(clusterNodeCount, "clusterNodeCount");
            Ensure.Positive(prepareAckCount, "prepareAckCount");
            Ensure.Positive(commitAckCount, "commitAckCount");
            Ensure.Positive(initializationThreads, "initializationThreads");
            Ensure.NotNull(gossipAdvertiseInfo, "gossipAdvertiseInfo");
            if (maxAppendSize > TFConsts.EffectiveMaxLogRecordSize)
            {
                throw new ArgumentOutOfRangeException(nameof(maxAppendSize), $"{nameof(maxAppendSize)} exceeded {TFConsts.EffectiveMaxLogRecordSize} bytes.");
            }

            if (discoverViaDns && string.IsNullOrWhiteSpace(clusterDns))
            {
                throw new ArgumentException(
                          "Either DNS Discovery must be disabled (and seeds specified), or a cluster DNS name must be provided.");
            }

            LoadConfigFunc = loadConfigFunc;
            NodeInfo       = new VNodeInfo(instanceId, debugIndex,
                                           internalTcpEndPoint, internalSecureTcpEndPoint,
                                           externalTcpEndPoint, externalSecureTcpEndPoint,
                                           httpEndPoint,
                                           readOnlyReplica);
            GossipAdvertiseInfo = gossipAdvertiseInfo;
            EnableTrustedAuth   = enableTrustedAuth;
            Certificate         = certificate;
            TrustedRootCerts    = trustedRootCerts;
            CertificateReservedNodeCommonName = certificateReservedNodeCommonName;

            WorkerThreads                   = workerThreads;
            StartStandardProjections        = startStandardProjections;
            EnableAtomPubOverHTTP           = enableAtomPubOverHTTP;
            DisableHTTPCaching              = disableHTTPCaching;
            LogHttpRequests                 = logHttpRequests;
            LogFailedAuthenticationAttempts = logFailedAuthenticationAttempts;
            AdditionalConsumerStrategies    =
                additionalConsumerStrategies ?? new IPersistentSubscriptionConsumerStrategyFactory[0];

            DiscoverViaDns     = discoverViaDns;
            ClusterDns         = clusterDns;
            GossipSeeds        = gossipSeeds;
            GossipOnSingleNode = gossipOnSingleNode;

            ClusterNodeCount = clusterNodeCount;
            MinFlushDelay    = minFlushDelay;
            PrepareAckCount  = prepareAckCount;
            CommitAckCount   = commitAckCount;
            PrepareTimeout   = prepareTimeout;
            CommitTimeout    = commitTimeout;
            WriteTimeout     = writeTimeout;

            DisableInternalTcpTls = disableInternalTcpTls;
            DisableExternalTcpTls = disableExternalTcpTls;
            DisableHttps          = disableHttps;
            EnableExternalTCP     = enableExternalTCP;

            StatsPeriod  = statsPeriod;
            StatsStorage = statsStorage;

            AuthenticationProviderFactory      = authenticationProviderFactory;
            AuthorizationProviderFactory       = authorizationProviderFactory;
            DisableFirstLevelHttpAuthorization = disableFirstLevelHttpAuthorization;

            NodePriority                        = nodePriority;
            DisableScavengeMerging              = disableScavengeMerging;
            ScavengeHistoryMaxAge               = scavengeHistoryMaxAge;
            AdminOnPublic                       = adminOnPublic;
            StatsOnPublic                       = statsOnPublic;
            GossipOnPublic                      = gossipOnPublic;
            GossipInterval                      = gossipInterval;
            GossipAllowedTimeDifference         = gossipAllowedTimeDifference;
            GossipTimeout                       = gossipTimeout;
            IntTcpHeartbeatTimeout              = intTcpHeartbeatTimeout;
            IntTcpHeartbeatInterval             = intTcpHeartbeatInterval;
            ExtTcpHeartbeatTimeout              = extTcpHeartbeatTimeout;
            ExtTcpHeartbeatInterval             = extTcpHeartbeatInterval;
            ConnectionPendingSendBytesThreshold = connectionPendingSendBytesThreshold;
            ConnectionQueueSizeThreshold        = connectionQueueSizeThreshold;
            DeadMemberRemovalPeriod             = deadMemberRemovalPeriod;

            VerifyDbHash           = verifyDbHash;
            MaxMemtableEntryCount  = maxMemtableEntryCount;
            HashCollisionReadLimit = hashCollisionReadLimit;

            EnableHistograms    = enableHistograms;
            SkipIndexVerify     = skipIndexVerify;
            IndexCacheDepth     = indexCacheDepth;
            IndexBitnessVersion = indexBitnessVersion;
            OptimizeIndexMerge  = optimizeIndexMerge;
            Index = index;
            UnsafeIgnoreHardDeletes    = unsafeIgnoreHardDeletes;
            ReaderThreadsCount         = readerThreadsCount;
            AlwaysKeepScavenged        = alwaysKeepScavenged;
            SkipIndexScanOnReads       = skipIndexScanOnReads;
            ReduceFileCachePressure    = reduceFileCachePressure;
            InitializationThreads      = initializationThreads;
            MaxAutoMergeIndexLevel     = maxAutoMergeIndexLevel;
            FaultOutOfOrderProjections = faultOutOfOrderProjections;
            ReadOnlyReplica            = readOnlyReplica;
            MaxAppendSize           = maxAppendSize;
            PTableMaxReaderCount    = ptableMaxReaderCount;
            UnsafeAllowSurplusNodes = unsafeAllowSurplusNodes;
            MaxTruncation           = maxTruncation;
            StreamInfoCacheCapacity = streamInfoCacheCapacity;
        }
        /// <summary>
        /// Installs a UA application.
        /// </summary>
        public static async Task InstallApplication(
            InstalledApplication application,
            bool autostart,
            bool configureFirewall)
        {
            // validate the executable file.
            string executableFile = Utils.GetAbsoluteFilePath(application.ExecutableFile, true, true, false);

            // get the default application name from the executable file.
            FileInfo executableFileInfo = new FileInfo(executableFile);

            string applicationName = executableFileInfo.Name.Substring(0, executableFileInfo.Name.Length - 4);

            // choose a default configuration file.
            if (String.IsNullOrEmpty(application.ConfigurationFile))
            {
                application.ConfigurationFile = Utils.Format(
                    "{0}\\{1}.Config.xml",
                    executableFileInfo.DirectoryName,
                    applicationName);
            }

            // validate the configuration file.
            string configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, false, false);

            // create a new file if one does not exist.
            bool useExisting = true;

            if (configurationFile == null)
            {
                configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, true, true);
                useExisting       = false;
            }

            // create the default configuration file.

            if (useExisting)
            {
                try
                {
                    Opc.Ua.Security.SecuredApplication existingSettings = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(configurationFile);

                    // copy current settings
                    application.ApplicationType             = existingSettings.ApplicationType;
                    application.BaseAddresses               = existingSettings.BaseAddresses;
                    application.ApplicationCertificate      = existingSettings.ApplicationCertificate;
                    application.ApplicationName             = existingSettings.ApplicationName;
                    application.ProductName                 = existingSettings.ProductName;
                    application.RejectedCertificatesStore   = existingSettings.RejectedCertificatesStore;
                    application.TrustedCertificateStore     = existingSettings.TrustedCertificateStore;
                    application.TrustedCertificates         = existingSettings.TrustedCertificates;
                    application.IssuerCertificateStore      = existingSettings.IssuerCertificateStore;
                    application.IssuerCertificates          = application.IssuerCertificates;
                    application.UseDefaultCertificateStores = false;
                }
                catch (Exception e)
                {
                    useExisting = false;
                    Utils.Trace("WARNING. Existing configuration file could not be loaded: {0}.\r\nReplacing with default: {1}", e.Message, configurationFile);
                    File.Copy(configurationFile, configurationFile + ".bak", true);
                }
            }

            // create the configuration file from the default.
            if (!useExisting)
            {
                try
                {
                    string installationFile = Utils.Format(
                        "{0}\\Install\\{1}.Config.xml",
                        executableFileInfo.Directory.Parent.FullName,
                        applicationName);

                    if (!File.Exists(installationFile))
                    {
                        Utils.Trace("Could not find default configuation at: {0}", installationFile);
                    }

                    File.Copy(installationFile, configurationFile, true);
                    Utils.Trace("File.Copy({0}, {1})", installationFile, configurationFile);
                }
                catch (Exception e)
                {
                    Utils.Trace("Could not copy default configuation to: {0}. Error={1}.", configurationFile, e.Message);
                }
            }

            // create a default application name.
            if (String.IsNullOrEmpty(application.ApplicationName))
            {
                application.ApplicationName = applicationName;
            }

            // create a default product name.
            if (String.IsNullOrEmpty(application.ProductName))
            {
                application.ProductName = application.ApplicationName;
            }

            // create a default uri.
            if (String.IsNullOrEmpty(application.ApplicationUri))
            {
                application.ApplicationUri = Utils.Format("http://localhost/{0}/{1}", applicationName, Guid.NewGuid());
            }

            // make the uri specify the local machine.
            application.ApplicationUri = Utils.ReplaceLocalhost(application.ApplicationUri);

            // set a default application store.
            if (application.ApplicationCertificate == null)
            {
                application.ApplicationCertificate           = new Opc.Ua.Security.CertificateIdentifier();
                application.ApplicationCertificate.StoreType = Utils.DefaultStoreType;
                application.ApplicationCertificate.StorePath = ApplicationData.Current.LocalFolder.Path + "\\OPC Foundation\\CertificateStores\\MachineDefault";
            }

            if (application.UseDefaultCertificateStores)
            {
                if (application.IssuerCertificateStore == null)
                {
                    application.IssuerCertificateStore           = new Opc.Ua.Security.CertificateStoreIdentifier();
                    application.IssuerCertificateStore.StoreType = Utils.DefaultStoreType;
                    application.IssuerCertificateStore.StorePath = ApplicationData.Current.LocalFolder.Path + "\\OPC Foundation\\CertificateStores\\MachineDefault";
                }

                if (application.TrustedCertificateStore == null)
                {
                    application.TrustedCertificateStore           = new Opc.Ua.Security.CertificateStoreIdentifier();
                    application.TrustedCertificateStore.StoreType = Utils.DefaultStoreType;
                    application.TrustedCertificateStore.StorePath = ApplicationData.Current.LocalFolder.Path + "\\OPC Foundation\\CertificateStores\\MachineDefault";
                }

                try
                {
                    Utils.GetAbsoluteDirectoryPath(application.TrustedCertificateStore.StorePath, true, true, true);
                }
                catch (Exception e)
                {
                    Utils.Trace("Could not access the machine directory: {0} '{1}'", application.RejectedCertificatesStore.StorePath, e);
                }

                if (application.RejectedCertificatesStore == null)
                {
                    application.RejectedCertificatesStore           = new Opc.Ua.Security.CertificateStoreIdentifier();
                    application.RejectedCertificatesStore.StoreType = CertificateStoreType.Directory;
                    application.RejectedCertificatesStore.StorePath = ApplicationData.Current.LocalFolder.Path + "\\OPC Foundation\\CertificateStores\\RejectedCertificates";

                    StringBuilder buffer = new StringBuilder();

                    buffer.Append(ApplicationData.Current.LocalFolder.Path);
                    buffer.Append("\\OPC Foundation");
                    buffer.Append("\\RejectedCertificates");

                    string folderPath = buffer.ToString();

                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                }
            }

            // check for valid certificate (discard invalid certificates).
            CertificateIdentifier applicationCertificate = Opc.Ua.Security.SecuredApplication.FromCertificateIdentifier(application.ApplicationCertificate);
            X509Certificate2      certificate            = await applicationCertificate.Find(true);

            if (certificate == null)
            {
                certificate = await applicationCertificate.Find(false);

                if (certificate != null)
                {
                    Utils.Trace(
                        "Found existing certificate but it does not have a private key: Store={0}, Certificate={1}",
                        application.ApplicationCertificate.StorePath,
                        application.ApplicationCertificate);
                }
                else
                {
                    Utils.Trace(
                        "Existing certificate could not be found: Store={0}, Certificate={1}",
                        application.ApplicationCertificate.StorePath,
                        application.ApplicationCertificate);
                }
            }

            // check if no certificate exists.
            if (certificate == null)
            {
                certificate = await CreateCertificateForApplication(application);
            }

            // ensure the application certificate is in the trusted peers store.
            try
            {
                CertificateStoreIdentifier certificateStore = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(application.TrustedCertificateStore);

                using (ICertificateStore store = certificateStore.OpenStore())
                {
                    X509Certificate2Collection peerCertificates = await store.FindByThumbprint(certificate.Thumbprint);

                    if (peerCertificates.Count == 0)
                    {
                        await store.Add(new X509Certificate2(certificate.RawData));
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(
                    "Could not add certificate '{0}' to trusted peer store '{1}'. Error={2}",
                    certificate.Subject,
                    application.TrustedCertificateStore,
                    e.Message);
            }

            // update configuration file location.
            UpdateConfigurationLocation(executableFile, configurationFile);

            // update configuration file.
            new Opc.Ua.Security.SecurityConfigurationManager().WriteConfiguration(configurationFile, application);

            ApplicationAccessRuleCollection accessRules = application.AccessRules;
            bool noRulesDefined = application.AccessRules == null || application.AccessRules.Count == 0;

            // add the default access rules.
            if (noRulesDefined)
            {
                ApplicationAccessRule rule = new ApplicationAccessRule();

                rule.IdentityName = WellKnownSids.Administrators;
                rule.RuleType     = AccessControlType.Allow;
                rule.Right        = ApplicationAccessRight.Configure;

                accessRules.Add(rule);

                rule = new ApplicationAccessRule();

                rule.IdentityName = WellKnownSids.Users;
                rule.RuleType     = AccessControlType.Allow;
                rule.Right        = ApplicationAccessRight.Update;

                accessRules.Add(rule);
            }

            // ensure the service account has priviledges.
            if (application.InstallAsService)
            {
                // check if a specific account is assigned.
                AccountInfo accountInfo = null;

                if (!String.IsNullOrEmpty(application.ServiceUserName))
                {
                    accountInfo = AccountInfo.Create(application.ServiceUserName);
                }

                // choose a built-in service account.
                if (accountInfo == null)
                {
                    accountInfo = AccountInfo.Create(WellKnownSids.NetworkService);

                    if (accountInfo == null)
                    {
                        accountInfo = AccountInfo.Create(WellKnownSids.LocalSystem);
                    }
                }

                ApplicationAccessRule rule = new ApplicationAccessRule();

                rule.IdentityName = accountInfo.ToString();
                rule.RuleType     = AccessControlType.Allow;
                rule.Right        = ApplicationAccessRight.Run;

                accessRules.Add(rule);
            }

            // set the permissions for the HTTP endpoints used by the application.
            if (configureFirewall && application.BaseAddresses != null && application.BaseAddresses.Count > 0)
            {
                for (int ii = 0; ii < application.BaseAddresses.Count; ii++)
                {
                    Uri url = Utils.ParseUri(application.BaseAddresses[ii]);

                    if (url != null)
                    {
                        try
                        {
                            HttpAccessRule.SetAccessRules(url, accessRules, true);
                            Utils.Trace("Added HTTP access rules for URL: {0}", url);
                        }
                        catch (Exception e)
                        {
                            Utils.Trace("Could not set HTTP access rules for URL: {0}. Error={1}", url, e.Message);

                            for (int jj = 0; jj < accessRules.Count; jj++)
                            {
                                ApplicationAccessRule rule = accessRules[jj];

                                Utils.Trace(
                                    (int)Utils.TraceMasks.Error,
                                    "IdentityName={0}, Right={1}, RuleType={2}",
                                    rule.IdentityName,
                                    rule.Right,
                                    rule.RuleType);
                            }
                        }
                    }
                }
            }

            // set permissions on the local certificate store.
            SetCertificatePermissions(
                application,
                applicationCertificate,
                accessRules,
                false);

            // set permissions on the local certificate store.
            if (application.RejectedCertificatesStore != null)
            {
                // need to grant full control to certificates in the RejectedCertificatesStore.
                foreach (ApplicationAccessRule rule in accessRules)
                {
                    if (rule.RuleType == AccessControlType.Allow)
                    {
                        rule.Right = ApplicationAccessRight.Configure;
                    }
                }

                CertificateStoreIdentifier rejectedCertificates = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(application.RejectedCertificatesStore);

                using (ICertificateStore store = rejectedCertificates.OpenStore())
                {
                    if (store.SupportsAccessControl)
                    {
                        store.SetAccessRules(accessRules, false);
                    }
                }
            }
        }
Esempio n. 38
0
        public static void ImportFromFileTests()
        {
            using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                X509Certificate2Collection cc2 = new X509Certificate2Collection();
                cc2.Import(Path.Combine("TestData" ,"My.pfx"), TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet);
                int count = cc2.Count;
                Assert.Equal(1, count);

                using (X509Certificate2 c = cc2[0])
                {
                    // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies.
                    Assert.NotSame(pfxCer, c);

                    Assert.Equal(pfxCer, c);
                    Assert.Equal(pfxCer.Thumbprint, c.Thumbprint);
                }
            }
        }
Esempio n. 39
0
        private bool startAuthenticate(IceInternal.AsyncCallback callback, object state)
        {
            try
            {
                _writeCallback = callback;
                if (!_incoming)
                {
                    //
                    // Client authentication.
                    //
                    _writeResult = _sslStream.BeginAuthenticateAsClient(_host,
                                                                        _instance.certs(),
                                                                        _instance.protocols(),
                                                                        _instance.checkCRL() > 0,
                                                                        writeCompleted,
                                                                        state);
                }
                else
                {
                    //
                    // Server authentication.
                    //
                    // Get the certificate collection and select the first one.
                    //
                    X509Certificate2Collection certs = _instance.certs();
                    X509Certificate2           cert  = null;
                    if (certs.Count > 0)
                    {
                        cert = certs[0];
                    }

                    _writeResult = _sslStream.BeginAuthenticateAsServer(cert,
                                                                        _verifyPeer > 0,
                                                                        _instance.protocols(),
                                                                        _instance.checkCRL() > 0,
                                                                        writeCompleted,
                                                                        state);
                }
            }
            catch (IOException ex)
            {
                if (IceInternal.Network.connectionLost(ex))
                {
                    //
                    // This situation occurs when connectToSelf is called; the "remote" end
                    // closes the socket immediately.
                    //
                    throw new Ice.ConnectionLostException();
                }
                throw new Ice.SocketException(ex);
            }
            catch (AuthenticationException ex)
            {
                Ice.SecurityException e = new Ice.SecurityException(ex);
                e.reason = ex.Message;
                throw e;
            }
            catch (Exception ex)
            {
                throw new Ice.SyscallException(ex);
            }

            Debug.Assert(_writeResult != null);
            return(_writeResult.CompletedSynchronously);
        }
Esempio n. 40
0
        /// <summary>
        ///
        ///     Entradas:
        ///         XMLString: string XML a ser assinada
        ///         RefUri   : Referência da URI a ser assinada (Ex. infNFe
        ///         X509Cert : certificado digital a ser utilizado na assinatura digital
        ///
        ///     Retornos:
        ///         Assinar : 0 - Assinatura realizada com sucesso
        ///                   1 - Erro: Problema ao acessar o certificado digital - %exceção%
        ///                   2 - Problemas no certificado digital
        ///                   3 - XML mal formado + exceção
        ///                   4 - A tag de assinatura %RefUri% inexiste
        ///                   5 - A tag de assinatura %RefUri% não é unica
        ///                   6 - Erro Ao assinar o documento - ID deve ser string %RefUri(Atributo)%
        ///                  7 - Erro: Ao assinar o documento - %exceção%
        ///
        ///         XMLStringAssinado : string XML assinada
        ///
        ///         XMLDocAssinado    : XMLDocument do XML assinado
        ///
        /// </summary>
        /// <param name="XMLString"></param>
        /// <param name="RefUri"></param>
        /// <param name="X509Cert"></param>
        /// <returns></returns>
        public int VerificarCertificadoEAssinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
        {
            int resultado = 0;

            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                //   certificado para ser utilizado na assinatura
                //
                string _xnome = "";
                if (X509Cert != null)
                {
                    _xnome = X509Cert.Subject.ToString();
                }
                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store        store     = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection  = store.Certificates;
                X509Certificate2Collection collection1 = collection.Find(X509FindType.FindBySubjectDistinguishedName, _xnome, false);
                if (collection1.Count == 0)
                {
                    resultado    = 2;
                    msgResultado = "Problemas no certificado digital";
                }
                else
                {
                    // certificado ok
                    _X509Cert = collection1[0];
                    string x;
                    x = _X509Cert.GetKeyAlgorithm().ToString();
                    // Create a new XML document.
                    XmlDocument doc = new XmlDocument();

                    // Format the document to ignore white spaces.
                    doc.PreserveWhitespace = false;

                    // Load the passed XML file using it's name.
                    try
                    {
                        doc.LoadXml(XMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            //  a URI indicada não existe
                            resultado    = 4;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {
                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                resultado    = 5;
                                msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";
                            }
                            //else if (_listaNum.IndexOf(doc.GetElementsByTagName(RefUri).Item(0).Attributes.ToString().Substring(1,1))>0)
                            //{
                            //    resultado = 6;
                            //    msgResultado = "Erro: Ao assinar o documento - ID deve ser string (" + doc.GetElementsByTagName(RefUri).Item(0).Attributes + ")";
                            //}
                            else
                            {
                                try
                                {
                                    // Create a SignedXml object.
                                    SignedXml signedXml = new SignedXml(doc);

                                    // Add the key to the SignedXml document
                                    signedXml.SigningKey = _X509Cert.PrivateKey;

                                    // Create a reference to be signed
                                    Reference reference = new Reference();
                                    // pega o uri que deve ser assinada
                                    XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes;
                                    foreach (XmlAttribute _atributo in _Uri)
                                    {
                                        if (_atributo.Name == "Id")
                                        {
                                            reference.Uri = "#" + _atributo.InnerText;
                                        }
                                    }

                                    // Add an enveloped transformation to the reference.
                                    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                    reference.AddTransform(env);

                                    XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                    reference.AddTransform(c14);

                                    // Add the reference to the SignedXml object.
                                    signedXml.AddReference(reference);

                                    // Create a new KeyInfo object
                                    KeyInfo keyInfo = new KeyInfo();

                                    // Load the certificate into a KeyInfoX509Data object
                                    // and add it to the KeyInfo object.
                                    keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));

                                    // Add the KeyInfo object to the SignedXml object.
                                    signedXml.KeyInfo = keyInfo;

                                    signedXml.ComputeSignature();

                                    // Get the XML representation of the signature and save
                                    // it to an XmlElement object.
                                    XmlElement xmlDigitalSignature = signedXml.GetXml();

                                    // Append the element to the XML document.
                                    doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                    XMLDoc = new XmlDocument();
                                    XMLDoc.PreserveWhitespace = false;
                                    XMLDoc = doc;
                                }
                                catch (Exception caught)
                                {
                                    resultado    = 7;
                                    msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                                }
                            }
                        }
                    }
                    catch (Exception caught)
                    {
                        resultado    = 3;
                        msgResultado = "Erro: XML mal formado - " + caught.Message;
                    }
                }
            }
            catch (Exception caught)
            {
                resultado    = 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
                //throw new NFeInvalidCertificadoException(msgResultado, );
            }

            return(resultado);
        }
Esempio n. 41
0
        private static void AssertEqualUnordered(
           X509Certificate2Collection collection,
           X509Certificate2Collection importedCollection)
        {
            // Verify that the two collections contain the same certificates,
            // but the order isn't really a factor.
            Assert.Equal(collection.Count, importedCollection.Count);

            // Compare just the subject names first, because it's the easiest thing to read out of the failure message.
            string[] subjects = new string[collection.Count];
            string[] importedSubjects = new string[collection.Count];
            X509Certificate2[] importedCertificates = new X509Certificate2[collection.Count];

            for (int i = 0; i < collection.Count; i++)
            {
                subjects[i] = collection[i].GetNameInfo(X509NameType.SimpleName, false);
                importedSubjects[i] = importedCollection[i].GetNameInfo(X509NameType.SimpleName, false);
                importedCertificates[i] = importedCollection[i];
            }

            // The best error message would come from a mis-matched subject
            foreach (string subject in subjects)
            {
                Assert.Contains(subject, importedSubjects);
            }

            // But, really, the collections should be equivalent
            foreach (X509Certificate2 expectedCert in collection)
            {
                Assert.Contains(expectedCert, importedCertificates);
            }
        }
Esempio n. 42
0
 public static List <X509Certificate2> ToList(this X509Certificate2Collection source) => source.OfType <X509Certificate2>().ToList();
Esempio n. 43
0
        public static void X509Certificate2CollectionThrowsArgumentNullException()
        {
            using (X509Certificate2 certificate = new X509Certificate2())
            {
                Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2[])null));
                Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2Collection)null));

                X509Certificate2Collection collection = new X509Certificate2Collection { certificate };

                Assert.Throws<ArgumentNullException>(() => collection[0] = null);
                Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate)null));
                Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate2)null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2[])null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2Collection)null));
                Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0));
                Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate)null));
                Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate2)null));
                Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate)null));
                Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate2)null));
                Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2[])null));
                Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2Collection)null));

                Assert.Throws<ArgumentNullException>(() => collection.Import((byte[])null));
                Assert.Throws<ArgumentNullException>(() => collection.Import((string)null));

                IList ilist = (IList)collection;
                Assert.Throws<ArgumentNullException>(() => ilist[0] = null);
                Assert.Throws<ArgumentNullException>(() => ilist.Add(null));
                Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0));
                Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null));
                Assert.Throws<ArgumentNullException>(() => ilist.Remove(null));
            }
        }
Esempio n. 44
0
        private async Task BeginLoop()
        {
            TCPConnection = new TcpConnection()
            {
                Socket = _tcp.Client,
                Ref    = this
            };
            using (NetworkStream stream = _tcp.GetStream())
            {
                TCPConnection.Stream = stream;
                if (Certificate == null)
                {
                    while (true)
                    {
                        Packet pkt = new Packet(stream, TCPConnection);
                        PacketWorker.Queue.Add(new PacketWorker.QueuedPacket()
                        {
                            Entry  = this,
                            Packet = pkt,
                            Rx     = true
                        });
                    }
                }
                else
                {
                    using (SslStream str2 = new SslStream(stream))
                    {
                        TCPConnection.Stream = str2;
                        X509Certificate2Collection coll = null;
                        if (ClientCertificate != null)
                        {
                            coll = new X509Certificate2Collection(ClientCertificate);
                        }
                        SslClientAuthenticationOptions authOpt = new SslClientAuthenticationOptions()
                        {
                            TargetHost = Address.Address.ToString(),
                            CertificateRevocationCheckMode      = X509RevocationMode.NoCheck,
                            ClientCertificates                  = coll,
                            RemoteCertificateValidationCallback = RemoteCertificateValidationCallback
                        };
                        await str2.AuthenticateAsClientAsync(authOpt);

                        if (!str2.IsAuthenticated)
                        {
                            Log.Error("Authentication to entry point failed");
                            return;
                        }
                        while (true)
                        {
                            Packet pkt = new Packet(str2, TCPConnection);
                            PacketWorker.Queue.Add(new PacketWorker.QueuedPacket()
                            {
                                Entry  = this,
                                Packet = pkt,
                                Rx     = true
                            });
                        }
                    }
                }
            }
        }
Esempio n. 45
0
        public static void X509Certificate2CollectionContains()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection collection = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });

                Assert.True(collection.Contains(c1));
                Assert.True(collection.Contains(c2));
                Assert.True(collection.Contains(c3));

                // Note: X509Certificate2Collection.Contains used to throw ArgumentNullException, but it
                // has been deliberately changed to no longer throw to match the behavior of
                // X509CertificateCollection.Contains and the IList.Contains implementation, which do not
                // throw.
                Assert.False(collection.Contains(null));

                IList ilist = (IList)collection;
                Assert.True(ilist.Contains(c1));
                Assert.True(ilist.Contains(c2));
                Assert.True(ilist.Contains(c3));
                Assert.False(ilist.Contains(null));
                Assert.False(ilist.Contains("Bogus"));
            }
        }
Esempio n. 46
0
 public void CloneTo(X509Certificate2Collection collection)
 {
     // Never show any data.
 }
Esempio n. 47
0
        public static void ImportStoreSavedAsSerializedCerData()
        {
            using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                X509Certificate2Collection cc2 = new X509Certificate2Collection();
                cc2.Import(TestData.StoreSavedAsSerializedCerData);
                int count = cc2.Count;
                Assert.Equal(1, count);

                using (X509Certificate2 c = cc2[0])
                {
                    // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies.
                    Assert.NotSame(pfxCer, c);

                    Assert.Equal(pfxCer, c);
                    Assert.Equal(pfxCer.Thumbprint, c.Thumbprint);
                }
            }
        }
Esempio n. 48
0
 public sealed override DecryptorPal Decode(ReadOnlySpan <byte> encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes)
 {
     return(DecryptorPalWindows.Decode(encodedMessage, out version, out contentInfo, out contentEncryptionAlgorithm, out originatorCerts, out unprotectedAttributes));
 }
Esempio n. 49
0
        public static void ImportStoreSavedAsPfxData()
        {
            using (var msCer = new X509Certificate2(TestData.MsCertificate))
            using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                X509Certificate2Collection cc2 = new X509Certificate2Collection();
                cc2.Import(TestData.StoreSavedAsPfxData);
                int count = cc2.Count;
                Assert.Equal(2, count);

                X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray();
                Assert.NotSame(msCer, cs[0]);
                Assert.Equal(msCer, cs[0]);
                Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint);

                Assert.NotSame(pfxCer, cs[1]);
                Assert.Equal(pfxCer, cs[1]);
                Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint);
            }
        }
Esempio n. 50
0
        public override void Execute()
        {
            if (!CanRunOnPlatform())
            {
                return;
            }

            Start();

            // On Windows we can use the .NET API to iterate through all the stores.
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                foreach (StoreLocation storeLocation in (StoreLocation[])Enum.GetValues(typeof(StoreLocation)))
                {
                    foreach (StoreName storeName in (StoreName[])Enum.GetValues(typeof(StoreName)))
                    {
                        try
                        {
                            X509Store store = new X509Store(storeName, storeLocation);
                            store.Open(OpenFlags.ReadOnly);

                            foreach (X509Certificate2 certificate in store.Certificates)
                            {
                                var obj = new CertificateObject()
                                {
                                    StoreLocation         = storeLocation.ToString(),
                                    StoreName             = storeName.ToString(),
                                    CertificateHashString = certificate.GetCertHashString(),
                                    Subject = certificate.Subject,
                                    Pkcs12  = certificate.HasPrivateKey ? "redacted" : certificate.Export(X509ContentType.Pkcs12).ToString()
                                };
                                DatabaseManager.Write(obj, this.runId);
                            }
                            store.Close();
                        }
                        catch (Exception e)
                        {
                            Log.Debug(e.StackTrace);
                            Log.Debug(e.GetType().ToString());
                            Log.Debug(e.Message);
                            Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                        }
                    }
                }
            }
            // On linux we check the central trusted root store (a folder), which has symlinks to actual cert locations scattered across the db
            // We list all the certificates and then create a new X509Certificate2 object for each by filename.
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var result = ExternalCommandRunner.RunExternalCommand("ls", new string[] { "/etc/ssl/certs", "-A" });
                Log.Debug("{0}", result);

                foreach (var _line in result.Split('\n'))
                {
                    Log.Debug("{0}", _line);
                    try
                    {
                        X509Certificate2 certificate = new X509Certificate2("/etc/ssl/certs/" + _line);

                        var obj = new CertificateObject()
                        {
                            StoreLocation         = StoreLocation.LocalMachine.ToString(),
                            StoreName             = StoreName.Root.ToString(),
                            CertificateHashString = certificate.GetCertHashString(),
                            Subject = certificate.Subject,
                            Pkcs12  = certificate.HasPrivateKey ? "redacted" : certificate.Export(X509ContentType.Pkcs12).ToString()
                        };
                        DatabaseManager.Write(obj, this.runId);
                    }
                    catch (Exception e)
                    {
                        Log.Debug("{0} {1} Issue creating certificate based on /etc/ssl/certs/{2}", e.GetType().ToString(), e.Message, _line);
                        Log.Debug("{0}", e.StackTrace);
                    }
                }
            }
            // On macos we use the keychain and export the certificates as .pem.
            // However, on macos Certificate2 doesn't support loading from a pem,
            // so first we need pkcs12s instead, we convert using openssl, which requires we set a password
            // we import the pkcs12 with all our certs, delete the temp files and then iterate over it the certs
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                var    result  = ExternalCommandRunner.RunExternalCommand("security", new string[] { "find-certificate", "-ap", "/System/Library/Keychains/SystemRootCertificates.keychain" });
                string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), "tmpcert.pem");
                string pkPath  = Path.Combine(Directory.GetCurrentDirectory(), "tmpcert.pk12");

                File.WriteAllText(tmpPath, result);
                _ = ExternalCommandRunner.RunExternalCommand("openssl", new string[] { "pkcs12", "-export", "-nokeys", "-out", pkPath, "-passout pass:pass", "-in", tmpPath });

                X509Certificate2Collection xcert = new X509Certificate2Collection();
                xcert.Import(pkPath, "pass", X509KeyStorageFlags.DefaultKeySet);

                File.Delete(tmpPath);
                File.Delete(pkPath);

                var X509Certificate2Enumerator = xcert.GetEnumerator();

                while (X509Certificate2Enumerator.MoveNext())
                {
                    var obj = new CertificateObject()
                    {
                        StoreLocation         = StoreLocation.LocalMachine.ToString(),
                        StoreName             = StoreName.Root.ToString(),
                        CertificateHashString = X509Certificate2Enumerator.Current.GetCertHashString(),
                        Subject = X509Certificate2Enumerator.Current.Subject,
                        Pkcs12  = X509Certificate2Enumerator.Current.HasPrivateKey ? "redacted" : X509Certificate2Enumerator.Current.Export(X509ContentType.Pkcs12).ToString()
                    };
                    DatabaseManager.Write(obj, this.runId);
                }
            }

            DatabaseManager.Commit();
            Stop();
        }
Esempio n. 51
0
        public static void ImportMultiplePrivateKeysPfx()
        {
            var collection = new X509Certificate2Collection();
            collection.Import(TestData.MultiPrivateKeyPfx);

            Assert.Equal(2, collection.Count);

            foreach (X509Certificate2 cert in collection)
            {
                Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey");
            }
        }
Esempio n. 52
0
        static void Main()
        {
            string[] nameParts;
            string   CN          = string.Empty;
            string   cName       = string.Empty;
            string   cFamily     = string.Empty;
            string   cPatronymic = string.Empty;

            char[] charsToTrim = { ',' };
            string certs       = string.Empty;
            List <Certs_reminder.Certificate> certificates = new List <Certs_reminder.Certificate> {
            };
            List <string> fio = new List <string> {
            };

            // Ищем валидные сертификаты
            X509Store store = new X509Store("My", StoreLocation.CurrentUser);                                            // Открываем хранилище сертификатов у текущего пользователя

            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);                                                 // Даем права на чтение хранилища

            X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false); // Находим сертификаты только не с истекшим сроком действия

            foreach (var cert in col)                                                                                    // Для каждого сертификата с не истекшим сроком делаем
            {
                DateTime certExpDate = DateTime.Parse(cert.GetExpirationDateString());

                string[] oneItem = cert.Subject.Split('=');
                if (oneItem[0].Trim() == "CN")
                {
                    CN = oneItem[1];
                    if (CN.IndexOf(" ") > 0)
                    { // Делим на ФИО
                        nameParts   = CN.Split(' ');
                        cFamily     = nameParts[0];
                        cName       = nameParts[1];
                        cPatronymic = nameParts[2].TrimEnd(charsToTrim);
                    }
                }

                var crt = new Certs_reminder.Certificate();

                crt.Fio     = cFamily + " " + cName + " " + cPatronymic;
                crt.Day     = certExpDate.DayOfYear;
                crt.Year    = certExpDate.Year;
                crt.Expired = false;
                certificates.Add(crt);

                //int certExpDate_day = certExpDate.DayOfYear;
                //int certExpDate_day_now = DateTime.Now.DayOfYear;

                //if (certExpDate.Year == DateTime.Now.Year) // если год равен текущему, то проверяем срок действия
                //{
                //    int certExpDate_day_left = certExpDate_day - certExpDate_day_now; // осталось дней до окончания сертификата

                //    if (certExpDate_day_left <= 35)
                //    {
                //        count++;
                //        string certExpDate_formated = certExpDate.ToString("dd.MM.yy");

                //        string[] oneItem = cert.Subject.Split('=');
                //        if (oneItem[0].Trim() == "CN")
                //        {
                //            CN = oneItem[1];
                //            if (CN.IndexOf(" ") > 0)
                //            { // Делим на ФИО
                //                nameParts = CN.Split(' ');
                //                cFamily = nameParts[0];
                //                cName = nameParts[1];
                //                cPatronymic = nameParts[2].TrimEnd(charsToTrim);
                //            }
                //        }

                //        certs = "Срок действия сертификата (" + cFamily + " " + cName + " " + cPatronymic + ")\nзаканчивается через " + certExpDate_day_left + " дней";
                //        AllCerts += certs + "\n\n";
                //    }
                //}
            }
            //AllCerts += "Выполните процедуру продления сертификатов в ЕИС!";
            //if (count > 0)
            //    MessageBox.Show(AllCerts, "Внимание!");

            foreach (var cert in certificates)
            {
                fio.Add(cert.Fio);
            }

            var duplicates    = fio.GroupBy(s => s).SelectMany(g => g.Skip(1));
            var nonduplicates = fio.Except(duplicates);


            foreach (var cert in certificates)
            {
                int cert_day_left = cert.Day - DateTime.Now.DayOfYear;

                foreach (var nondublicate in nonduplicates)
                {
                    if (cert.Fio == nondublicate)
                    {
                        if (cert.Year == DateTime.Now.Year)
                        {
                            if (cert_day_left <= 35)
                            {
                                cert.Expired = true;
                            }
                        }
                    }
                }
                string Declension = GetDeclension(cert_day_left, "день", "дня", "дней");
                if (cert.Expired)
                {
                    certs = "Срок действия сертификата (" + cert.Fio + ")\nзаканчивается через " + cert_day_left + " " + Declension + "\n\n";
                }
            }

            if (!string.IsNullOrEmpty(certs))
            {
                certs += "Выполните процедуру продления сертификатов в ЕИС.";

                MessageBox.Show(certs, "Внимание!");
            }
        }
Esempio n. 53
0
        public static void MultipleImport()
        {
            var collection = new X509Certificate2Collection();

            collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), null, default(X509KeyStorageFlags));
            collection.Import(TestData.PfxData, TestData.PfxDataPassword, default(X509KeyStorageFlags));

            Assert.Equal(3, collection.Count);
        }
Esempio n. 54
0
 public bool OnSelectClientCertificate(IWebBrowser browserControl, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback)
 {
     throw new NotImplementedException();
 }
Esempio n. 55
0
        public static void X509Certificate2CollectionRemoveRangeArray()
        {
            using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
            using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer))
            using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate))
            {
                X509Certificate2[] array = new X509Certificate2[] { c1, c2 };

                X509Certificate2Collection cc = new X509Certificate2Collection(array);
                cc.RemoveRange(array);
                Assert.Equal(0, cc.Count);

                cc = new X509Certificate2Collection(array);
                cc.RemoveRange(new X509Certificate2[] { c2, c1 });
                Assert.Equal(0, cc.Count);

                cc = new X509Certificate2Collection(array);
                cc.RemoveRange(new X509Certificate2[] { c1 });
                Assert.Equal(1, cc.Count);
                Assert.Same(c2, cc[0]);

                cc = new X509Certificate2Collection(array);
                Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, c2, null }));
                Assert.Equal(2, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);

                cc = new X509Certificate2Collection(array);
                Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, null, c2 }));
                Assert.Equal(2, cc.Count);
                Assert.Same(c2, cc[0]);
                Assert.Same(c1, cc[1]);

                // Remove c1Clone (success)
                // Remove c1 (exception)
                // Add c1Clone back
                // End state: { c1, c2 } => { c2, c1Clone }
                cc = new X509Certificate2Collection(array);
                Assert.Throws<ArgumentException>(() => cc.RemoveRange(new X509Certificate2[] { c1Clone, c1, c2 }));
                Assert.Equal(2, cc.Count);
                Assert.Same(c2, cc[0]);
                Assert.Same(c1Clone, cc[1]);
            }
        }
Esempio n. 56
0
        private static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, X509Certificate2Collection remoteCertificateStore)
        {
            bool gotReference = false;

            if (securityContext == null)
            {
                return(null);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(securityContext);
            }

            X509Certificate2    result        = null;
            SafeFreeCertContext remoteContext = null;

            try
            {
                int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext);

                if (remoteContext != null && !remoteContext.IsInvalid)
                {
                    remoteContext.DangerousAddRef(ref gotReference);
                    result = new X509Certificate2(remoteContext.DangerousGetHandle());
                }

                if (remoteCertificateStore != null)
                {
                    using (SafeSharedX509StackHandle chainStack =
                               Interop.OpenSsl.GetPeerCertificateChain(((SafeDeleteSslContext)securityContext).SslContext))
                    {
                        if (!chainStack.IsInvalid)
                        {
                            int count = Interop.Crypto.GetX509StackFieldCount(chainStack);

                            for (int i = 0; i < count; i++)
                            {
                                IntPtr certPtr = Interop.Crypto.GetX509StackField(chainStack, i);

                                if (certPtr != IntPtr.Zero)
                                {
                                    // X509Certificate2(IntPtr) calls X509_dup, so the reference is appropriately tracked.
                                    X509Certificate2 chainCert = new X509Certificate2(certPtr);
                                    remoteCertificateStore.Add(chainCert);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                result?.Dispose();
                throw;
            }
            finally
            {
                if (remoteContext != null)
                {
                    if (gotReference)
                    {
                        remoteContext.DangerousRelease();
                    }

                    remoteContext.Dispose();
                }
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Log.RemoteCertificate(result);
                NetEventSource.Exit(securityContext, result);
            }
            return(result);
        }
Esempio n. 57
0
        public static void X509Certificate2CollectionIndexer()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                cc[0] = c3;
                cc[1] = c2;
                cc[2] = c1;
                Assert.Same(c3, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c1, cc[2]);

                IList il = cc;
                il[0] = c1;
                il[1] = c2;
                il[2] = c3;
                Assert.Same(c1, il[0]);
                Assert.Same(c2, il[1]);
                Assert.Same(c3, il[2]);
            }
        }
Esempio n. 58
0
        //
        // Extracts a remote certificate upon request.
        //
        internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateStore)
        {
            remoteCertificateStore = null;
            bool gotReference = false;

            if (securityContext == null)
            {
                return(null);
            }

            GlobalLog.Enter("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()");
            X509Certificate2    result        = null;
            SafeFreeCertContext remoteContext = null;

            try
            {
                int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext);

                if (remoteContext != null && !remoteContext.IsInvalid)
                {
                    remoteContext.DangerousAddRef(ref gotReference);
                    result = new X509Certificate2(remoteContext.DangerousGetHandle());
                }

                remoteCertificateStore = new X509Certificate2Collection();

                using (SafeSharedX509StackHandle chainStack =
                           Interop.OpenSsl.GetPeerCertificateChain(securityContext.SslContext))
                {
                    if (!chainStack.IsInvalid)
                    {
                        int count = Interop.Crypto.GetX509StackFieldCount(chainStack);

                        for (int i = 0; i < count; i++)
                        {
                            IntPtr certPtr = Interop.Crypto.GetX509StackField(chainStack, i);

                            if (certPtr != IntPtr.Zero)
                            {
                                // X509Certificate2(IntPtr) calls X509_dup, so the reference is appropriately tracked.
                                X509Certificate2 chainCert = new X509Certificate2(certPtr);
                                remoteCertificateStore.Add(chainCert);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (gotReference)
                {
                    remoteContext.DangerousRelease();
                }

                if (remoteContext != null)
                {
                    remoteContext.Dispose();
                }
            }

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_remote_certificate, (result == null ? "null" : result.ToString(true))));
            }

            GlobalLog.Leave("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject));

            return(result);
        }
Esempio n. 59
0
        public static void ExportPublicKeyAsPkcs12()
        {
            using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate))
            {
                // Pre-condition: There's no private key
                Assert.False(publicOnly.HasPrivateKey);

                // This won't throw.
                byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12);

                // Read it back as a collection, there should be only one cert, and it should
                // be equal to the one we started with.
                X509Certificate2Collection fromPfx = new X509Certificate2Collection();
                fromPfx.Import(pkcs12Bytes);

                Assert.Equal(1, fromPfx.Count);
                Assert.Equal(publicOnly, fromPfx[0]);
            }
        }
Esempio n. 60
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string?testName = null, bool longChain = false, bool serverCertificate = true)
        {
            const int keySize = 2048;

            if (PlatformDetection.IsWindows && testName != null)
            {
                CleanupCertificates(testName);
            }

            X509Certificate2Collection chain      = new X509Certificate2Collection();
            X509ExtensionCollection    extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(targetName);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority intermediate,
                out X509Certificate2 endEntity,
                subjectName: targetName,
                testName: testName,
                keySize: keySize,
                extensions: extensions);

            if (longChain)
            {
                using (RSA intermedKey2 = RSA.Create(keySize))
                    using (RSA intermedKey3 = RSA.Create(keySize))
                    {
                        X509Certificate2 intermedPub2 = intermediate.CreateSubordinateCA(
                            $"CN=\"A SSL Test CA 2\", O=\"testName\"",
                            intermedKey2);

                        X509Certificate2 intermedCert2 = intermedPub2.CopyWithPrivateKey(intermedKey2);
                        intermedPub2.Dispose();
                        CertificateAuthority intermediateAuthority2 = new CertificateAuthority(intermedCert2, null, null, null);

                        X509Certificate2 intermedPub3 = intermediateAuthority2.CreateSubordinateCA(
                            $"CN=\"A SSL Test CA 3\", O=\"testName\"",
                            intermedKey3);

                        X509Certificate2 intermedCert3 = intermedPub3.CopyWithPrivateKey(intermedKey3);
                        intermedPub3.Dispose();
                        CertificateAuthority intermediateAuthority3 = new CertificateAuthority(intermedCert3, null, null, null);

                        RSA eeKey = endEntity.GetRSAPrivateKey();
                        endEntity = intermediateAuthority3.CreateEndEntity(
                            $"CN=\"A SSL Test\", O=\"testName\"",
                            eeKey,
                            extensions);

                        endEntity = endEntity.CopyWithPrivateKey(eeKey);

                        chain.Add(intermedCert3);
                        chain.Add(intermedCert2);
                    }
            }

            chain.Add(intermediate.CloneIssuerCert());
            chain.Add(root.CloneIssuerCert());

            responder.Dispose();
            root.Dispose();
            intermediate.Dispose();

            if (PlatformDetection.IsWindows)
            {
                endEntity = new X509Certificate2(endEntity.Export(X509ContentType.Pfx));
            }

            return(endEntity, chain);
        }