internal PsApiManagementHostnameCertificate(CertificateInformation value)
     : this()
 {
     Expiry     = value.Expiry;
     Subject    = value.Subject;
     Thumbprint = value.Thumbprint;
 }
Example #2
0
        public void LogCertificateInformation(CertificateInformation info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            string          value           = (info.RootCertificate == null) ? string.Empty : info.RootCertificate.Format(false);
            LogRowFormatter logRowFormatter = new LogRowFormatter(this.logSchema);

            logRowFormatter[1]  = Environment.MachineName;
            logRowFormatter[2]  = info.StoreName;
            logRowFormatter[3]  = info.Version;
            logRowFormatter[4]  = info.Subject.Format(false);
            logRowFormatter[5]  = info.Issuer.Format(false);
            logRowFormatter[6]  = info.ValidFrom;
            logRowFormatter[7]  = info.ValidTo;
            logRowFormatter[8]  = info.Thumbprint;
            logRowFormatter[9]  = info.SignatureAlgorithm;
            logRowFormatter[10] = info.PublicKeySize;
            logRowFormatter[11] = info.SerialNumber;
            logRowFormatter[12] = value;
            logRowFormatter[13] = info.SubjectKeyIdentifier;
            logRowFormatter[14] = info.BasicConstraints;
            logRowFormatter[15] = info.KeyUsage;
            logRowFormatter[16] = info.EnhancedKeyUsage;
            logRowFormatter[17] = info.ComponentOwner;
            this.exlog.Append(logRowFormatter, 0);
        }
Example #3
0
        protected override void ValidateExpiration(CertificateInformation info)
        {
            TimeSpan t    = info.ValidTo.ToUniversalTime().Subtract(DateTime.UtcNow);
            string   text = string.Format("The following certificate is expiring within {0} day(s).", Math.Ceiling(t.TotalDays));

            if (t <= this.ErrorDaysBeforeExpiry)
            {
                TriggerHandler.Trigger("SSLCertificateErrorEvent", new object[]
                {
                    text,
                    info.ToString(),
                    info.ComponentOwner,
                    base.GetType().Name
                });
                return;
            }
            if (t <= this.WarningDaysBeforeExpiry)
            {
                TriggerHandler.Trigger("SSLCertificateWarningEvent", new object[]
                {
                    text,
                    info.ToString(),
                    info.ComponentOwner,
                    base.GetType().Name
                });
            }
        }
Example #4
0
        public static CertificateInformation GetCertificateInformation(this PsApiManagementCertificateInformation psCertificateInformation)
        {
            if (psCertificateInformation == null)
            {
                return(null);
            }

            var certificateInformation = new CertificateInformation();

            certificateInformation.Expiry     = psCertificateInformation.Expiry;
            certificateInformation.Thumbprint = psCertificateInformation.Thumbprint;
            certificateInformation.Subject    = psCertificateInformation.Subject;

            return(certificateInformation);
        }
        public void PreviewCertificate_returns_view_when_service_returns_object()
        {
            // Given
            var certificateInformation = new CertificateInformation(
                CentreTestHelper.GetDefaultCentre(),
                "Test",
                "Name",
                "Course",
                DateTime.UtcNow,
                "Modifier"
                );

            A.CallTo(() => certificateService.GetPreviewCertificateForCentre(A <int> ._)).Returns(certificateInformation);

            // When
            var result = controller.PreviewCertificate();

            // Then
            result.Should().BeViewResult().WithDefaultViewName();
        }
Example #6
0
        private Task RemoveCertFromVmssTask(VirtualMachineScaleSet vmss, CertificateInformation certInformation)
        {
            var secretGroup = vmss.VirtualMachineProfile.OsProfile.Secrets.SingleOrDefault(
                s => s.SourceVault.Id.Equals(certInformation.KeyVault.Id, StringComparison.OrdinalIgnoreCase));

            bool removeNeeded = false;

            if (secretGroup != null)
            {
                if (secretGroup.VaultCertificates != null)
                {
                    if (secretGroup.VaultCertificates.Count() == 1 && secretGroup.VaultCertificates.First().CertificateUrl.Equals(certInformation.SecretUrl))
                    {
                        vmss.VirtualMachineProfile.OsProfile.Secrets.Remove(secretGroup);
                        removeNeeded = true;
                    }
                    else
                    {
                        var certAdded = secretGroup.VaultCertificates.Single(cert => cert.CertificateUrl.Equals(certInformation.SecretUrl));
                        if (certAdded != null)
                        {
                            secretGroup.VaultCertificates.Remove(certAdded);
                            removeNeeded = true;
                        }
                    }
                }
            }

            if (removeNeeded)
            {
                return(ComputeClient.VirtualMachineScaleSets.CreateOrUpdateAsync(
                           this.ResourceGroupName,
                           vmss.Name,
                           vmss));
            }
            else
            {
                return(null);
            }
        }
