コード例 #1
0
        static void InitStore()
        {
            SigningCertificate = CertificateHelper.CreateSelfSignedCertificate(
                "ADFS Signing - " + EnvironmentConfig.ADFSFamrDNSName);
            if (System.IO.File.Exists(dataStoreFile))
            {
                dataStore.Load(dataStoreFile);
            }
            else if (dataStore.DocumentElement == null)
            {
                dataStore.AppendChild(dataStore.CreateElement("Root"));



                XmlNode      defaultApp = dataStore.CreateElement("Data");
                XmlAttribute attr       = dataStore.CreateAttribute("key");
                attr.Value = managedAppsRecord;
                defaultApp.Attributes.Append(attr);
                attr       = dataStore.CreateAttribute("version");
                attr.Value = "-1";
                defaultApp.Attributes.Append(attr);
                attr = dataStore.CreateAttribute("value");
                RelyingPartyTrust[] relies = new RelyingPartyTrust[1];

                relies[0] = createInitialRelyingPartyTrust(managedApp1Name, managedApp1Id);

                attr.Value = JsonUtility.SerializeJSON(relies);
                defaultApp.Attributes.Append(attr);
                dataStore.DocumentElement.AppendChild(defaultApp);
            }
        }
コード例 #2
0
    static void GenerateCertificate(string name, int keyBitLength)
    {
        Console.WriteLine("Generating Certificate for: {0}", name);
        var    properties         = new CertificateHelper.SelfSignedCertProperties(name, keyBitLength);
        var    cert               = CertificateHelper.CreateSelfSignedCertificate(properties);
        var    priBin             = "Store\\" + name + ".pfx";
        var    pubCer             = "Store\\" + name + ".PublicKey.cer";
        var    priPem             = "Store\\" + name + ".PrivateKey.pem";
        var    priPvk             = "Store\\" + name + ".PrivateKey.pvk";
        string privateKeyPassword = "******";

        byte[] pvkBytes;
        if (cert != null)
        {
            CertificateHelper.ExportPrivateKey(cert, priBin, false, privateKeyPassword);
            CertificateHelper.ExportPrivateKey(cert, priPem, true, privateKeyPassword);
            CertificateHelper.ExportPublicKey(cert, pubCer, false);
            pvkBytes = PrivateKeyHelper.Convert(cert.PrivateKey as RSACryptoServiceProvider, privateKeyPassword);
            System.IO.File.WriteAllBytes(priPvk, pvkBytes);
        }
        // Encryption test.
        var text = "Test";

        Console.WriteLine("Encrypt: {0}", text);
        var encrypted = CertificateHelper.Encrypt(pubCer, "Test", null, false);

        Console.WriteLine("Encrypted:\r\n{0}", encrypted);
        // Decryption test.
        //var decrypted = CertificateHelper.Decrypt(priBin, encrypted, privateKeyPassword);

        pvkBytes = System.IO.File.ReadAllBytes(priPvk);
        var key            = PrivateKeyHelper.Convert(pvkBytes, privateKeyPassword);
        var bytes          = Convert.FromBase64String(encrypted);
        var decryptedBytes = key.Decrypt(bytes, true);
        var decrypted      = Encoding.Unicode.GetString(decryptedBytes);

        Console.WriteLine("Decrypted: {0}", decrypted);
    }
