Ejemplo n.º 1
0
        private static CertificateProvider GetCP()
        {
            CertificateProvider.RegisterProvider <ACMESharp.PKI.Providers.OpenSslCliProvider>();
            //CertificateProvider.RegisterProvider<ACMESharp.PKI.Providers.CertEnrollProvider>();

            return(CertificateProvider.GetProvider());
        }
Ejemplo n.º 2
0
        public string GetCertificate(AcmeClient client)
        {
            IdnMapping idn           = new IdnMapping();
            var        dnsIdentifier = idn.GetAscii(config.Host);

            CertificateProvider.RegisterProvider <BouncyCastleProvider>(BouncyCastleProvider.PROVIDER_NAME);
            var cp     = CertificateProvider.GetProvider(BouncyCastleProvider.PROVIDER_NAME);
            var rsaPkp = new RsaPrivateKeyParams();

            try
            {
                if (config.RSAKeyLength >= 1024)
                {
                    rsaPkp.NumBits = config.RSAKeyLength;
                    Trace.TraceInformation("RSAKeyBits: {0}", config.RSAKeyLength);
                }
                else
                {
                    Trace.TraceWarning("RSA Key Bits less than 1024 is not secure. Letting ACMESharp default key bits. http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {0}", ex);
                Console.WriteLine($"Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {ex.Message.ToString()}");
            }

            var rsaKeys    = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails
            {
                CommonName = dnsIdentifier,
            };

            if (config.AlternateNames != null)
            {
                if (config.AlternateNames.Count > 0)
                {
                    csrDetails.AlternativeNames = config.AlternateNames.Select(s => idn.GetAscii(s));
                }
            }
            var csrParams = new CsrParams
            {
                Details = csrDetails,
            };
            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }
            var derB64u = JwsHelper.Base64UrlEncode(derRaw);

            Console.WriteLine($"\nRequesting Certificate");
            Trace.TraceInformation("Requesting Certificate");
            CertificateRequest certRequ = client.RequestCertificate(derB64u);

            Trace.TraceInformation("certRequ {0}", JsonConvert.SerializeObject(certRequ));

            Console.WriteLine($" Request Status: {certRequ.StatusCode}");
            Trace.TraceInformation("Request Status: {0}", certRequ.StatusCode);

            if (certRequ.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var    keyGenFile = Path.Combine(this.configPath, $"{dnsIdentifier}-gen-key.json");
                var    keyPemFile = Path.Combine(configPath, $"{dnsIdentifier}-key.pem");
                var    csrGenFile = Path.Combine(configPath, $"{dnsIdentifier}-gen-csr.json");
                var    csrPemFile = Path.Combine(configPath, $"{dnsIdentifier}-csr.pem");
                var    crtDerFile = Path.Combine(configPath, $"{dnsIdentifier}-crt.der");
                var    crtPemFile = Path.Combine(configPath, $"{dnsIdentifier}-crt.pem");
                string crtPfxFile = null;

                crtPfxFile = Path.Combine(configPath, $"{dnsIdentifier}-all.pfx");



                using (var fs = new FileStream(keyGenFile, FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (var fs = new FileStream(keyPemFile, FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (var fs = new FileStream(csrGenFile, FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (var fs = new FileStream(csrPemFile, FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Console.WriteLine($" Saving Certificate to {crtDerFile}");
                Trace.TraceInformation("Saving Certificate to {0}", crtDerFile);
                using (var file = File.Create(crtDerFile))
                    certRequ.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                       target = new FileStream(crtPemFile, FileMode.Create))
                {
                    crt = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                }

                // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate
                var isuPemFile = GetIssuerCertificate(certRequ, cp);



                Console.WriteLine($" Saving Certificate to {crtPfxFile}");
                Trace.TraceInformation("Saving Certificate to {0}", crtPfxFile);
                using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                       target = new FileStream(crtPfxFile, FileMode.Create))
                {
                    try
                    {
                        var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                        cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, config.PFXPassword);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error exporting archive {0}", ex);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Error exporting archive: {ex.Message.ToString()}");
                        Console.ResetColor();
                    }
                }


                cp.Dispose();

                return(crtPfxFile);
            }
            if ((int)certRequ.StatusCode == 429)
            {
                Trace.TraceError("Unable to request certificate, too many certificate requests to Let's Encrypt certificate servers for the domain within the last 7 days. Please try again later. (If you are testing, please use the staging enviroment where you can request unlimited number of certificates. During the beta period only 5 certificate requests per domain per week are allowed to the production environment.)");
                throw new Exception("Unable to request certificate, too many certificate requests to Let's Encrypt certificate servers for the domain within the last 7 days. Please try again later. (If you are testing, please use the staging enviroment where you can request unlimited number of certificates. During the beta period only 5 certificate requests per domain per week are allowed to the production environment.)");
            }

            Trace.TraceError("Request status = {0}", certRequ.StatusCode);
            throw new Exception($"Request status = {certRequ.StatusCode}");
        }
        /// <summary>
        /// Generate a certificate request
        /// </summary>
        /// <param name="certificatename"></param>
        /// <param name="mainhost">Main host: www.google.com</param>
        /// <param name="certificatePath">Path to store the generated certificates</param>
        /// <param name="alternatehosts">Alterante hosts: list of alterante hosts for this certificate</param>
        /// <returns></returns>
        public CertificatePaths DownloadCertificate(
            string certificatename,
            string mainhost,
            string certificatePath,
            List <string> alternatehosts = null)
        {
            if (alternatehosts != null && alternatehosts.Any())
            {
                throw new NotSupportedException("Alternate host provisioning not supported yet.");
            }

            List <string> allDnsIdentifiers = new List <string>()
            {
                mainhost
            };

            if (alternatehosts != null)
            {
                allDnsIdentifiers.AddRange(alternatehosts);
            }

            // Tomado de app.config
            var rsaKeyBits = 2048; // 1024;//

            if (Environment.Is64BitProcess)
            {
                CertificateProvider.RegisterProvider(typeof(ACMESharp.PKI.Providers.OpenSslLib64Provider));
            }
            else
            {
                CertificateProvider.RegisterProvider(typeof(ACMESharp.PKI.Providers.OpenSslLib32Provider));
            }

            var cp     = CertificateProvider.GetProvider();
            var rsaPkp = new RsaPrivateKeyParams();

            try
            {
                if (rsaKeyBits >= 1024)
                {
                    rsaPkp.NumBits = rsaKeyBits;

                    // Log.Debug("RSAKeyBits: {RSAKeyBits}", Properties.Settings.Default.RSAKeyBits);
                }
                else
                {
                    // Log.Warning(
                    //    "RSA Key Bits less than 1024 is not secure. Letting ACMESharp default key bits. http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html");
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogInfo(true, $"Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {ex.Message.ToString()}");
            }

            var rsaKeys    = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails
            {
                CommonName = allDnsIdentifiers[0]
            };

            if (alternatehosts != null)
            {
                if (alternatehosts.Count > 0)
                {
                    csrDetails.AlternativeNames = alternatehosts;
                }
            }

            var csrParams = new CsrParams
            {
                Details = csrDetails,
            };

            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }

            var derB64U = JwsHelper.Base64UrlEncode(derRaw);

            this.Logger.LogInfo(true, $"Requesting Certificate");

            // Log.Information("Requesting Certificate");
            var certRequ = this.AcmeClient.RequestCertificate(derB64U);

            // Log.Debug("certRequ {@certRequ}", certRequ);

            this.Logger.LogInfo(true, $"Request Status: {certRequ.StatusCode}");

            if (certRequ.StatusCode != System.Net.HttpStatusCode.Created)
            {
                throw new Exception($"Could not create certificate request, response code: = {certRequ.StatusCode}");
            }

            var keyGenFile   = Path.Combine(certificatePath, $"{certificatename}-gen-key.json");
            var keyPemFile   = Path.Combine(certificatePath, $"{certificatename}-key.pem");
            var csrGenFile   = Path.Combine(certificatePath, $"{certificatename}-gen-csr.json");
            var csrPemFile   = Path.Combine(certificatePath, $"{certificatename}-csr.pem");
            var crtDerFile   = Path.Combine(certificatePath, $"{certificatename}-crt.der");
            var crtPemFile   = Path.Combine(certificatePath, $"{certificatename}-crt.pem");
            var chainPemFile = Path.Combine(certificatePath, $"{certificatename}-chain.pem");
            var pfxPemFile   = Path.Combine(certificatePath, $"{certificatename}.pfx");

            using (var fs = new FileStream(keyGenFile, FileMode.Create))
            {
                cp.SavePrivateKey(rsaKeys, fs);
            }

            using (var fs = new FileStream(keyPemFile, FileMode.Create))
            {
                cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
            }

            using (var fs = new FileStream(csrGenFile, FileMode.Create))
            {
                cp.SaveCsr(csr, fs);
            }

            using (var fs = new FileStream(csrPemFile, FileMode.Create))
            {
                cp.ExportCsr(csr, EncodingFormat.PEM, fs);
            }

            this.Logger.LogInfo(true, $"Saving Certificate to {crtDerFile}");

            // Log.Information("Saving Certificate to {crtDerFile}", crtDerFile);
            using (var file = File.Create(crtDerFile))
            {
                certRequ.SaveCertificate(file);
            }

            Crt crt;

            using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                   target = new FileStream(crtPemFile, FileMode.Create))
            {
                crt = cp.ImportCertificate(EncodingFormat.DER, source);
                cp.ExportCertificate(crt, EncodingFormat.PEM, target);
            }

            cp.Dispose();

            var ret = new CertificatePaths()
            {
                chainPemFile = chainPemFile,
                crtDerFile   = crtDerFile,
                crtPemFile   = crtPemFile,
                csrGenFile   = csrGenFile,
                csrPemFile   = csrPemFile,
                keyGenFile   = keyGenFile,
                keyPemFile   = keyPemFile,
                name         = certificatename,
                pfxPemFile   = pfxPemFile
            };

            // Generate the PFX version manually
            UtilsCertificate.CreatePfXfromPem(ret.crtPemFile, ret.keyPemFile, ret.pfxPemFile, null);

            return(ret);
        }