Example #7
0
        GetPreviewCertificateForCentre_returns_expected_certificate_information_when_data_service_returns_centre()
        {
            // Given
            var centre = CentreTestHelper.GetDefaultCentre();

            A.CallTo(() => centresDataService.GetCentreDetailsById(centre.CentreId)).Returns(centre);

            // When
            var result = certificateService.GetPreviewCertificateForCentre(centre.CentreId);

            // Then
            var expectedCertificateInformation = new CertificateInformation(
                centre,
                "Joseph",
                "Bloggs",
                "Level 2 - ITSP Course Name",
                new DateTime(2014, 4, 1),
                "Passing online Digital Learning Solutions post learning assessments"
                );

            result.Should().BeEquivalentTo(expectedCertificateInformation);
        }
        public PreviewCertificateViewModel(CertificateInformation certificateInformation)
        {
            CentreContactName = certificateInformation.ContactSurname != null
                ? DisplayStringHelper.GetNonSortableFullNameForDisplayOnly(
                certificateInformation.ContactForename,
                certificateInformation.ContactSurname
                )
                : null;

            DelegateName = DisplayStringHelper.GetNonSortableFullNameForDisplayOnly(
                certificateInformation.DelegateFirstName,
                certificateInformation.DelegateLastName
                );

            CourseName = certificateInformation.CourseName;

            SignatureImage      = certificateInformation.SignatureImage;
            CentreLogo          = certificateInformation.CentreLogo;
            CompletionDate      = certificateInformation.CompletionDate;
            CentreName          = certificateInformation.CentreName;
            CertificateModifier = certificateInformation.CertificateModifier;
        }
Example #9
0
        internal Task AddCertToVmssTask(VirtualMachineScaleSet vmss, CertificateInformation certInformation)
        {
            var secretGroup = vmss.VirtualMachineProfile.OsProfile.Secrets.SingleOrDefault(
                s => s.SourceVault.Id.Equals(certInformation.KeyVault.Id, StringComparison.OrdinalIgnoreCase));


            string configStore = null;

            if (vmss.VirtualMachineProfile.OsProfile.WindowsConfiguration != null)
            {
                configStore = Constants.DefaultCertificateStore;
            }

            if (secretGroup == null)
            {
                vmss.VirtualMachineProfile.OsProfile.Secrets.Add(
                    new VaultSecretGroup()
                {
                    SourceVault = new Azure.Commands.Common.Compute.Version_2018_04.Models.SubResource()
                    {
                        Id = certInformation.KeyVault.Id
                    },
                    VaultCertificates = new List <VaultCertificate>()
                    {
                        new VaultCertificate()
                        {
                            CertificateStore = configStore,
                            CertificateUrl   = certInformation.SecretUrl
                        }
                    }
                });
            }
            else
            {
                if (secretGroup.VaultCertificates != null)
                {
                    var exsit =
                        secretGroup.VaultCertificates.Any(
                            cert =>
                            cert.CertificateUrl.Equals(certInformation.SecretUrl,
                                                       StringComparison.OrdinalIgnoreCase));

                    if (!exsit)
                    {
                        secretGroup.VaultCertificates.Add(
                            new VaultCertificate()
                        {
                            CertificateStore = configStore,
                            CertificateUrl   = certInformation.SecretUrl
                        });
                    }
                }
                else
                {
                    secretGroup.VaultCertificates = new List <VaultCertificate>()
                    {
                        new VaultCertificate()
                        {
                            CertificateStore = configStore,
                            CertificateUrl   = certInformation.SecretUrl
                        }
                    };
                }
            }

            return(ComputeClient.VirtualMachineScaleSets.CreateOrUpdateAsync(
                       this.ResourceGroupName,
                       vmss.Name,
                       vmss));
        }