コード例 #3
0
        public override void Install(
            IDictionary stateSaver)
        {
            // enable the line below to debug this installer; disable otherwise
            //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");

            // if the installer is running in repair mode, it will try to re-install Myrtille... which is fine
            // problem is, it won't uninstall it first... which is not fine because some components can't be installed twice!
            // thus, prior to any install, try to uninstall first

            Context.LogMessage("Myrtille.Web is being installed, cleaning first");

            try
            {
                Uninstall(null);
            }
            catch (Exception exc)
            {
                Context.LogMessage(string.Format("Failed to clean Myrtille.Web ({0})", exc));
            }

            Context.LogMessage("Installing Myrtille.Web");

            base.Install(stateSaver);

            try
            {
                // register Myrtille.Web to local IIS
                if (!IISHelper.IsIISApplicationPoolExists("MyrtilleAppPool"))
                {
                    IISHelper.CreateIISApplicationPool("MyrtilleAppPool", "v4.0");
                }

                if (!IISHelper.IsIISApplicationExists("/Myrtille"))
                {
                    IISHelper.CreateIISApplication("/Myrtille", Path.GetFullPath(Context.Parameters["targetdir"]), "MyrtilleAppPool");
                }

                // load config
                var config     = new XmlDocument();
                var configPath = Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "Web.config");
                config.Load(configPath);

                var navigator = config.CreateNavigator();

                // services port
                int servicesPort = 8080;
                if (!string.IsNullOrEmpty(Context.Parameters["SERVICESPORT"]))
                {
                    int.TryParse(Context.Parameters["SERVICESPORT"], out servicesPort);
                }

                if (servicesPort != 8080)
                {
                    // client endpoints
                    var client = XmlTools.GetNode(navigator, "/configuration/system.serviceModel/client");
                    if (client != null)
                    {
                        client.InnerXml = client.InnerXml.Replace("8080", servicesPort.ToString());
                    }
                }

                // ssl certificate
                if (!string.IsNullOrEmpty(Context.Parameters["SSLCERT"]))
                {
                    // create a self signed certificate
                    var cert = CertificateHelper.CreateSelfSignedCertificate(Environment.MachineName, "Myrtille self-signed certificate");

                    // bind it to the default website
                    IISHelper.BindCertificate(cert);
                }

                // pdf printer
                var appSettings = XmlTools.GetNode(navigator, "/configuration/appSettings");
                if (appSettings != null)
                {
                    XmlTools.WriteConfigKey(appSettings, "AllowPrintDownload", (!string.IsNullOrEmpty(Context.Parameters["PDFPRINTER"])).ToString().ToLower());
                }

                // save config
                config.Save(configPath);

                // add write permission to the targetdir "log" folder for MyrtilleAppPool, so that Myrtille.Web can save logs into it
                PermissionsHelper.AddDirectorySecurity(
                    Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log"),
                    "IIS AppPool\\MyrtilleAppPool",
                    FileSystemRights.Write,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow);

                Context.LogMessage("Installed Myrtille.Web");
            }
            catch (Exception exc)
            {
                Context.LogMessage(string.Format("Failed to install Myrtille.Web ({0})", exc));
                throw;
            }
        }
