/// <summary> /// Request certificate from the ACME server /// </summary> /// <param name="binding"></param> /// <returns></returns> public CertificateInfo RequestCertificate(ICsrPlugin csrPlugin, RunLevel runLevel, Renewal renewal, Target target, OrderDetails order) { // What are we going to get? var pfxFileInfo = new FileInfo(PfxFilePath(renewal)); // Determine/check the common name var identifiers = target.GetHosts(false); var commonNameUni = target.CommonName; var commonNameAscii = string.Empty; if (!string.IsNullOrWhiteSpace(commonNameUni)) { var idn = new IdnMapping(); commonNameAscii = idn.GetAscii(commonNameUni); if (!identifiers.Contains(commonNameAscii, StringComparer.InvariantCultureIgnoreCase)) { _log.Warning($"Common name {commonNameUni} provided is invalid."); commonNameAscii = identifiers.First(); commonNameUni = idn.GetUnicode(commonNameAscii); } } // Determine the friendly name var friendlyName = renewal.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) { friendlyName = target.FriendlyName; } if (string.IsNullOrEmpty(friendlyName)) { friendlyName = commonNameUni; } // Try using cached certificate first to avoid rate limiting during // (initial?) deployment troubleshooting. Real certificate requests // will only be done once per day maximum unless the --force parameter // is used. var cache = CachedInfo(renewal); if (cache != null && cache.CacheFile.LastWriteTime > DateTime.Now.AddDays(Settings.Default.CertificateCacheDays * -1) && cache.Match(target)) { if (runLevel.HasFlag(RunLevel.IgnoreCache)) { _log.Warning("Cached certificate available but not used with --{switch}. Use 'Renew specific' or " + "'Renew all' in the main menu to run unscheduled renewals without hitting rate limits.", nameof(MainArguments.Force).ToLower()); } else { _log.Warning("Using cached certificate for {friendlyName}. To force issue of a new certificate within " + "24 hours, delete the .pfx file from the CertificatePath or run with the --{switch} switch. " + "Be ware that you might run into rate limits doing so.", friendlyName, nameof(MainArguments.Force).ToLower()); return(cache); } } var csr = csrPlugin.GenerateCsr(commonNameAscii, identifiers); var csrBytes = csr.CreateSigningRequest(); order = _client.SubmitCsr(order, csrBytes); File.WriteAllText(GetPath(renewal, "-csr.pem"), _pemService.GetPem("CERTIFICATE REQUEST", csrBytes)); _log.Information("Requesting certificate {friendlyName}", friendlyName); var rawCertificate = _client.GetCertificate(order); if (rawCertificate == null) { throw new Exception($"Unable to get certificate"); } var certificate = new X509Certificate2(rawCertificate); var certificateExport = certificate.Export(X509ContentType.Cert); var crtPem = _pemService.GetPem("CERTIFICATE", certificateExport); // Get issuer certificate var issuerCertificate = new X509Certificate2(rawCertificate.Skip(certificateExport.Length).ToArray()); var issuerCertificateExport = issuerCertificate.Export(X509ContentType.Cert); var issuerPem = _pemService.GetPem("CERTIFICATE", issuerCertificateExport); // Build pfx archive var pfx = new bc.Pkcs.Pkcs12Store(); var bcCertificate = _pemService.ParsePem <bc.X509.X509Certificate>(crtPem); var bcCertificateEntry = new bc.Pkcs.X509CertificateEntry(bcCertificate); var bcCertificateAlias = bcCertificate.SubjectDN.ToString(); var bcPrivateKeyEntry = new bc.Pkcs.AsymmetricKeyEntry(csrPlugin.GetPrivateKey()); pfx.SetCertificateEntry(bcCertificateAlias, bcCertificateEntry); pfx.SetKeyEntry(bcCertificateAlias, bcPrivateKeyEntry, new[] { bcCertificateEntry }); var bcIssuer = _pemService.ParsePem <bc.X509.X509Certificate>(issuerPem); var bcIssuerEntry = new bc.Pkcs.X509CertificateEntry(bcIssuer); var bcIssuerAlias = bcIssuer.SubjectDN.ToString(); pfx.SetCertificateEntry(bcIssuerAlias, bcIssuerEntry); var pfxStream = new MemoryStream(); pfx.Save(pfxStream, null, new bc.Security.SecureRandom()); pfxStream.Position = 0; using (var pfxStreamReader = new BinaryReader(pfxStream)) { var tempPfx = new X509Certificate2( pfxStreamReader.ReadBytes((int)pfxStream.Length), (string)null, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); if (csrPlugin.CanConvert()) { try { var converted = csrPlugin.Convert(tempPfx.PrivateKey); if (converted != null) { tempPfx.PrivateKey = converted; } } catch { _log.Warning("Private key conversion error."); } } tempPfx.FriendlyName = $"{friendlyName} {DateTime.Now.ToUserString()}"; File.WriteAllBytes(pfxFileInfo.FullName, tempPfx.Export(X509ContentType.Pfx, renewal.PfxPassword?.Value)); pfxFileInfo.Refresh(); } // Update LastFriendlyName so that the user sees // the most recently issued friendlyName in // the WACS GUI renewal.LastFriendlyName = friendlyName; // Recreate X509Certificate2 with correct flags for Store/Install return(new CertificateInfo() { Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword?.Value), CacheFile = pfxFileInfo, CacheFilePassword = renewal.PfxPassword?.Value }); }
/// <summary> /// Request certificate from the ACME server /// </summary> /// <param name="binding"></param> /// <returns></returns> public CertificateInfo RequestCertificate(ICsrPlugin csrPlugin, Renewal renewal, Target target, OrderDetails order) { // What are we going to get? var pfxFileInfo = new FileInfo(PfxFilePath(renewal)); // Determine/check the common name var identifiers = target.GetHosts(false); var commonName = target.CommonName; if (!string.IsNullOrWhiteSpace(commonName)) { var idn = new IdnMapping(); commonName = idn.GetAscii(commonName); if (!identifiers.Contains(commonName, StringComparer.InvariantCultureIgnoreCase)) { _log.Warning($"Common name {commonName} provided is invalid."); commonName = identifiers.First(); } } // Try using cached certificate first to avoid rate limiting during // (initial?) deployment troubleshooting. Real certificate requests // will only be done once per day maximum. if (pfxFileInfo.Exists && pfxFileInfo.LastWriteTime > DateTime.Now.AddDays(-1)) { try { var cached = new CertificateInfo() { Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword), PfxFile = pfxFileInfo }; var idn = new IdnMapping(); if (cached.SubjectName == commonName && cached.HostNames.Count == identifiers.Count() && cached.HostNames.All(h => identifiers.Contains(idn.GetAscii(h)))) { if (_options.Force) { _log.Warning("Cached certificate available but not used with --{switch}. Use 'Renew specific' or 'Renew all' in the main menu to run unscheduled renewals without hitting rate limits.", nameof(MainArguments.Force).ToLower()); } else { _log.Warning("Using cached certificate for {friendlyName}. To force issue of a new certificate within 24 hours, delete the .pfx file from the CertificatePath or run with the --{switch} switch. Be ware that you might run into rate limits doing so.", renewal.FriendlyName, nameof(MainArguments.Force).ToLower()); return(cached); } } } catch { // File corrupt or invalid password? _log.Warning("Unable to read from certificate cache"); } } var csr = csrPlugin.GenerateCsr(commonName, identifiers); var csrBytes = csr.CreateSigningRequest(); order = _client.SubmitCsr(order, csrBytes); if (Settings.Default.SavePrivateKeyPem) { File.WriteAllText(GetPath(renewal, "-key.pem"), GetPem(csrPlugin.GeneratePrivateKey())); } File.WriteAllText(GetPath(renewal, "-csr.pem"), GetPem("CERTIFICATE REQUEST", csrBytes)); _log.Information("Requesting certificate {friendlyName}", renewal.FriendlyName); var rawCertificate = _client.GetCertificate(order); if (rawCertificate == null) { throw new Exception($"Unable to get certificate"); } var certificate = new X509Certificate2(rawCertificate); var certificateExport = certificate.Export(X509ContentType.Cert); var crtDerFile = GetPath(renewal, $"-crt.der"); var crtPemFile = GetPath(renewal, $"-crt.pem"); var crtPem = GetPem("CERTIFICATE", certificateExport); _log.Information("Saving certificate to {crtDerFile}", _certificatePath); File.WriteAllBytes(crtDerFile, certificateExport); File.WriteAllText(crtPemFile, crtPem); // Get issuer certificate and save in DER and PEM formats var chain = new X509Chain(); chain.Build(certificate); X509Certificate2 issuerCertificate = chain.ChainElements[1].Certificate; var issuerCertificateExport = issuerCertificate.Export(X509ContentType.Cert); var issuerPem = GetPem("CERTIFICATE", issuerCertificateExport); File.WriteAllBytes(GetPath(renewal, "-crt.der", "ca-"), issuerCertificateExport); File.WriteAllText(GetPath(renewal, "-crt.pem", "ca-"), issuerPem); // Generate combined files File.WriteAllText(GetPath(renewal, "-chain.pem", "ca-"), crtPem + issuerPem); // Build pfx archive var pfx = new bc.Pkcs.Pkcs12Store(); var bcCertificate = ParsePem <bc.X509.X509Certificate>(crtPem); var bcCertificateEntry = new bc.Pkcs.X509CertificateEntry(bcCertificate); var bcCertificateAlias = bcCertificate.SubjectDN.ToString(); var bcPrivateKeyEntry = new bc.Pkcs.AsymmetricKeyEntry(csrPlugin.GeneratePrivateKey()); pfx.SetCertificateEntry(bcCertificateAlias, bcCertificateEntry); pfx.SetKeyEntry(bcCertificateAlias, bcPrivateKeyEntry, new[] { bcCertificateEntry }); var bcIssuer = ParsePem <bc.X509.X509Certificate>(issuerPem); var bcIssuerEntry = new bc.Pkcs.X509CertificateEntry(bcIssuer); var bcIssuerAlias = bcIssuer.SubjectDN.ToString(); pfx.SetCertificateEntry(bcIssuerAlias, bcIssuerEntry); using (var pfxStream = new MemoryStream()) { pfx.Save(pfxStream, null, new bc.Security.SecureRandom()); pfxStream.Position = 0; using (var pfxStreamReader = new BinaryReader(pfxStream)) { var tempPfx = new X509Certificate2( pfxStreamReader.ReadBytes((int)pfxStream.Length), (string)null, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); if (csrPlugin.CanConvert()) { try { var converted = csrPlugin.Convert(tempPfx.PrivateKey); if (converted != null) { tempPfx.PrivateKey = converted; } } catch { _log.Warning("Private key conversion error."); } } tempPfx.FriendlyName = FriendlyName(renewal); File.WriteAllBytes(pfxFileInfo.FullName, tempPfx.Export(X509ContentType.Pfx, renewal.PfxPassword)); pfxFileInfo.Refresh(); } } // Recreate X509Certificate2 with correct flags for Store/Install return(new CertificateInfo() { Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword), PfxFile = pfxFileInfo }); }