Example #10
0
        internal List <Task> CreateAddOrRemoveCertVMSSTasks(CertificateInformation certInformation, string clusterId, bool isClusterCert = true, bool addCert = true)
        {
            var allTasks  = new List <Task>();
            var vmssPages = this.ComputeClient.VirtualMachineScaleSets.List(this.ResourceGroupName);

            if (vmssPages == null || !vmssPages.Any())
            {
                throw new PSArgumentException(string.Format(
                                                  ServiceFabricProperties.Resources.NoVMSSFoundInRG,
                                                  this.ResourceGroupName));
            }

            do
            {
                if (!vmssPages.Any())
                {
                    break;
                }

                foreach (var vmss in vmssPages)
                {
                    VirtualMachineScaleSetExtension sfExt;
                    if (TryGetFabricVmExt(vmss.VirtualMachineProfile.ExtensionProfile?.Extensions, out sfExt))
                    {
                        if (!string.Equals(GetClusterIdFromExtension(sfExt), clusterId, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        WriteVerboseWithTimestamp(string.Format("Found VMSS: {0}, id: {1} for cluster {2}", vmss.Name, vmss.Id, clusterId));

                        var extConfig = (JObject)sfExt.Settings;

                        if (addCert)
                        {
                            if (isClusterCert)
                            {
                                if (this.CertificateCommonName != null)
                                {
                                    JArray newCommonNames = (JArray)extConfig.SelectToken("certificate.commonNames");
                                    newCommonNames.Add(this.CertificateCommonName);

                                    extConfig["certificate"]["commonNames"] = newCommonNames;
                                }
                                else
                                {
                                    var input = string.Format(
                                        @"{{""thumbprint"":""{0}"",""x509StoreName"":""{1}""}}",
                                        certInformation.CertificateThumbprint,
                                        Constants.DefaultCertificateStore);

                                    extConfig["certificateSecondary"] = JObject.Parse(input);
                                }

                                vmss.VirtualMachineProfile.ExtensionProfile.Extensions.Single(
                                    extension =>
                                    extension.Name.Equals(sfExt.Name, StringComparison.OrdinalIgnoreCase)).Settings = extConfig;
                            }

                            allTasks.Add(AddCertToVmssTask(vmss, certInformation));
                        }
                        else
                        {
                            if (isClusterCert)
                            {
                                if (this.CertificateCommonName != null)
                                {
                                    JArray commonNames        = (JArray)extConfig.SelectToken("certificate.commonNames");
                                    var    commonNameToRemove = commonNames.FirstOrDefault(commonName => (string)commonName == this.CertificateCommonName);
                                    if (commonNameToRemove != null)
                                    {
                                        commonNames.Remove(commonNameToRemove);
                                    }
                                }
                                else
                                {
                                    string secondaryThumbprint = (string)extConfig["certificateSecondary"]["thumbprint"];
                                    if (certInformation.CertificateThumbprint.Equals(secondaryThumbprint, StringComparison.OrdinalIgnoreCase))
                                    {
                                        extConfig.Remove("certificateSecondary");
                                    }
                                }

                                vmss.VirtualMachineProfile.ExtensionProfile.Extensions.Single(
                                    extension =>
                                    extension.Name.Equals(sfExt.Name, StringComparison.OrdinalIgnoreCase)).Settings = extConfig;
                            }

                            allTasks.Add(RemoveCertFromVmssTask(vmss, certInformation));
                        }
                    }
                }
            } while (!string.IsNullOrEmpty(vmssPages.NextPageLink) &&
                     (vmssPages = this.ComputeClient.VirtualMachineScaleSets.ListNext(vmssPages.NextPageLink)) != null);

            if (allTasks.Count() == 0)
            {
                throw new ItemNotFoundException(string.Format(ServiceFabricProperties.Resources.NoVmssFoundForCluster, this.ResourceGroupName, clusterId));
            }

            return(allTasks);
        }
Example #11
0
        public CertificateLog(string logDirectory, long maxDirectorySize, long maxFileSize, int maxBufferSize, TimeSpan flushInterval)
        {
            this.logSchema = new LogSchema("Microsoft Exchange Server", "15.0.0.0", "Certificate Log", CertificateInformation.GetColumnHeaders());
            LogHeaderFormatter headerFormatter = new LogHeaderFormatter(this.logSchema, LogHeaderCsvOption.CsvStrict);

            this.exlog = new Log(CertificateLog.LogFilePrefix, headerFormatter, "Certificate Log");
            this.exlog.Configure(logDirectory, TimeSpan.Zero, maxDirectorySize, maxFileSize, maxBufferSize, flushInterval, true);
        }
Example #12
0
        internal List <CertificateInformation> GetOrCreateCertificateInformation()
        {
            var certificateInformations = new List <CertificateInformation>();

            if (string.IsNullOrEmpty(this.KeyVaultResourceGroupName))
            {
                this.KeyVaultResourceGroupName = this.ResourceGroupName;
            }

            if (string.IsNullOrEmpty(this.KeyVaultName))
            {
                this.KeyVaultName = CreateDefaultKeyVaultName(this.ResourceGroupName);
            }

            if (ParameterSetName != ByExistingKeyVault)
            {
                var resourceGroup = SafeGetResource(
                    () => this.ResourceManagerClient.ResourceGroups.Get(
                        this.KeyVaultResourceGroupName),
                    true);

                if (resourceGroup == null)
                {
                    this.ResourceManagerClient.ResourceGroups.CreateOrUpdate(
                        this.KeyVaultResourceGroupName,
                        new ResourceGroup()
                    {
                        Location = this.KeyVaultResourceGroupLocation
                    });
                }
            }

            switch (ParameterSetName)
            {
            case ByNewPfxAndVaultName:
            case ByDefaultArmTemplate:
            {
                string            thumbprint        = null;
                Vault             vault             = null;
                CertificateBundle certificateBundle = null;
                string            pfxOutputPath     = null;
                string            commonName        = null;
                GetKeyVaultReady(out vault, out certificateBundle, out thumbprint, out pfxOutputPath, out commonName, null);

                certificateInformations.Add(new CertificateInformation()
                    {
                        KeyVault              = vault,
                        Certificate           = certificateBundle.Cer == null ? null : new X509Certificate2(certificateBundle.Cer),
                        SecretUrl             = certificateBundle.SecretIdentifier.Identifier,
                        CertificateUrl        = certificateBundle.CertificateIdentifier.Identifier,
                        CertificateName       = certificateBundle.CertificateIdentifier.Name,
                        CertificateThumbprint = thumbprint,
                        SecretName            = certificateBundle.SecretIdentifier.Name,
                        Version = certificateBundle.SecretIdentifier.Version,
                        CertificateOutputPath = pfxOutputPath
                    });

                return(certificateInformations);
            }

            case ByExistingPfxAndVaultName:
            {
                var sourcePfxPath = GetPfxSrcFiles();
                foreach (var srcPfx in sourcePfxPath)
                {
                    Vault             vault             = null;
                    CertificateBundle certificateBundle = null;
                    string            thumbprint        = null;
                    string            pfxOutputPath     = null;
                    string            commonName        = null;
                    GetKeyVaultReady(out vault, out certificateBundle, out thumbprint, out pfxOutputPath, out commonName, srcPfx);

                    certificateInformations.Add(new CertificateInformation()
                        {
                            KeyVault    = vault,
                            Certificate =
                                certificateBundle.Cer == null
                                        ? null
                                        : new X509Certificate2(certificateBundle.Cer),
                            CertificateUrl        = certificateBundle.CertificateIdentifier.Identifier,
                            CertificateName       = certificateBundle.CertificateIdentifier.Name,
                            SecretUrl             = certificateBundle.SecretIdentifier.Identifier,
                            CertificateThumbprint = thumbprint,
                            CertificateCommonName = commonName,
                            SecretName            = certificateBundle.SecretIdentifier.Name,
                            Version = certificateBundle.SecretIdentifier.Version
                        });
                }

                return(certificateInformations);
            }

            case ByExistingKeyVault:
            {
                CertificateInformation certInfor = GetCertificateInforamtionFromSecret(this.SecretIdentifier);
                certificateInformations.Add(certInfor);

                return(certificateInformations);
            }

            default:
                throw new PSArgumentException("Invalid ParameterSetName");
            }
        }
Example #13
0
 public EmailService(EmailCredentials credentials, CertificateInformation information = null, bool useCustomCertificateValidationCallback = false)
 {
     _credentials = credentials;
     _information = information;
     _useCustomCertificateValidationCallback = useCustomCertificateValidationCallback;
 }
Example #14
0
 protected override bool ShouldValidateCertificate(CertificateInformation info)
 {
     return(info.StoreName.Equals(StoreName.My.ToString()));
 }