コード例 #4
0
ファイル: SyncRelationship.cs プロジェクト: yvanam/SyncPro
        public async Task SaveAsync()
        {
            if (this.Adapters.Count < 2)
            {
                throw new Exception("Cannot create relationship database with fewer than 2 adapters");
            }

            await this.saveLock.WaitAsync();

            try
            {
                if (!Directory.Exists(this.RelationshipRootPath))
                {
                    Directory.CreateDirectory(this.RelationshipRootPath);
                }

                // Set properties in the configuration based on values in the model
                this.Configuration.Description     = this.Description;
                this.Configuration.Name            = this.Name;
                this.Configuration.Scope           = this.SyncScope;
                this.Configuration.SyncAttributes  = this.SyncAttributes;
                this.Configuration.SendSyncReports = this.SendSyncJobReports;

                this.Configuration.ThrottlingConfiguration.IsEnabled   = this.IsThrottlingEnabled;
                this.Configuration.ThrottlingConfiguration.Value       = this.ThrottlingValue;
                this.Configuration.ThrottlingConfiguration.ScaleFactor = this.ThrottlingScaleFactor;

                this.Configuration.TriggerConfiguration.TriggerType      = this.TriggerType;
                this.Configuration.TriggerConfiguration.ScheduleInterval = this.TriggerScheduleInterval;

                this.Configuration.TriggerConfiguration.HourlyIntervalValue       = this.TriggerHourlyInterval;
                this.Configuration.TriggerConfiguration.HourlyMinutesPastSyncTime = this.TriggerHourlyMinutesPastSyncTime;

                this.Configuration.TriggerConfiguration.DailyIntervalValue = this.TriggerDailyIntervalValue;
                this.Configuration.TriggerConfiguration.DailyStartTime     = this.TriggerDailyStartTime;

                this.Configuration.TriggerConfiguration.WeeklyIntervalValue = this.TriggerWeeklyIntervalValue;
                this.Configuration.TriggerConfiguration.WeeklyStartTime     = this.TriggerWeeklyStartTime;

                // Set the encryption mode for adapters that may need it. Other encryption configuration is set below.
                this.Configuration.EncryptionConfiguration.Mode = this.EncryptionMode;

                // If the relaionship contains adapters that arent in the configuration, add them
                foreach (AdapterConfiguration adapterConfig in this.Adapters.Select(a => a.Configuration))
                {
                    if (!this.Configuration.Adapters.Contains(adapterConfig))
                    {
                        this.Configuration.Adapters.Add(adapterConfig);
                    }
                }

                // Assign IDs to the adapters. Start my determining the highest ID currently in use, then assigning
                // incremented IDs from there.
                int highestId = this.Adapters.Select(a => a.Configuration).Max(c => c.Id);
                foreach (AdapterBase adapter in this.Adapters.Where(a => !a.Configuration.IsCreated))
                {
                    // The adapter config hasn't been created, so set the Id
                    highestId++;
                    adapter.Configuration.Id = highestId;
                }

                // Now that the adapters have IDs, set the IDs in the relationship's configuration. This is only
                // needed when the SourceAdapter and DestinationAdapter properties have been set (when the
                // relationship is being created for the first time).
                if (this.SourceAdapter != null && this.DestinationAdapter != null)
                {
                    this.Configuration.SourceAdapterId      = this.SourceAdapter.Configuration.Id;
                    this.Configuration.DestinationAdapterId = this.DestinationAdapter.Configuration.Id;
                }

                // Set the IsOriginator property according to Scope configured for the relationship. If the scope
                // is set to bidirectional, both adapters are originators (and can produce changes). Otherwise,
                // only the source adapter is an originator.
                this.Configuration.Adapters.First(a => a.Id == this.Configuration.SourceAdapterId).IsOriginator      = true;
                this.Configuration.Adapters.First(a => a.Id == this.Configuration.DestinationAdapterId).IsOriginator =
                    this.Configuration.Scope == SyncScopeType.Bidirectional;

                SyncDatabase db = await this.GetDatabaseAsync().ConfigureAwait(false);

                using (db)
                {
                    foreach (AdapterBase adapter in this.Adapters.Where(a => !a.Configuration.IsCreated))
                    {
                        // Originating adapters that have not been created need to have the root entry created
                        if (adapter.Configuration.IsOriginator)
                        {
                            // Create the root sync entry using the adapter
                            SyncEntry rootSyncEntry = await adapter.CreateRootEntry().ConfigureAwait(false);

                            // Add the sync entry and adapter entries to the db.
                            db.Entries.Add(rootSyncEntry);
                            db.AdapterEntries.AddRange(rootSyncEntry.AdapterEntries);

                            // Save the current changes to the DB. This will set the ID for the root sync entry, which
                            // we will want to persist in the config for this adapter.
                            await db.SaveChangesAsync().ConfigureAwait(false);

                            adapter.Configuration.RootIndexEntryId = rootSyncEntry.Id;
                        }

                        adapter.Configuration.IsCreated = true;
                    }
                }

                // Call each adapter to save it's own configuration. This allows different adapter types of save their
                // own configuration as needed.
                foreach (AdapterBase adapterBase in this.Adapters)
                {
                    adapterBase.SaveConfiguration();
                }

                // Check if we are creating this relationship for the first time
                if (this.Configuration.InitiallyCreatedUtc == DateTime.MinValue)
                {
                    // Create the encryption certificate if needed
                    if (this.EncryptionMode == EncryptionMode.Encrypt && this.EncryptionCreateCertificate)
                    {
                        string subjectName = "SyncProEncryption " + this.Configuration.RelationshipId.ToString("D").ToLowerInvariant();

                        X509Certificate2 encryptionCert = CertificateHelper.CreateSelfSignedCertificate(subjectName);

                        this.EncryptionCertificateThumbprint = encryptionCert.Thumbprint;
                        this.Configuration.EncryptionConfiguration.CertificateThumbprint = encryptionCert.Thumbprint;
                    }

                    this.Configuration.InitiallyCreatedUtc = DateTime.UtcNow;
                }

                // Finally save the configuration for the relationship itself
                this.Configuration.Save(this.RelationshipRootPath);

                Logger.RelationshipSaved(
                    new Dictionary <string, object>()
                {
                    { "RelationshipId", this.Configuration.RelationshipId },
                    { "Name", this.Configuration.Name },
                });
            }
            finally
            {
                this.saveLock.Release();
            }
        }
