Exemple #1
0
        public async Task <List <CertificateInstallModel> > RenewCertificate(bool skipInstallCertificate = false, int renewXNumberOfDaysBeforeExpiration = 0)
        {
            Trace.TraceInformation("Checking certificate");
            var ss = SettingsStore.Instance.Load();

            using (var client = await ArmHelper.GetWebSiteManagementClient(settings))
                using (var httpClient = await ArmHelper.GetHttpClient(settings))
                {
                    var retryPolicy = ArmHelper.ExponentialBackoff();
                    var body        = string.Empty;
                    //Cant just get certificates by resource group, because sites that have been moved, have their certs sitting in the old RG.
                    //Also cant use client.Certificates.List() due to bug in the nuget
                    var response = await retryPolicy.ExecuteAsync(async() =>
                    {
                        return(await httpClient.GetAsync($"/subscriptions/{settings.SubscriptionId}/providers/Microsoft.Web/certificates?api-version=2016-03-01"));
                    });

                    response.EnsureSuccessStatusCode();
                    body = await response.Content.ReadAsStringAsync();

                    IEnumerable <Certificate> certs = ExtractCertificates(body);

                    var expiringCerts = certs.Where(s => s.ExpirationDate < DateTime.UtcNow.AddDays(renewXNumberOfDaysBeforeExpiration) && (s.Issuer.Contains("Let's Encrypt") || s.Issuer.Contains("Fake LE")));

                    if (expiringCerts.Count() == 0)
                    {
                        Trace.TraceInformation(string.Format("No certificates installed issued by Let's Encrypt that are about to expire within the next {0} days. Skipping.", renewXNumberOfDaysBeforeExpiration));
                    }
                    var res = new List <CertificateInstallModel>();
                    foreach (var toExpireCert in expiringCerts)
                    {
                        Trace.TraceInformation("Starting renew of certificate " + toExpireCert.Name + " expiration date " + toExpireCert.ExpirationDate);
                        var site      = client.WebApps.GetSiteOrSlot(settings.ResourceGroupName, settings.WebAppName, settings.SiteSlotName);
                        var sslStates = site.HostNameSslStates.Where(s => s.Thumbprint == toExpireCert.Thumbprint);
                        if (!sslStates.Any())
                        {
                            Trace.TraceInformation(String.Format("Certificate {0} was not assigned any hostname, skipping update", toExpireCert.Thumbprint));
                            continue;
                        }
                        var target = new AcmeConfig()
                        {
                            RegistrationEmail = this.acmeConfig.RegistrationEmail ?? ss.FirstOrDefault(s => s.Name == "email").Value,
                            Host           = sslStates.First().Name,
                            BaseUri        = this.acmeConfig.BaseUri,
                            UseProduction  = !bool.Parse(ss.FirstOrDefault(s => s.Name == "useStaging")?.Value ?? false.ToString()),
                            AlternateNames = sslStates.Skip(1).Select(s => s.Name).ToList(),
                            PFXPassword    = this.acmeConfig.PFXPassword,
                            RSAKeyLength   = this.acmeConfig.RSAKeyLength
                        };
                        if (!skipInstallCertificate)
                        {
                            res.Add(await RequestAndInstallInternalAsync(target));
                        }
                    }
                    return(res);
                }
        }
        /// <summary>
        /// Used for automatic installation of letsencrypt certificate
        /// </summary>
        public async Task <CertificateInstallModel> AddCertificate()
        {
            Trace.TraceInformation("Staring add certificate");
            using (var client = ArmHelper.GetWebSiteManagementClient(settings))
            {
                Trace.TraceInformation($"Add certificate for acmeConfig hostname {string.Join(", ", acmeConfig.Hostnames)}");

                if (acmeConfig.Hostnames.Any())
                {
                    return(await RequestAndInstallInternalAsync(this.acmeConfig));
                }
                else
                {
                    Trace.TraceWarning("No hostnames found in configuration cannot add certificate automatically. Please run the manual configuration, or provide the all required app settings for automated deployment and delete firstrun.job in letsencrypt in the blob storage account to enable the job to be rerun.");
                }
            }
            return(null);
        }