コード例 #5
0
        public override void Install(
            IDictionary stateSaver)
        {
            // enable the line below to debug this installer; disable otherwise
            //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");

            // if the installer is running in repair mode, it will try to re-install Myrtille... which is fine
            // problem is, it won't uninstall it first... which is not fine because some components can't be installed twice!
            // thus, prior to any install, try to uninstall first

            Context.LogMessage("Myrtille.Web is being installed, cleaning first");

            try
            {
                Uninstall(null);
            }
            catch (Exception exc)
            {
                Context.LogMessage(string.Format("Failed to clean Myrtille.Web ({0})", exc));
            }

            Context.LogMessage("Installing Myrtille.Web");

            base.Install(stateSaver);

            try
            {
                // register Myrtille.Web to local IIS
                if (!IISHelper.IsIISApplicationPoolExists("MyrtilleAppPool"))
                {
                    IISHelper.CreateIISApplicationPool("MyrtilleAppPool", "v4.0");
                }

                if (!IISHelper.IsIISApplicationExists("/Myrtille"))
                {
                    IISHelper.CreateIISApplication("/Myrtille", Path.GetFullPath(Context.Parameters["targetdir"]), "MyrtilleAppPool");
                }

                // load config
                var config     = new XmlDocument();
                var configPath = Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "Web.config");
                config.Load(configPath);

                var navigator = config.CreateNavigator();

                // services port
                int servicesPort = 8080;
                if (!string.IsNullOrEmpty(Context.Parameters["SERVICESPORT"]))
                {
                    int.TryParse(Context.Parameters["SERVICESPORT"], out servicesPort);
                }

                if (servicesPort != 8080)
                {
                    // client endpoints
                    var client = XmlTools.GetNode(navigator, "/configuration/system.serviceModel/client");
                    if (client != null)
                    {
                        client.InnerXml = client.InnerXml.Replace("8080", servicesPort.ToString());
                    }
                }

                // admin services port
                int adminServicesPort = 8008;
                if (!string.IsNullOrEmpty(Context.Parameters["ADMINSERVICESPORT"]))
                {
                    int.TryParse(Context.Parameters["ADMINSERVICESPORT"], out adminServicesPort);
                }

                if (adminServicesPort != 8008)
                {
                    // application settings
                    var settings = XmlTools.GetNode(navigator, "/configuration/applicationSettings/Myrtille.Web.Properties.Settings");
                    if (settings != null)
                    {
                        settings.InnerXml = settings.InnerXml.Replace("8008", adminServicesPort.ToString());
                    }
                }

                // ssl certificate
                if (!string.IsNullOrEmpty(Context.Parameters["SSLCERT"]))
                {
                    // create a self signed certificate
                    var cert = CertificateHelper.CreateSelfSignedCertificate(Environment.MachineName, "Myrtille self-signed certificate");

                    // bind it to the default website
                    IISHelper.BindCertificate(cert);
                }

                // pdf printer
                var appSettings = XmlTools.GetNode(navigator, "/configuration/appSettings");
                if (appSettings != null)
                {
                    XmlTools.WriteConfigKey(appSettings, "AllowPrintDownload", (!string.IsNullOrEmpty(Context.Parameters["PDFPRINTER"])).ToString().ToLower());
                }

                // connection api
                if (!string.IsNullOrEmpty(Context.Parameters["CONNECTIONAPI"]))
                {
                    var systemWeb = XmlTools.GetNode(navigator, "/configuration/system.web");
                    if (systemWeb != null)
                    {
                        XmlNode sessionStateUseUri     = null;
                        XmlNode sessionStateUseCookies = null;

                        foreach (XmlNode node in systemWeb.ChildNodes)
                        {
                            // session state
                            // the connection api is likely to be used with iframes
                            // as for multiple connections/tabs, Myrtille must be configured in cookieless mode
                            if (node is XmlComment && node.Value.StartsWith("<sessionState") && node.Value.Contains("cookieless=\"UseUri\""))
                            {
                                sessionStateUseUri = node;
                            }
                            else if (node.Name == "sessionState" && node.OuterXml.Contains("cookieless=\"UseCookies\""))
                            {
                                sessionStateUseCookies = node;
                            }
                        }

                        // uncomment cookieless="UseUri"
                        if (sessionStateUseUri != null)
                        {
                            var nodeReader      = XmlReader.Create(new StringReader(sessionStateUseUri.Value));
                            var uncommentedNode = config.ReadNode(nodeReader);
                            systemWeb.ReplaceChild(uncommentedNode, sessionStateUseUri);
                        }

                        // comment cookieless="UseCookies"
                        if (sessionStateUseCookies != null)
                        {
                            var commentContent = sessionStateUseCookies.OuterXml;
                            var commentedNode  = config.CreateComment(commentContent);
                            systemWeb.ReplaceChild(commentedNode, sessionStateUseCookies);
                        }
                    }
                }

                // save config
                config.Save(configPath);

                // add write permission to the targetdir "log" folder for MyrtilleAppPool, so that Myrtille.Web can save logs into it
                PermissionsHelper.AddDirectorySecurity(
                    Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log"),
                    "IIS AppPool\\MyrtilleAppPool",
                    FileSystemRights.Write,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow);

                Context.LogMessage("Installed Myrtille.Web");
            }
            catch (Exception exc)
            {
                Context.LogMessage(string.Format("Failed to install Myrtille.Web ({0})", exc));
                throw;
            }
        }
コード例 #6
0
        protected override void ProcessRecord()
        {
            if (MyInvocation.BoundParameters.ContainsKey(nameof(Store)) && !Utilities.OperatingSystem.IsWindows())
            {
                throw new PSArgumentException("The Store parameter is only supported on Microsoft Windows");
            }

            if (ValidYears < 1 || ValidYears > 30)
            {
                ValidYears = 10;
            }
            DateTime validFrom = DateTime.Today;
            DateTime validTo   = validFrom.AddYears(ValidYears);


#if NETFRAMEWORK
            var x500Values = new List <string>();
            if (!string.IsNullOrWhiteSpace(CommonName))
            {
                x500Values.Add($"CN={CommonName}");
            }
            if (!string.IsNullOrWhiteSpace(Country))
            {
                x500Values.Add($"C={Country}");
            }
            if (!string.IsNullOrWhiteSpace(State))
            {
                x500Values.Add($"S={State}");
            }
            if (!string.IsNullOrWhiteSpace(Locality))
            {
                x500Values.Add($"L={Locality}");
            }
            if (!string.IsNullOrWhiteSpace(Organization))
            {
                x500Values.Add($"O={Organization}");
            }
            if (!string.IsNullOrWhiteSpace(OrganizationUnit))
            {
                x500Values.Add($"OU={OrganizationUnit}");
            }

            string x500 = string.Join("; ", x500Values);

            byte[]           certificateBytes = CertificateHelper.CreateSelfSignCertificatePfx(x500, validFrom, validTo, CertificatePassword);
            X509Certificate2 certificate      = new X509Certificate2(certificateBytes, CertificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
#else
            X509Certificate2 certificate = CertificateHelper.CreateSelfSignedCertificate(CommonName, Country, State, Locality, Organization, OrganizationUnit, CertificatePassword, CommonName, validFrom, validTo);
#endif

            if (!string.IsNullOrWhiteSpace(OutPfx))
            {
                if (!Path.IsPathRooted(OutPfx))
                {
                    OutPfx = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, OutPfx);
                }
                byte[] certData = certificate.Export(X509ContentType.Pfx, CertificatePassword);
                File.WriteAllBytes(OutPfx, certData);
            }

            if (!string.IsNullOrWhiteSpace(OutCert))
            {
                if (!Path.IsPathRooted(OutCert))
                {
                    OutCert = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, OutCert);
                }
                byte[] certData = certificate.Export(X509ContentType.Cert);
                File.WriteAllBytes(OutCert, certData);
            }

            if (Utilities.OperatingSystem.IsWindows() && MyInvocation.BoundParameters.ContainsKey(nameof(Store)))
            {
                using (var store = new X509Store("My", Store))
                {
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(certificate);
                    store.Close();
                }
                Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, "Certificate added to store");
            }

            var rawCert        = certificate.GetRawCertData();
            var base64Cert     = Convert.ToBase64String(rawCert);
            var rawCertHash    = certificate.GetCertHash();
            var base64CertHash = Convert.ToBase64String(rawCertHash);
            var keyId          = Guid.NewGuid();

            var template      = @"
{{
    ""customKeyIdentifier"": ""{0}"",
    ""keyId"": ""{1}"",
    ""type"": ""AsymmetricX509Cert"",
    ""usage"": ""Verify"",
    ""value"":  ""{2}""
}}
";
            var manifestEntry = string.Format(template, base64CertHash, keyId, base64Cert);

            var record = new PSObject();
            record.Properties.Add(new PSVariableProperty(new PSVariable("Subject", certificate.Subject)));
            record.Properties.Add(new PSVariableProperty(new PSVariable("ValidFrom", certificate.NotBefore)));
            record.Properties.Add(new PSVariableProperty(new PSVariable("ValidTo", certificate.NotAfter)));
            record.Properties.Add(new PSVariableProperty(new PSVariable("Thumbprint", certificate.Thumbprint)));
            var pfxBytes     = certificate.Export(X509ContentType.Pfx, CertificatePassword);
            var base64string = Convert.ToBase64String(pfxBytes);
            record.Properties.Add(new PSVariableProperty(new PSVariable("PfxBase64", base64string)));
            record.Properties.Add(new PSVariableProperty(new PSVariable("KeyCredentials", manifestEntry)));
            record.Properties.Add(new PSVariableProperty(new PSVariable("Certificate", CertificateHelper.CertificateToBase64(certificate))));
            record.Properties.Add(new PSVariableProperty(new PSVariable("PrivateKey", CertificateHelper.PrivateKeyToBase64(certificate))));

            WriteObject(record);
        }
コード例 #7
0
        private X509Certificate2 GetCertificate(PSObject record)
        {
            var cert = new X509Certificate2();

            if (ParameterSetName == ParameterSet_EXISTINGCERT)
            {
                if (!System.IO.Path.IsPathRooted(CertificatePath))
                {
                    CertificatePath = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, CertificatePath);
                }
                // Ensure a file exists at the provided CertificatePath
                if (!File.Exists(CertificatePath))
                {
                    throw new PSArgumentException(string.Format(Resources.CertificateNotFoundAtPath, CertificatePath), nameof(CertificatePath));
                }

                try
                {
                    cert = new X509Certificate2(CertificatePath, CertificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
                }
                catch (CryptographicException e) when(e.Message.Contains("The specified password is not correct"))
                {
                    throw new PSArgumentNullException(nameof(CertificatePassword), string.Format(Resources.PrivateKeyCertificateImportFailedPasswordIncorrect, nameof(CertificatePassword)));
                }

                // Ensure the certificate at the provided CertificatePath holds a private key
                if (!cert.HasPrivateKey)
                {
                    throw new PSArgumentException(string.Format(Resources.CertificateAtPathHasNoPrivateKey, CertificatePath), nameof(CertificatePath));
                }
            }
            else
            {
#if NETFRAMEWORK
                var x500Values = new List <string>();
                if (!MyInvocation.BoundParameters.ContainsKey("CommonName"))
                {
                    CommonName = ApplicationName;
                }
                if (!string.IsNullOrWhiteSpace(CommonName))
                {
                    x500Values.Add($"CN={CommonName}");
                }
                if (!string.IsNullOrWhiteSpace(Country))
                {
                    x500Values.Add($"C={Country}");
                }
                if (!string.IsNullOrWhiteSpace(State))
                {
                    x500Values.Add($"S={State}");
                }
                if (!string.IsNullOrWhiteSpace(Locality))
                {
                    x500Values.Add($"L={Locality}");
                }
                if (!string.IsNullOrWhiteSpace(Organization))
                {
                    x500Values.Add($"O={Organization}");
                }
                if (!string.IsNullOrWhiteSpace(OrganizationUnit))
                {
                    x500Values.Add($"OU={OrganizationUnit}");
                }

                string x500 = string.Join("; ", x500Values);

                if (ValidYears < 1 || ValidYears > 30)
                {
                    ValidYears = 10;
                }
                DateTime validFrom = DateTime.Today;
                DateTime validTo   = validFrom.AddYears(ValidYears);

                byte[] certificateBytes = CertificateHelper.CreateSelfSignCertificatePfx(x500, validFrom, validTo, CertificatePassword);
                cert = new X509Certificate2(certificateBytes, CertificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
#else
                if (!MyInvocation.BoundParameters.ContainsKey("CommonName"))
                {
                    CommonName = ApplicationName;
                }
                DateTime validFrom = DateTime.Today;
                DateTime validTo   = validFrom.AddYears(ValidYears);
                cert = CertificateHelper.CreateSelfSignedCertificate(CommonName, Country, State, Locality, Organization, OrganizationUnit, CertificatePassword, CommonName, validFrom, validTo);
#endif
            }
            var pfxPath = string.Empty;
            var cerPath = string.Empty;


            if (Directory.Exists(OutPath))
            {
                pfxPath = Path.Combine(OutPath, $"{ApplicationName}.pfx");
                cerPath = Path.Combine(OutPath, $"{ApplicationName}.cer");
                byte[] certPfxData = cert.Export(X509ContentType.Pfx, CertificatePassword);
                File.WriteAllBytes(pfxPath, certPfxData);
                record.Properties.Add(new PSVariableProperty(new PSVariable("Pfx file", pfxPath)));

                byte[] certCerData = cert.Export(X509ContentType.Cert);
                File.WriteAllBytes(cerPath, certCerData);
                record.Properties.Add(new PSVariableProperty(new PSVariable("Cer file", cerPath)));
            }
            if (ParameterSpecified(nameof(Store)))
            {
                if (OperatingSystem.IsWindows())
                {
                    using (var store = new X509Store("My", Store))
                    {
                        store.Open(OpenFlags.ReadWrite);
                        store.Add(cert);
                        store.Close();
                    }
                    Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, "Certificate added to store");
                }
            }
            return(cert);
        }
コード例 #8
0
ファイル: WebInstaller.cs プロジェクト: yusufozturk/myrtille
        public override void Install(
            IDictionary stateSaver)
        {
            // enable the line below to debug this installer; disable otherwise
            //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");

            // if the installer is running in repair mode, it will try to re-install Myrtille... which is fine
            // problem is, it won't uninstall it first... which is not fine because some components can't be installed twice!
            // thus, prior to any install, try to uninstall first

            Trace.TraceInformation("Myrtille.Web is being installed, cleaning first");

            try
            {
                Uninstall(null);
            }
            catch (Exception exc)
            {
                Trace.TraceInformation("Failed to clean Myrtille.Web ({0})", exc);
            }

            base.Install(stateSaver);

            Trace.TraceInformation("Installing Myrtille.Web");

            try
            {
                // register Myrtille.Web to local IIS
                if (!IISHelper.IsIISApplicationPoolExists("MyrtilleAppPool"))
                {
                    IISHelper.CreateIISApplicationPool("MyrtilleAppPool", "v4.0");
                }

                if (!IISHelper.IsIISApplicationExists("/Myrtille"))
                {
                    IISHelper.CreateIISApplication("/Myrtille", Path.GetFullPath(Context.Parameters["targetdir"]), "MyrtilleAppPool");
                }

                // create a self signed certificate
                var cert = CertificateHelper.CreateSelfSignedCertificate(Environment.MachineName, "Myrtille self-signed certificate");

                // bind it to the default website
                IISHelper.BindCertificate(cert);

                // add write permission to the targetdir "log" folder for MyrtilleAppPool, so that Myrtille.Web can save logs into it
                PermissionsHelper.AddDirectorySecurity(
                    Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log"),
                    "IIS AppPool\\MyrtilleAppPool",
                    FileSystemRights.Write,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow);

                Trace.TraceInformation("Installed Myrtille.Web");
            }
            catch (Exception exc)
            {
                Context.LogMessage(exc.InnerException != null ? exc.InnerException.Message: exc.Message);
                Trace.TraceError("Failed to install Myrtille.Web ({0})", exc);
                throw;
            }
        }
コード例 #9
0
        public override void Install(
            IDictionary stateSaver)
        {
            // enable the line below to debug this installer; disable otherwise
            //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");

            // if the installer is running in repair mode, it will try to re-install Myrtille... which is fine
            // problem is, it won't uninstall it first... which is not fine because some components can't be installed twice!
            // thus, prior to any install, try to uninstall first

            Trace.TraceInformation("Myrtille.Web is being installed, cleaning first");

            try
            {
                Uninstall(null);
            }
            catch (Exception exc)
            {
                Trace.TraceInformation("Failed to clean Myrtille.Web ({0})", exc);
            }

            base.Install(stateSaver);

            Trace.TraceInformation("Installing Myrtille.Web");

            try
            {
                // register Myrtille.Web to local IIS
                if (!IISHelper.IsIISApplicationPoolExists("MyrtilleAppPool"))
                {
                    IISHelper.CreateIISApplicationPool("MyrtilleAppPool", "v4.0");
                }

                if (!IISHelper.IsIISApplicationExists("/Myrtille"))
                {
                    IISHelper.CreateIISApplication("/Myrtille", Path.GetFullPath(Context.Parameters["targetdir"]), "MyrtilleAppPool");
                }

                // create a self signed certificate
                var cert = CertificateHelper.CreateSelfSignedCertificate(Environment.MachineName, "Myrtille self-signed certificate");

                // bind it to the default website
                IISHelper.BindCertificate(cert);

                // export it to the targetdir "ssl" folder, for secure websocket communication
                var certBytes = cert.Export(X509ContentType.Pfx, "");
                File.WriteAllBytes(Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "ssl", "PKCS12Cert.pfx"), certBytes);

                // add write permission to the targetdir "log" folder for MyrtilleAppPool, so that Myrtille.Web can save logs into it
                PermissionsHelper.AddDirectorySecurity(
                    Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log"),
                    "IIS AppPool\\MyrtilleAppPool",
                    FileSystemRights.Write,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow);

                // websockets ports
                int wsPort;
                if (!int.TryParse(Context.Parameters["WSPort"], out wsPort))
                {
                    wsPort = 8181;
                }

                int wssPort;
                if (!int.TryParse(Context.Parameters["WSSPort"], out wssPort))
                {
                    wssPort = 8431;
                }

                // load config
                var config     = new XmlDocument();
                var configPath = Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "Web.config");
                config.Load(configPath);

                // update settings
                var navigator = config.CreateNavigator();

                var node = XmlTools.GetNode(navigator, "/configuration/appSettings");
                if (node != null)
                {
                    XmlTools.WriteConfigKey(node, "WebSocketServerPort", wsPort.ToString());
                    XmlTools.WriteConfigKey(node, "WebSocketServerPortSecured", wssPort.ToString());
                }

                // save config
                config.Save(configPath);

                // open ports
                FirewallHelper.OpenFirewallPort(wsPort, "Myrtille Websockets");
                FirewallHelper.OpenFirewallPort(wssPort, "Myrtille Websockets Secured");

                Trace.TraceInformation("Installed Myrtille.Web");
            }
            catch (Exception exc)
            {
                Context.LogMessage(exc.InnerException != null ? exc.InnerException.Message: exc.Message);
                Trace.TraceError("Failed to install Myrtille.Web ({0})", exc);
                throw;
            }
        }